@reclaimprotocol/js-sdk 4.6.5 → 4.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -1
- package/dist/index.d.ts +38 -0
- package/dist/index.js +20 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -349,7 +349,7 @@ The Reclaim SDK offers several advanced options to customize your integration:
|
|
|
349
349
|
useBrowserExtension: true, // Enable browser extension support (default: true)
|
|
350
350
|
extensionID: "custom-extension-id", // Custom extension identifier
|
|
351
351
|
useAppClip: true, // Enable mobile app clips (default: true)
|
|
352
|
-
log: true, // Enable logging for debugging
|
|
352
|
+
log: true, // Enable troubleshooting mode and more verbose logging for debugging
|
|
353
353
|
});
|
|
354
354
|
```
|
|
355
355
|
|
|
@@ -403,6 +403,32 @@ const sessionId = reclaimProofRequest.getSessionId();
|
|
|
403
403
|
console.log("Current session ID:", sessionId);
|
|
404
404
|
```
|
|
405
405
|
|
|
406
|
+
11. **Control auto-submission of proofs**:
|
|
407
|
+
|
|
408
|
+
Whether the verification client should automatically submit necessary proofs once they are generated. If set to false, the user must manually click a button to submit.
|
|
409
|
+
Defaults to true.
|
|
410
|
+
|
|
411
|
+
```js
|
|
412
|
+
// Initialize with options
|
|
413
|
+
const proofRequest = await ReclaimProofRequest.init(APP_ID, APP_SECRET, PROVIDER_ID, {
|
|
414
|
+
canAutoSubmit: true,
|
|
415
|
+
});
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
12. **Add additional metadata for verification client**:
|
|
419
|
+
|
|
420
|
+
Additional metadata to pass to the verification client. This can be used to customize the client experience, such as customizing themes or UI by passing context-specific information.
|
|
421
|
+
The keys and values must be strings. For most clients, this is not required and goes unused.
|
|
422
|
+
|
|
423
|
+
This has no effect on the verification process.
|
|
424
|
+
|
|
425
|
+
```js
|
|
426
|
+
// Initialize with options
|
|
427
|
+
const proofRequest = await ReclaimProofRequest.init(APP_ID, APP_SECRET, PROVIDER_ID, {
|
|
428
|
+
metadata: { theme: 'dark', verify_another_way_link: 'https://exampe.org/alternative-verification?id=1234' },
|
|
429
|
+
});
|
|
430
|
+
```
|
|
431
|
+
|
|
406
432
|
## Handling Proofs on Your Backend
|
|
407
433
|
|
|
408
434
|
For production applications, it's recommended to handle proofs on your backend:
|
package/dist/index.d.ts
CHANGED
|
@@ -56,7 +56,13 @@ type StartSessionParams = {
|
|
|
56
56
|
type OnSuccess = (proof?: Proof | Proof[] | string) => void;
|
|
57
57
|
type OnError = (error: Error) => void;
|
|
58
58
|
type ProofRequestOptions = {
|
|
59
|
+
/**
|
|
60
|
+
* Enables troubleshooting mode and more verbose logging
|
|
61
|
+
*/
|
|
59
62
|
log?: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Accepts AI providers in the verification flow
|
|
65
|
+
*/
|
|
60
66
|
acceptAiProviders?: boolean;
|
|
61
67
|
useAppClip?: boolean;
|
|
62
68
|
device?: string;
|
|
@@ -67,6 +73,26 @@ type ProofRequestOptions = {
|
|
|
67
73
|
customSharePageUrl?: string;
|
|
68
74
|
customAppClipUrl?: string;
|
|
69
75
|
launchOptions?: ReclaimFlowLaunchOptions;
|
|
76
|
+
/**
|
|
77
|
+
* Whether the verification client should automatically submit necessary proofs once they are generated.
|
|
78
|
+
* If set to false, the user must manually click a button to submit.
|
|
79
|
+
*
|
|
80
|
+
* @since 4.7.0
|
|
81
|
+
* @default true
|
|
82
|
+
*/
|
|
83
|
+
canAutoSubmit?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Additional metadata to pass to the verification client.
|
|
86
|
+
* This can be used to customize the client experience, such as customizing themes or UI by passing context-specific information.
|
|
87
|
+
* The keys and values must be strings. For most clients, this is not required and goes unused.
|
|
88
|
+
*
|
|
89
|
+
* This has no effect on the verification process.
|
|
90
|
+
*
|
|
91
|
+
* Example: `{ theme: 'dark', verify_another_way_link: 'https://exampe.org/alternative-verification?id=1234' }`
|
|
92
|
+
*
|
|
93
|
+
* @since 4.7.0
|
|
94
|
+
*/
|
|
95
|
+
metadata?: Record<string, string>;
|
|
70
96
|
};
|
|
71
97
|
type ReclaimFlowLaunchOptions = {
|
|
72
98
|
/**
|
|
@@ -524,6 +550,18 @@ declare class ReclaimProofRequest {
|
|
|
524
550
|
* ```
|
|
525
551
|
*/
|
|
526
552
|
closeModal(): void;
|
|
553
|
+
/**
|
|
554
|
+
* Returns whether proofs will be submitted as JSON format
|
|
555
|
+
*
|
|
556
|
+
* @returns boolean - True if proofs are sent as application/json, false for application/x-www-form-urlencoded
|
|
557
|
+
*
|
|
558
|
+
* @example
|
|
559
|
+
* ```typescript
|
|
560
|
+
* const isJson = proofRequest.getJsonProofResponse();
|
|
561
|
+
* console.log('JSON format:', isJson);
|
|
562
|
+
* ```
|
|
563
|
+
*/
|
|
564
|
+
getJsonProofResponse(): boolean;
|
|
527
565
|
}
|
|
528
566
|
|
|
529
567
|
/**
|
package/dist/index.js
CHANGED
|
@@ -72,7 +72,7 @@ var require_package = __commonJS({
|
|
|
72
72
|
"package.json"(exports2, module2) {
|
|
73
73
|
module2.exports = {
|
|
74
74
|
name: "@reclaimprotocol/js-sdk",
|
|
75
|
-
version: "4.
|
|
75
|
+
version: "4.7.0",
|
|
76
76
|
description: "Designed to request proofs from the Reclaim protocol and manage the flow of claims and witness interactions.",
|
|
77
77
|
main: "dist/index.js",
|
|
78
78
|
types: "dist/index.d.ts",
|
|
@@ -1882,7 +1882,7 @@ var ReclaimProofRequest = class _ReclaimProofRequest {
|
|
|
1882
1882
|
* @returns
|
|
1883
1883
|
*/
|
|
1884
1884
|
this.getTemplateData = () => {
|
|
1885
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
1885
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
1886
1886
|
if (!this.signature) {
|
|
1887
1887
|
throw new SignatureNotFoundError("Signature is not set.");
|
|
1888
1888
|
}
|
|
@@ -1902,7 +1902,9 @@ var ReclaimProofRequest = class _ReclaimProofRequest {
|
|
|
1902
1902
|
acceptAiProviders: (_f = (_e = this.options) == null ? void 0 : _e.acceptAiProviders) != null ? _f : false,
|
|
1903
1903
|
sdkVersion: this.sdkVersion,
|
|
1904
1904
|
jsonProofResponse: this.jsonProofResponse,
|
|
1905
|
-
log: (_h = (_g = this.options) == null ? void 0 : _g.log) != null ? _h : false
|
|
1905
|
+
log: (_h = (_g = this.options) == null ? void 0 : _g.log) != null ? _h : false,
|
|
1906
|
+
canAutoSubmit: (_j = (_i = this.options) == null ? void 0 : _i.canAutoSubmit) != null ? _j : true,
|
|
1907
|
+
metadata: (_k = this.options) == null ? void 0 : _k.metadata
|
|
1906
1908
|
};
|
|
1907
1909
|
return templateData;
|
|
1908
1910
|
};
|
|
@@ -2127,6 +2129,7 @@ var ReclaimProofRequest = class _ReclaimProofRequest {
|
|
|
2127
2129
|
proofRequestInstance.sdkVersion = sdkVersion2;
|
|
2128
2130
|
proofRequestInstance.resolvedProviderVersion = resolvedProviderVersion;
|
|
2129
2131
|
proofRequestInstance.modalOptions = modalOptions;
|
|
2132
|
+
proofRequestInstance.jsonProofResponse = jsonProofResponse != null ? jsonProofResponse : false;
|
|
2130
2133
|
return proofRequestInstance;
|
|
2131
2134
|
} catch (error) {
|
|
2132
2135
|
logger7.info("Failed to parse JSON string in fromJsonString:", error);
|
|
@@ -2842,6 +2845,20 @@ var ReclaimProofRequest = class _ReclaimProofRequest {
|
|
|
2842
2845
|
logger7.info("Modal closed by user");
|
|
2843
2846
|
}
|
|
2844
2847
|
}
|
|
2848
|
+
/**
|
|
2849
|
+
* Returns whether proofs will be submitted as JSON format
|
|
2850
|
+
*
|
|
2851
|
+
* @returns boolean - True if proofs are sent as application/json, false for application/x-www-form-urlencoded
|
|
2852
|
+
*
|
|
2853
|
+
* @example
|
|
2854
|
+
* ```typescript
|
|
2855
|
+
* const isJson = proofRequest.getJsonProofResponse();
|
|
2856
|
+
* console.log('JSON format:', isJson);
|
|
2857
|
+
* ```
|
|
2858
|
+
*/
|
|
2859
|
+
getJsonProofResponse() {
|
|
2860
|
+
return this.jsonProofResponse;
|
|
2861
|
+
}
|
|
2845
2862
|
};
|
|
2846
2863
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2847
2864
|
0 && (module.exports = {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../src/index.ts","../src/utils/interfaces.ts","../src/witness.ts","../src/utils/strings.ts","../src/utils/types.ts","../src/Reclaim.ts","../src/utils/errors.ts","../src/utils/logger.ts","../src/utils/helper.ts","../src/utils/constants.ts","../src/utils/validationUtils.ts","../src/utils/sessionUtils.ts","../src/utils/proofUtils.ts","../src/contract-types/contracts/factories/Reclaim__factory.ts","../src/contract-types/config.json","../src/smart-contract.ts","../src/utils/modalUtils.ts","../src/utils/device.ts"],"sourcesContent":["{\n \"name\": \"@reclaimprotocol/js-sdk\",\n \"version\": \"4.6.5\",\n \"description\": \"Designed to request proofs from the Reclaim protocol and manage the flow of claims and witness interactions.\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"keywords\": [\n \"reclaim\",\n \"protocol\",\n \"blockchain\",\n \"proof\",\n \"verification\",\n \"identity\",\n \"claims\",\n \"witness\",\n \"sdk\",\n \"javascript\",\n \"typescript\",\n \"decentralized\",\n \"web3\"\n ],\n \"files\": [\n \"dist\"\n ],\n \"tsup\": {\n \"entry\": [\n \"src/index.ts\"\n ],\n \"splitting\": false,\n \"sourcemap\": true,\n \"clean\": true\n },\n \"scripts\": {\n \"build\": \"sh scripts/build.sh\",\n \"release\": \"release-it\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:coverage\": \"jest --coverage\",\n \"commitlint\": \"commitlint --edit\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/reclaimprotocol/reclaim-js-sdk\"\n },\n \"author\": \"ali <ali@creatoros.co>\",\n \"license\": \"See License in <https://github.com/reclaimprotocol/.github/blob/main/LICENSE>\",\n \"bugs\": {\n \"url\": \"https://github.com/reclaimprotocol/reclaim-js-sdk/issues\"\n },\n \"homepage\": \"https://github.com/reclaimprotocol/reclaim-js-sdk/\",\n \"publishConfig\": {\n \"registry\": \"https://registry.npmjs.org/\",\n \"access\": \"public\"\n },\n \"release-it\": {\n \"git\": {\n \"commitMessage\": \"chore: release ${version}\",\n \"tagName\": \"v${version}\"\n },\n \"npm\": {\n \"publish\": true,\n \"tag\": \"latest\"\n },\n \"github\": {\n \"release\": true\n },\n \"plugins\": {\n \"@release-it/conventional-changelog\": {\n \"preset\": \"angular\"\n }\n }\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"^17.7.1\",\n \"@commitlint/config-conventional\": \"^17.7.0\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/qs\": \"^6.9.11\",\n \"@types/url-parse\": \"^1.4.11\",\n \"@types/uuid\": \"^9.0.7\",\n \"jest\": \"^30.1.3\",\n \"jest-environment-jsdom\": \"^30.1.2\",\n \"ts-jest\": \"^29.4.1\",\n \"tsup\": \"^8.0.1\",\n \"typescript\": \"^5.3.3\"\n },\n \"dependencies\": {\n \"@release-it/conventional-changelog\": \"^10.0.1\",\n \"canonicalize\": \"^2.0.0\",\n \"ethers\": \"^6.9.1\",\n \"qs\": \"^6.11.2\",\n \"release-it\": \"^19.0.4\",\n \"url-parse\": \"^1.5.10\",\n \"uuid\": \"^9.0.1\"\n },\n \"overrides\": {\n \"@conventional-changelog/git-client\": \"^2.0.0\"\n }\n}\n","export * from './Reclaim';\nexport * from './utils/interfaces';\nexport { ClaimCreationType, ModalOptions, DeviceType, ProofPropertiesJSON } from './utils/types';\n// Export device detection utilities for debugging (optional)\nexport { \n getDeviceType, \n getMobileDeviceType, \n isMobileDevice, \n isDesktopDevice,\n clearDeviceCache \n} from './utils/device';","// Proof-related interfaces\nexport interface Proof {\n identifier: string;\n claimData: ProviderClaimData;\n signatures: string[];\n witnesses: WitnessData[];\n extractedParameterValues: any;\n publicData?: { [key: string]: string };\n taskId?: number;\n}\n\n// Extension Interactions\nexport const RECLAIM_EXTENSION_ACTIONS = {\n CHECK_EXTENSION: 'RECLAIM_EXTENSION_CHECK',\n EXTENSION_RESPONSE: 'RECLAIM_EXTENSION_RESPONSE',\n START_VERIFICATION: 'RECLAIM_START_VERIFICATION',\n STATUS_UPDATE: 'RECLAIM_STATUS_UPDATE',\n};\n\nexport interface ExtensionMessage {\n action: string;\n messageId: string;\n data?: any;\n extensionID?: string;\n}\n\nexport interface WitnessData {\n id: string;\n url: string;\n}\n\nexport interface ProviderClaimData {\n provider: string;\n parameters: string;\n owner: string;\n timestampS: number;\n context: string;\n identifier: string;\n epoch: number;\n}\n\n// Context and Beacon interfaces\nexport interface Context {\n contextAddress: string;\n contextMessage: string;\n}\n\nexport interface Beacon {\n getState(epoch?: number): Promise<BeaconState>;\n close?(): Promise<void>;\n}\n\nexport type BeaconState = {\n witnesses: WitnessData[];\n epoch: number;\n witnessesRequiredForClaim: number;\n nextEpochTimestampS: number;\n};\n\n\n","import { ethers } from 'ethers';\nimport type { WitnessData } from './utils/interfaces';\nimport type { ClaimID, ClaimInfo, CompleteClaimData } from './utils/types';\nimport { canonicalStringify } from './utils/strings';\n\ntype BeaconState = {\n witnesses: WitnessData[];\n epoch: number;\n witnessesRequiredForClaim: number;\n nextEpochTimestampS: number;\n};\n\nexport function fetchWitnessListForClaim(\n { witnesses, witnessesRequiredForClaim, epoch }: BeaconState,\n params: string | ClaimInfo,\n timestampS: number\n): WitnessData[] {\n const identifier: ClaimID =\n typeof params === 'string' ? params : getIdentifierFromClaimInfo(params);\n const completeInput: string = [\n identifier,\n epoch.toString(),\n witnessesRequiredForClaim.toString(),\n timestampS.toString(),\n ].join('\\n');\n const completeHashStr: string = ethers.keccak256(strToUint8Array(completeInput));\n const completeHash: Uint8Array = ethers.getBytes(completeHashStr);\n const completeHashView: DataView = uint8ArrayToDataView(completeHash);\n const witnessesLeft: WitnessData[] = [...witnesses];\n const selectedWitnesses: WitnessData[] = [];\n let byteOffset: number = 0;\n for (let i = 0; i < witnessesRequiredForClaim; i++) {\n const randomSeed: number = completeHashView.getUint32(byteOffset);\n const witnessIndex: number = randomSeed % witnessesLeft.length;\n const witness: WitnessData = witnessesLeft[witnessIndex];\n selectedWitnesses.push(witness);\n\n witnessesLeft[witnessIndex] = witnessesLeft[witnessesLeft.length - 1];\n witnessesLeft.pop();\n byteOffset = (byteOffset + 4) % completeHash.length;\n }\n\n return selectedWitnesses;\n}\n\n\nexport function getIdentifierFromClaimInfo(info: ClaimInfo): ClaimID {\n // re-canonicalize context if it's not empty\n let canonicalContext = info.context || '';\n if (canonicalContext.length > 0) {\n try {\n const ctx = JSON.parse(canonicalContext);\n canonicalContext = canonicalStringify(ctx);\n } catch (e) {\n throw new Error('unable to parse non-empty context. Must be JSON');\n }\n }\n\n const str = `${info.provider}\\n${info.parameters}\\n${canonicalContext}`;\n return ethers.keccak256(strToUint8Array(str)).toLowerCase();\n}\n\nexport function strToUint8Array(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\nexport function uint8ArrayToDataView(arr: Uint8Array): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\nexport function createSignDataForClaim(data: CompleteClaimData): string {\n const identifier: ClaimID =\n 'identifier' in data ? data.identifier : getIdentifierFromClaimInfo(data);\n const lines: string[] = [\n identifier,\n data.owner.toLowerCase(),\n data.timestampS.toString(),\n data.epoch.toString(),\n ];\n\n return lines.join('\\n');\n}\n","import canonicalize from \"canonicalize\"\n\n/**\n * Canonically stringifies an object, so that the same object will always\n * produce the same string despite the order of keys\n */\nexport function canonicalStringify(params: { [key: string]: any } | undefined) {\n\tif(!params) {\n\t\treturn ''\n\t}\n\n\t// have to cast as ESM isn't correctly typing this\n\treturn (canonicalize as unknown as ((p: unknown) => string))(params) || ''\n}","import type { Context, Proof, ProviderClaimData } from './interfaces';\n\n// Claim-related types\nexport type ClaimID = ProviderClaimData['identifier'];\n\nexport type ClaimInfo = Pick<ProviderClaimData, 'context' | 'provider' | 'parameters'>;\n\nexport type AnyClaimInfo = ClaimInfo | { identifier: ClaimID };\n\nexport type CompleteClaimData = Pick<ProviderClaimData, 'owner' | 'timestampS' | 'epoch'> & AnyClaimInfo;\n\nexport type SignedClaim = {\n claim: CompleteClaimData;\n signatures: Uint8Array[];\n};\n\n// Request and session-related types\nexport type CreateVerificationRequest = {\n providerIds: string[];\n applicationSecret?: string;\n};\n\nexport type StartSessionParams = {\n onSuccess: OnSuccess;\n onError: OnError;\n};\n\nexport type OnSuccess = (proof?: Proof | Proof[] | string) => void;\nexport type OnError = (error: Error) => void;\n\nexport type ProofRequestOptions = {\n log?: boolean;\n acceptAiProviders?: boolean;\n useAppClip?: boolean;\n device?: string;\n envUrl?: string;\n useBrowserExtension?: boolean;\n extensionID?: string;\n providerVersion?: string;\n customSharePageUrl?: string;\n customAppClipUrl?: string;\n launchOptions?: ReclaimFlowLaunchOptions;\n};\n\nexport type ReclaimFlowLaunchOptions = {\n /**\n * Enables deferred deep links for the Reclaim verification flow.\n *\n * When enabled, users without the verifier app installed will receive a deferred deep link\n * that automatically launches the verification flow after they install the app, ensuring\n * a seamless continuation of the verification process.\n *\n * **Platform Support:** Currently Android only\n *\n * **Default Behavior:** Opt-in during rollout phase. Will default to `true` for all apps\n * once fully released. See: https://blog.reclaimprotocol.org/posts/moving-beyond-google-play-instant\n */\n canUseDeferredDeepLinksFlow?: boolean;\n}\n\n// Modal customization options\nexport type ModalOptions = {\n title?: string;\n description?: string;\n extensionUrl?: string;\n darkTheme?: boolean;\n modalPopupTimer?: number;\n showExtensionInstallButton?: boolean;\n onClose?: () => void;\n};\n\n// JSON-safe modal options (excludes non-serializable functions)\nexport type SerializableModalOptions = Omit<ModalOptions, 'onClose'>;\n\n// Claim creation type enum\nexport enum ClaimCreationType {\n STANDALONE = 'createClaim',\n ON_ME_CHAIN = 'createClaimOnMechain'\n}\n\n// Device type enum \nexport enum DeviceType {\n ANDROID = 'android',\n IOS = 'ios',\n DESKTOP = 'desktop',\n MOBILE = 'mobile'\n}\n\n\n// Session and response types\nexport type InitSessionResponse = {\n sessionId: string;\n resolvedProviderVersion: string;\n};\n\nexport interface UpdateSessionResponse {\n success: boolean;\n message?: string;\n};\n\nexport enum SessionStatus {\n SESSION_INIT = 'SESSION_INIT',\n SESSION_STARTED = 'SESSION_STARTED',\n USER_INIT_VERIFICATION = 'USER_INIT_VERIFICATION',\n USER_STARTED_VERIFICATION = 'USER_STARTED_VERIFICATION',\n PROOF_GENERATION_STARTED = 'PROOF_GENERATION_STARTED',\n PROOF_GENERATION_SUCCESS = 'PROOF_GENERATION_SUCCESS',\n PROOF_GENERATION_FAILED = 'PROOF_GENERATION_FAILED',\n PROOF_SUBMITTED = 'PROOF_SUBMITTED',\n AI_PROOF_SUBMITTED = 'AI_PROOF_SUBMITTED',\n PROOF_SUBMISSION_FAILED = 'PROOF_SUBMISSION_FAILED',\n PROOF_MANUAL_VERIFICATION_SUBMITED = 'PROOF_MANUAL_VERIFICATION_SUBMITED',\n};\n\n// JSON and template-related types\nexport type ProofPropertiesJSON = {\n applicationId: string;\n providerId: string;\n sessionId: string;\n context: Context;\n signature: string;\n redirectUrl?: string;\n parameters: { [key: string]: string };\n /**\n * @deprecated use timestamp instead (maintained for compatibility)\n */\n timeStamp?: string;\n timestamp?: string; // new timestamp field\n appCallbackUrl?: string;\n claimCreationType?: ClaimCreationType;\n options?: ProofRequestOptions;\n sdkVersion: string;\n jsonProofResponse?: boolean;\n resolvedProviderVersion: string;\n modalOptions?: SerializableModalOptions;\n};\n\nexport type TemplateData = {\n sessionId: string;\n providerId: string;\n applicationId: string;\n signature: string;\n timestamp: string;\n callbackUrl: string;\n context: string;\n parameters: { [key: string]: string };\n redirectUrl: string;\n acceptAiProviders: boolean;\n sdkVersion: string;\n jsonProofResponse?: boolean;\n providerVersion?: string;\n resolvedProviderVersion: string;\n log?: boolean;\n};\n\n// Add the new StatusUrlResponse type\nexport type StatusUrlResponse = {\n message: string;\n session?: {\n id: string;\n appId: string;\n httpProviderId: string[];\n sessionId: string;\n proofs?: Proof[];\n statusV2: string;\n };\n providerId?: string;\n};","import { type Proof, type Context, RECLAIM_EXTENSION_ACTIONS, ExtensionMessage } from './utils/interfaces'\nimport { getIdentifierFromClaimInfo } from './witness'\nimport {\n SignedClaim,\n ProofRequestOptions,\n StartSessionParams,\n ProofPropertiesJSON,\n TemplateData,\n InitSessionResponse,\n ClaimCreationType,\n ModalOptions,\n ReclaimFlowLaunchOptions,\n} from './utils/types'\nimport { SessionStatus, DeviceType } from './utils/types'\nimport { ethers } from 'ethers'\nimport canonicalize from 'canonicalize'\nimport {\n replaceAll,\n scheduleIntervalEndingTask\n} from './utils/helper'\nimport { constants, setBackendBaseUrl } from './utils/constants'\nimport {\n SetContextError,\n GetAppCallbackUrlError,\n GetStatusUrlError,\n InitError,\n InvalidParamError,\n ProofNotVerifiedError,\n ProofSubmissionFailedError,\n ProviderFailedError,\n SessionNotStartedError,\n SetParamsError,\n SetSignatureError,\n SignatureGeneratingError,\n SignatureNotFoundError\n} from './utils/errors'\nimport { validateContext, validateFunctionParams, validateParameters, validateSignature, validateURL, validateModalOptions } from './utils/validationUtils'\nimport { fetchStatusUrl, initSession, updateSession } from './utils/sessionUtils'\nimport { assertValidSignedClaim, createLinkWithTemplateData, getWitnessesForClaim } from './utils/proofUtils'\nimport { QRCodeModal } from './utils/modalUtils'\nimport loggerModule from './utils/logger';\nimport { getDeviceType, getMobileDeviceType, isMobileDevice } from './utils/device'\nimport { canonicalStringify } from './utils/strings'\nconst logger = loggerModule.logger\n\nconst sdkVersion = require('../package.json').version;\n\n/**\n * Verifies one or more Reclaim proofs by validating signatures and witness information\n *\n * @param proofOrProofs - A single proof object or an array of proof objects to verify\n * @param allowAiWitness - Optional flag to allow AI witness verification. Defaults to false\n * @returns Promise<boolean> - Returns true if all proofs are valid, false otherwise\n * @throws {SignatureNotFoundError} When proof has no signatures\n * @throws {ProofNotVerifiedError} When identifier mismatch occurs\n *\n * @example\n * ```typescript\n * const isValid = await verifyProof(proof);\n * const areAllValid = await verifyProof([proof1, proof2, proof3]);\n * const isValidWithAI = await verifyProof(proof, true);\n * ```\n */\nexport async function verifyProof(proofOrProofs: Proof | Proof[], allowAiWitness?: boolean): Promise<boolean> {\n // If input is an array of proofs\n if (Array.isArray(proofOrProofs)) {\n for (const proof of proofOrProofs) {\n const isVerified = await verifyProof(proof, allowAiWitness);\n if (!isVerified) {\n return false;\n }\n }\n return true;\n }\n\n // Single proof verification logic\n const proof = proofOrProofs;\n if (!proof.signatures.length) {\n throw new SignatureNotFoundError('No signatures')\n }\n\n try {\n // check if witness array exist and first element is ai-witness\n let witnesses = []\n if (proof.witnesses.length && proof.witnesses[0]?.url === 'ai-witness' && allowAiWitness === true) {\n witnesses.push(proof.witnesses[0].id)\n } else {\n witnesses = await getWitnessesForClaim(\n proof.claimData.epoch,\n proof.identifier,\n proof.claimData.timestampS\n )\n }\n // then hash the claim info with the encoded ctx to get the identifier\n const calculatedIdentifier = getIdentifierFromClaimInfo({\n parameters: JSON.parse(\n canonicalize(proof.claimData.parameters) as string\n ),\n provider: proof.claimData.provider,\n context: proof.claimData.context\n })\n proof.identifier = replaceAll(proof.identifier, '\"', '')\n // check if the identifier matches the one in the proof\n if (calculatedIdentifier !== proof.identifier) {\n throw new ProofNotVerifiedError('Identifier Mismatch')\n }\n\n const signedClaim: SignedClaim = {\n claim: {\n ...proof.claimData\n },\n signatures: proof.signatures.map(signature => {\n return ethers.getBytes(signature)\n })\n }\n\n assertValidSignedClaim(signedClaim, witnesses)\n } catch (e: Error | unknown) {\n logger.info(`Error verifying proof: ${e instanceof Error ? e.message : String(e)}`)\n return false\n }\n\n return true\n}\n\n/**\n * Transforms a Reclaim proof into a format suitable for on-chain verification\n *\n * @param proof - The proof object to transform\n * @returns Object containing claimInfo and signedClaim formatted for blockchain contracts\n *\n * @example\n * ```typescript\n * const { claimInfo, signedClaim } = transformForOnchain(proof);\n * // Use claimInfo and signedClaim with smart contract verification\n * ```\n */\nexport function transformForOnchain(proof: Proof): { claimInfo: any, signedClaim: any } {\n const claimInfoBuilder = new Map([\n ['context', proof.claimData.context],\n ['parameters', proof.claimData.parameters],\n ['provider', proof.claimData.provider],\n ]);\n const claimInfo = Object.fromEntries(claimInfoBuilder);\n const claimBuilder = new Map<string, number | string>([\n ['epoch', proof.claimData.epoch],\n ['identifier', proof.claimData.identifier],\n ['owner', proof.claimData.owner],\n ['timestampS', proof.claimData.timestampS],\n ]);\n const signedClaim = {\n claim: Object.fromEntries(claimBuilder),\n signatures: proof.signatures,\n };\n return { claimInfo, signedClaim };\n}\n\n// create a empty template data object to assign to templateData\nconst emptyTemplateData: TemplateData = {\n sessionId: '',\n providerId: '',\n applicationId: '',\n signature: '',\n timestamp: '',\n callbackUrl: '',\n context: '',\n parameters: {},\n redirectUrl: '',\n acceptAiProviders: false,\n sdkVersion: '',\n providerVersion: '',\n resolvedProviderVersion: '',\n jsonProofResponse: false,\n log: false\n}\nexport class ReclaimProofRequest {\n private applicationId: string;\n private signature?: string;\n private appCallbackUrl?: string;\n private sessionId: string;\n private options?: ProofRequestOptions;\n private context: Context = { contextAddress: '0x0', contextMessage: 'sample context' };\n private claimCreationType?: ClaimCreationType = ClaimCreationType.STANDALONE;\n private providerId: string;\n private resolvedProviderVersion?: string;\n private parameters: { [key: string]: string };\n private redirectUrl?: string;\n private intervals: Map<string, NodeJS.Timer> = new Map();\n private timeStamp: string;\n private sdkVersion: string;\n private jsonProofResponse: boolean = false;\n private lastFailureTime?: number;\n private templateData: TemplateData;\n private extensionID: string = \"reclaim-extension\";\n private customSharePageUrl?: string;\n private customAppClipUrl?: string;\n private modalOptions?: ModalOptions;\n private modal?: QRCodeModal;\n private readonly FAILURE_TIMEOUT = 30 * 1000; // 30 seconds timeout, can be adjusted\n\n private constructor(applicationId: string, providerId: string, options?: ProofRequestOptions) {\n this.providerId = providerId;\n this.timeStamp = Date.now().toString();\n this.applicationId = applicationId;\n this.sessionId = \"\";\n // keep template data as empty object \n this.templateData = emptyTemplateData;\n this.parameters = {};\n\n if (!options) {\n options = {};\n }\n\n options.useBrowserExtension = options.useBrowserExtension ?? true;\n\n if (options?.log) {\n loggerModule.setLogLevel('info');\n } else {\n loggerModule.setLogLevel('silent');\n }\n\n if (options.useAppClip === undefined) {\n options.useAppClip = true;\n }\n\n if (options?.envUrl) {\n setBackendBaseUrl(options.envUrl);\n }\n\n if (options.extensionID) {\n this.extensionID = options.extensionID;\n }\n\n if (options?.customSharePageUrl) {\n this.customSharePageUrl = options.customSharePageUrl;\n }\n\n if (options?.customAppClipUrl) {\n this.customAppClipUrl = options.customAppClipUrl;\n }\n\n this.options = options;\n // Fetch sdk version from package.json\n this.sdkVersion = 'js-' + sdkVersion;\n logger.info(`Initializing client with applicationId: ${this.applicationId}`);\n }\n\n /**\n * Initializes a new Reclaim proof request instance with automatic signature generation and session creation\n *\n * @param applicationId - Your Reclaim application ID\n * @param appSecret - Your application secret key for signing requests\n * @param providerId - The ID of the provider to use for proof generation\n * @param options - Optional configuration options for the proof request\n * @returns Promise<ReclaimProofRequest> - A fully initialized proof request instance\n * @throws {InitError} When initialization fails due to invalid parameters or session creation errors\n *\n * @example\n * ```typescript\n * const proofRequest = await ReclaimProofRequest.init(\n * 'your-app-id',\n * 'your-app-secret',\n * 'provider-id',\n * { log: true, acceptAiProviders: true }\n * );\n * ```\n */\n static async init(applicationId: string, appSecret: string, providerId: string, options?: ProofRequestOptions): Promise<ReclaimProofRequest> {\n try {\n validateFunctionParams([\n { paramName: 'applicationId', input: applicationId, isString: true },\n { paramName: 'providerId', input: providerId, isString: true },\n { paramName: 'appSecret', input: appSecret, isString: true }\n ], 'the constructor')\n\n // check if options is provided and validate each property of options\n if (options) {\n if (options.acceptAiProviders) {\n validateFunctionParams([\n { paramName: 'acceptAiProviders', input: options.acceptAiProviders }\n ], 'the constructor')\n }\n if (options.providerVersion) {\n validateFunctionParams([\n { paramName: 'providerVersion', input: options.providerVersion, isString: true }\n ], 'the constructor')\n }\n if (options.log) {\n validateFunctionParams([\n { paramName: 'log', input: options.log }\n ], 'the constructor')\n }\n if (options.useAppClip) {\n validateFunctionParams([\n { paramName: 'useAppClip', input: options.useAppClip }\n ], 'the constructor')\n }\n if (options.device) {\n validateFunctionParams([\n { paramName: 'device', input: options.device, isString: true }\n ], 'the constructor')\n }\n if (options.useBrowserExtension) {\n validateFunctionParams([\n { paramName: 'useBrowserExtension', input: options.useBrowserExtension }\n ], 'the constructor')\n }\n if (options.extensionID) {\n validateFunctionParams([\n { paramName: 'extensionID', input: options.extensionID, isString: true }\n ], 'the constructor')\n }\n if (options.envUrl) {\n validateFunctionParams([\n { paramName: 'envUrl', input: options.envUrl, isString: true }\n ], 'the constructor')\n }\n if (options.customSharePageUrl) {\n validateFunctionParams([\n { paramName: 'customSharePageUrl', input: options.customSharePageUrl, isString: true }\n ], 'the constructor')\n }\n if (options.customAppClipUrl) {\n validateFunctionParams([\n { paramName: 'customAppClipUrl', input: options.customAppClipUrl, isString: true }\n ], 'the constructor')\n }\n }\n\n const proofRequestInstance = new ReclaimProofRequest(applicationId, providerId, options)\n\n const signature = await proofRequestInstance.generateSignature(appSecret)\n proofRequestInstance.setSignature(signature)\n\n const data: InitSessionResponse = await initSession(providerId, applicationId, proofRequestInstance.timeStamp, signature, options?.providerVersion);\n proofRequestInstance.sessionId = data.sessionId\n proofRequestInstance.resolvedProviderVersion = data.resolvedProviderVersion\n\n return proofRequestInstance\n } catch (error) {\n logger.info('Failed to initialize ReclaimProofRequest', error as Error);\n throw new InitError('Failed to initialize ReclaimProofRequest', error as Error)\n }\n }\n\n /**\n * Creates a ReclaimProofRequest instance from a JSON string representation\n *\n * This method deserializes a previously exported proof request (via toJsonString) and reconstructs\n * the instance with all its properties. Useful for recreating requests on the frontend or across different contexts.\n *\n * @param jsonString - JSON string containing the serialized proof request data\n * @returns {Promise<ReclaimProofRequest>} - Reconstructed proof request instance\n * @throws {InvalidParamError} When JSON string is invalid or contains invalid parameters\n *\n * @example\n * ```typescript\n * const jsonString = proofRequest.toJsonString();\n * const reconstructed = await ReclaimProofRequest.fromJsonString(jsonString);\n * // Can also be used with InApp SDK's startVerificationFromJson method\n * ```\n */\n static async fromJsonString(jsonString: string): Promise<ReclaimProofRequest> {\n try {\n const {\n applicationId,\n providerId,\n sessionId,\n context,\n parameters,\n signature,\n redirectUrl,\n timeStamp,\n timestamp,\n appCallbackUrl,\n claimCreationType,\n options,\n sdkVersion,\n jsonProofResponse,\n resolvedProviderVersion,\n modalOptions\n }: ProofPropertiesJSON = JSON.parse(jsonString)\n\n // Prefer 'timestamp' over 'timeStamp' for backward compatibility (remove in future versions)\n const resolvedTimestamp = timestamp || timeStamp;\n\n validateFunctionParams([\n { input: applicationId, paramName: 'applicationId', isString: true },\n { input: providerId, paramName: 'providerId', isString: true },\n { input: signature, paramName: 'signature', isString: true },\n { input: sessionId, paramName: 'sessionId', isString: true },\n { input: resolvedTimestamp, paramName: 'timestamp', isString: true },\n { input: sdkVersion, paramName: 'sdkVersion', isString: true },\n ], 'fromJsonString');\n\n if (modalOptions) {\n validateModalOptions(modalOptions, 'fromJsonString', 'modalOptions.');\n }\n\n if (redirectUrl) {\n validateURL(redirectUrl, 'fromJsonString');\n }\n\n if (appCallbackUrl) {\n validateURL(appCallbackUrl, 'fromJsonString');\n }\n\n if (context) {\n validateContext(context);\n }\n\n if (parameters) {\n validateParameters(parameters);\n }\n\n if (claimCreationType) {\n validateFunctionParams([\n { input: claimCreationType, paramName: 'claimCreationType' }\n ], 'fromJsonString');\n }\n\n if (jsonProofResponse !== undefined) {\n validateFunctionParams([\n { input: jsonProofResponse, paramName: 'jsonProofResponse' }\n ], 'fromJsonString');\n }\n\n\n if (options?.providerVersion) {\n validateFunctionParams([\n { input: options.providerVersion, paramName: 'providerVersion', isString: true }\n ], 'fromJsonString');\n }\n\n if (resolvedProviderVersion) {\n validateFunctionParams([\n { input: resolvedProviderVersion, paramName: 'resolvedProviderVersion', isString: true }\n ], 'fromJsonString');\n }\n\n const proofRequestInstance = new ReclaimProofRequest(applicationId, providerId, options);\n proofRequestInstance.sessionId = sessionId;\n proofRequestInstance.context = context;\n proofRequestInstance.parameters = parameters;\n proofRequestInstance.appCallbackUrl = appCallbackUrl\n proofRequestInstance.redirectUrl = redirectUrl\n proofRequestInstance.timeStamp = resolvedTimestamp!\n proofRequestInstance.signature = signature\n proofRequestInstance.sdkVersion = sdkVersion;\n proofRequestInstance.resolvedProviderVersion = resolvedProviderVersion;\n proofRequestInstance.modalOptions = modalOptions;\n return proofRequestInstance\n } catch (error) {\n logger.info('Failed to parse JSON string in fromJsonString:', error);\n throw new InvalidParamError('Invalid JSON string provided to fromJsonString');\n }\n }\n\n /**\n * Sets a custom callback URL where proofs will be submitted via HTTP POST\n *\n * By default, proofs are posted as `application/x-www-form-urlencoded`.\n * When a custom callback URL is set, Reclaim will no longer receive proofs upon submission,\n * and listeners on the startSession method will not be triggered. Your application must\n * coordinate with your backend to receive and verify proofs using verifyProof().\n *\n * Note: InApp SDKs are unaffected by this property as they do not handle proof submission.\n *\n * @param url - The URL where proofs should be submitted via HTTP POST\n * @param jsonProofResponse - Optional. Set to true to submit proofs as `application/json`. Defaults to false\n * @throws {InvalidParamError} When URL is invalid\n *\n * @example\n * ```typescript\n * proofRequest.setAppCallbackUrl('https://your-backend.com/callback');\n * // Or with JSON format\n * proofRequest.setAppCallbackUrl('https://your-backend.com/callback', true);\n * ```\n */\n setAppCallbackUrl(url: string, jsonProofResponse?: boolean): void {\n validateURL(url, 'setAppCallbackUrl')\n this.appCallbackUrl = url\n this.jsonProofResponse = jsonProofResponse ?? false\n }\n\n /**\n * Sets a redirect URL where users will be redirected after successfully acquiring and submitting proof\n *\n * @param url - The URL where users should be redirected after successful proof generation\n * @throws {InvalidParamError} When URL is invalid\n *\n * @example\n * ```typescript\n * proofRequest.setRedirectUrl('https://your-app.com/success');\n * ```\n */\n setRedirectUrl(url: string): void {\n validateURL(url, 'setRedirectUrl');\n this.redirectUrl = url;\n }\n\n /**\n * Sets the claim creation type for the proof request\n *\n * @param claimCreationType - The type of claim creation (e.g., STANDALONE)\n *\n * @example\n * ```typescript\n * proofRequest.setClaimCreationType(ClaimCreationType.STANDALONE);\n * ```\n */\n setClaimCreationType(claimCreationType: ClaimCreationType): void {\n this.claimCreationType = claimCreationType;\n }\n\n /**\n * Sets custom options for the QR code modal display\n *\n * @param options - Modal configuration options including title, description, theme, etc.\n * @throws {SetParamsError} When modal options are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setModalOptions({\n * title: 'Scan QR Code',\n * description: 'Scan with your mobile device',\n * darkTheme: true\n * });\n * ```\n */\n setModalOptions(options: ModalOptions): void {\n try {\n // Validate modal options\n validateModalOptions(options, 'setModalOptions');\n\n this.modalOptions = { ...this.modalOptions, ...options };\n logger.info('Modal options set successfully');\n } catch (error) {\n logger.info('Error setting modal options:', error);\n throw new SetParamsError('Error setting modal options', error as Error);\n }\n }\n\n /**\n * Sets additional context data to be stored with the claim\n *\n * This allows you to associate custom data (address and message) with the proof claim.\n * The context can be retrieved and validated when verifying the proof. \n * \n * Also see [setContext] which is an alternate way to set context that has an address & message.\n *\n * @param context - Any additional data you want to store with the claim. Should be serializable to a JSON string.\n * @throws {SetContextError} When context parameters are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setJsonContext({foo: 'bar'});\n * ```\n */\n setJsonContext(context: Record<string, any>) {\n try {\n validateFunctionParams([\n { input: context, paramName: 'context', isString: false }\n ], 'setJsonContext');\n // ensure context is canonically json serializable\n this.context = JSON.parse(canonicalStringify(context));\n } catch (error) {\n logger.info(\"Error setting context\", error)\n throw new SetContextError(\"Error setting context\", error as Error)\n }\n }\n\n /**\n * Sets additional context data to be stored with the claim\n *\n * This allows you to associate custom data (address and message) with the proof claim.\n * The context can be retrieved and validated when verifying the proof.\n *\n * @param address - Context address identifier\n * @param message - Additional data to associate with the address\n * @throws {SetContextError} When context parameters are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setContext('0x1234...', 'User verification for premium access');\n * ```\n */\n setContext(address: string, message: string): void {\n try {\n validateFunctionParams([\n { input: address, paramName: 'address', isString: true },\n { input: message, paramName: 'message', isString: true }\n ], 'setContext');\n this.context = { contextAddress: address, contextMessage: message };\n } catch (error) {\n logger.info(\"Error setting context\", error)\n throw new SetContextError(\"Error setting context\", error as Error)\n }\n }\n\n /**\n * @deprecated use setContext instead\n *\n * @param address \n * @param message additional data you want associated with the [address] \n */\n addContext(address: string, message: string): void {\n this.setContext(address, message);\n }\n\n /**\n * Sets provider-specific parameters for the proof request\n *\n * These parameters are passed to the provider and may include configuration options,\n * filters, or other provider-specific settings required for proof generation.\n *\n * @param params - Key-value pairs of parameters to set\n * @throws {SetParamsError} When parameters are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setParams({\n * minFollowers: '1000',\n * platform: 'twitter'\n * });\n * ```\n */\n setParams(params: { [key: string]: string }): void {\n try {\n validateParameters(params);\n this.parameters = { ...this.parameters, ...params }\n } catch (error) {\n logger.info('Error Setting Params:', error);\n throw new SetParamsError(\"Error setting params\", error as Error)\n }\n }\n\n /**\n * Returns the currently configured app callback URL\n *\n * If no custom callback URL was set via setAppCallbackUrl(), this returns the default\n * Reclaim service callback URL with the current session ID.\n *\n * @returns The callback URL where proofs will be submitted\n * @throws {GetAppCallbackUrlError} When unable to retrieve the callback URL\n *\n * @example\n * ```typescript\n * const callbackUrl = proofRequest.getAppCallbackUrl();\n * console.log('Proofs will be sent to:', callbackUrl);\n * ```\n */\n getAppCallbackUrl(): string {\n try {\n validateFunctionParams([{ input: this.sessionId, paramName: 'sessionId', isString: true }], 'getAppCallbackUrl');\n return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`\n } catch (error) {\n logger.info(\"Error getting app callback url\", error)\n throw new GetAppCallbackUrlError(\"Error getting app callback url\", error as Error)\n }\n }\n\n /**\n * Returns the status URL for monitoring the current session\n *\n * This URL can be used to check the status of the proof request session.\n *\n * @returns The status monitoring URL for the current session\n * @throws {GetStatusUrlError} When unable to retrieve the status URL\n *\n * @example\n * ```typescript\n * const statusUrl = proofRequest.getStatusUrl();\n * // Use this URL to poll for session status updates\n * ```\n */\n getStatusUrl(): string {\n try {\n validateFunctionParams([{ input: this.sessionId, paramName: 'sessionId', isString: true }], 'getStatusUrl');\n return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`\n } catch (error) {\n logger.info(\"Error fetching Status Url\", error)\n throw new GetStatusUrlError(\"Error fetching status url\", error as Error)\n }\n }\n\n /**\n * Returns the session ID associated with this proof request\n *\n * The session ID is automatically generated during initialization and uniquely\n * identifies this proof request session.\n *\n * @returns The session ID string\n * @throws {SessionNotStartedError} When session ID is not set\n *\n * @example\n * ```typescript\n * const sessionId = proofRequest.getSessionId();\n * console.log('Session ID:', sessionId);\n * ```\n */\n getSessionId(): string {\n if (!this.sessionId) {\n throw new SessionNotStartedError(\"SessionId is not set\");\n }\n return this.sessionId;\n }\n\n // Private helper methods\n private setSignature(signature: string): void {\n try {\n validateFunctionParams([{ input: signature, paramName: 'signature', isString: true }], 'setSignature');\n this.signature = signature;\n logger.info(`Signature set successfully for applicationId: ${this.applicationId}`);\n } catch (error) {\n logger.info(\"Error setting signature\", error)\n throw new SetSignatureError(\"Error setting signature\", error as Error)\n }\n }\n\n private async generateSignature(applicationSecret: string): Promise<string> {\n try {\n const wallet = new ethers.Wallet(applicationSecret)\n const canonicalData = canonicalize({ providerId: this.providerId, timestamp: this.timeStamp });\n\n\n if (!canonicalData) {\n throw new SignatureGeneratingError('Failed to canonicalize data for signing.');\n }\n\n const messageHash = ethers.keccak256(new TextEncoder().encode(canonicalData));\n\n return await wallet.signMessage(ethers.getBytes(messageHash));\n } catch (err) {\n logger.info(`Error generating proof request for applicationId: ${this.applicationId}, providerId: ${this.providerId}, signature: ${this.signature}, timeStamp: ${this.timeStamp}`, err);\n throw new SignatureGeneratingError(`Error generating signature for applicationSecret: ${applicationSecret}`)\n }\n }\n\n private clearInterval(): void {\n if (this.sessionId && this.intervals.has(this.sessionId)) {\n clearInterval(this.intervals.get(this.sessionId) as NodeJS.Timeout)\n this.intervals.delete(this.sessionId)\n }\n }\n\n private buildSharePageUrl(template: string): string {\n const baseUrl = 'https://share.reclaimprotocol.org/verify';\n\n if (this.customSharePageUrl) {\n return `${this.customSharePageUrl}/?template=${template}`;\n }\n\n return `${baseUrl}/?template=${template}`;\n }\n\n /**\n * Exports the Reclaim proof verification request as a JSON string\n *\n * This serialized format can be sent to the frontend to recreate this request using\n * ReclaimProofRequest.fromJsonString() or any InApp SDK's startVerificationFromJson()\n * method to initiate the verification journey.\n *\n * @returns JSON string representation of the proof request. Note: The JSON includes both `timestamp` and `timeStamp` (deprecated) for backward compatibility.\n *\n * @example\n * ```typescript\n * const jsonString = proofRequest.toJsonString();\n * // Send to frontend or store for later use\n * // Can be reconstructed with: ReclaimProofRequest.fromJsonString(jsonString)\n * ```\n */\n toJsonString(): string {\n return JSON.stringify({\n applicationId: this.applicationId,\n providerId: this.providerId,\n sessionId: this.sessionId,\n context: this.context,\n appCallbackUrl: this.appCallbackUrl,\n claimCreationType: this.claimCreationType,\n parameters: this.parameters,\n signature: this.signature,\n redirectUrl: this.redirectUrl,\n timestamp: this.timeStamp, // New field with correct spelling\n timeStamp: this.timeStamp, // @deprecated: Remove in future versions \n options: this.options,\n sdkVersion: this.sdkVersion,\n jsonProofResponse: this.jsonProofResponse,\n resolvedProviderVersion: this.resolvedProviderVersion ?? '',\n modalOptions: this.modalOptions ? {\n title: this.modalOptions.title,\n description: this.modalOptions.description,\n extensionUrl: this.modalOptions.extensionUrl,\n darkTheme: this.modalOptions.darkTheme,\n modalPopupTimer: this.modalOptions.modalPopupTimer,\n showExtensionInstallButton: this.modalOptions.showExtensionInstallButton\n // onClose is intentionally excluded as functions cannot be serialized\n } : undefined\n })\n }\n\n /**\n * Validates signature and returns template data\n * @returns \n */\n private getTemplateData = (): TemplateData => {\n if (!this.signature) {\n throw new SignatureNotFoundError('Signature is not set.')\n }\n validateSignature(this.providerId, this.signature, this.applicationId, this.timeStamp)\n const templateData: TemplateData = {\n sessionId: this.sessionId,\n providerId: this.providerId,\n applicationId: this.applicationId,\n signature: this.signature,\n timestamp: this.timeStamp,\n callbackUrl: this.getAppCallbackUrl(),\n context: canonicalStringify(this.context),\n providerVersion: this.options?.providerVersion ?? '',\n resolvedProviderVersion: this.resolvedProviderVersion ?? '',\n parameters: this.parameters,\n redirectUrl: this.redirectUrl ?? '',\n acceptAiProviders: this.options?.acceptAiProviders ?? false,\n sdkVersion: this.sdkVersion,\n jsonProofResponse: this.jsonProofResponse,\n log: this.options?.log ?? false\n\n }\n\n return templateData;\n }\n\n /**\n * Generates and returns the request URL for proof verification\n *\n * This URL can be shared with users to initiate the proof generation process.\n * The URL format varies based on device type:\n * - Mobile iOS: Returns App Clip URL (if useAppClip is enabled)\n * - Mobile Android: Returns Instant App URL (if useAppClip is enabled)\n * - Desktop/Other: Returns standard verification URL\n *\n * @param launchOptions - Optional launch configuration to override default behavior\n * @returns Promise<string> - The generated request URL\n * @throws {SignatureNotFoundError} When signature is not set\n *\n * @example\n * ```typescript\n * const requestUrl = await proofRequest.getRequestUrl();\n * // Share this URL with users or display as QR code\n * ```\n */\n async getRequestUrl(launchOptions?: ReclaimFlowLaunchOptions): Promise<string> {\n const options = launchOptions || this.options?.launchOptions || {};\n\n logger.info('Creating Request Url')\n if (!this.signature) {\n throw new SignatureNotFoundError('Signature is not set.')\n }\n\n try {\n const templateData = this.getTemplateData()\n await updateSession(this.sessionId, SessionStatus.SESSION_STARTED)\n const deviceType = getDeviceType();\n if (this.options?.useAppClip && deviceType === DeviceType.MOBILE) {\n let template = encodeURIComponent(JSON.stringify(templateData));\n template = replaceAll(template, '(', '%28');\n template = replaceAll(template, ')', '%29');\n\n // check if the app is running on iOS or Android\n const isIos = getMobileDeviceType() === DeviceType.IOS;\n if (!isIos) {\n let instantAppUrl = this.buildSharePageUrl(template);\n const isDeferredDeeplinksFlowEnabled = options.canUseDeferredDeepLinksFlow ?? false;\n\n if (isDeferredDeeplinksFlowEnabled) {\n instantAppUrl = instantAppUrl.replace(\"/verifier\", \"/link\");\n }\n logger.info('Instant App Url created successfully: ' + instantAppUrl);\n return instantAppUrl;\n } else {\n const appClipUrl = this.customAppClipUrl ? `${this.customAppClipUrl}&template=${template}` : `https://appclip.apple.com/id?p=org.reclaimprotocol.app.clip&template=${template}`;\n logger.info('App Clip Url created successfully: ' + appClipUrl);\n return appClipUrl;\n }\n } else {\n const link = await createLinkWithTemplateData(templateData, this.customSharePageUrl)\n logger.info('Request Url created successfully: ' + link);\n return link;\n }\n } catch (error) {\n logger.info('Error creating Request Url:', error)\n throw error\n }\n }\n\n /**\n * Triggers the appropriate Reclaim verification flow based on device type and configuration\n *\n * This method automatically detects the device type and initiates the optimal verification flow:\n * - Desktop with browser extension: Triggers extension flow\n * - Desktop without extension: Shows QR code modal\n * - Mobile Android: Redirects to Instant App\n * - Mobile iOS: Redirects to App Clip\n *\n * @param launchOptions - Optional launch configuration to override default behavior\n * @returns Promise<void>\n * @throws {SignatureNotFoundError} When signature is not set\n *\n * @example\n * ```typescript\n * await proofRequest.triggerReclaimFlow();\n * // The appropriate verification method will be triggered automatically\n * ```\n */\n async triggerReclaimFlow(launchOptions?: ReclaimFlowLaunchOptions): Promise<void> {\n const options = launchOptions || this.options?.launchOptions || {};\n\n if (!this.signature) {\n throw new SignatureNotFoundError('Signature is not set.')\n }\n\n try {\n const templateData = this.getTemplateData()\n\n this.templateData = templateData;\n\n logger.info('Triggering Reclaim flow');\n\n // Get device type\n const deviceType = getDeviceType();\n updateSession(this.sessionId, SessionStatus.SESSION_STARTED)\n\n if (deviceType === DeviceType.DESKTOP) {\n const extensionAvailable = await this.isBrowserExtensionAvailable();\n // Desktop flow\n if (this.options?.useBrowserExtension && extensionAvailable) {\n logger.info('Triggering browser extension flow');\n this.triggerBrowserExtensionFlow();\n return;\n } else {\n // Show QR code popup modal\n logger.info('Browser extension not available, showing QR code modal');\n await this.showQRCodeModal();\n }\n } else if (deviceType === DeviceType.MOBILE) {\n // Mobile flow\n const mobileDeviceType = getMobileDeviceType();\n\n if (mobileDeviceType === DeviceType.ANDROID) {\n // Redirect to instant app URL\n logger.info('Redirecting to Android instant app');\n await this.redirectToInstantApp(options);\n } else if (mobileDeviceType === DeviceType.IOS) {\n // Redirect to app clip URL\n logger.info('Redirecting to iOS app clip');\n this.redirectToAppClip();\n }\n }\n } catch (error) {\n logger.info('Error triggering Reclaim flow:', error);\n throw error;\n }\n }\n\n\n /**\n * Checks if the Reclaim browser extension is installed and available\n *\n * This method attempts to communicate with the browser extension to verify its availability.\n * It uses a timeout mechanism to quickly determine if the extension responds.\n *\n * @param timeout - Timeout in milliseconds to wait for extension response. Defaults to 200ms\n * @returns Promise<boolean> - True if extension is available, false otherwise\n *\n * @example\n * ```typescript\n * const hasExtension = await proofRequest.isBrowserExtensionAvailable();\n * if (hasExtension) {\n * console.log('Browser extension is installed');\n * }\n * ```\n */\n async isBrowserExtensionAvailable(timeout = 200): Promise<boolean> {\n try {\n return new Promise<boolean>((resolve) => {\n const messageId = `reclaim-check-${Date.now()}`;\n\n const timeoutId = setTimeout(() => {\n window.removeEventListener('message', messageListener);\n resolve(false);\n }, timeout);\n\n const messageListener = (event: MessageEvent) => {\n if (event.data?.action === RECLAIM_EXTENSION_ACTIONS.EXTENSION_RESPONSE &&\n event.data?.messageId === messageId) {\n clearTimeout(timeoutId);\n window.removeEventListener('message', messageListener);\n resolve(!!event.data.installed);\n }\n };\n\n window.addEventListener('message', messageListener);\n const message: ExtensionMessage = {\n action: RECLAIM_EXTENSION_ACTIONS.CHECK_EXTENSION,\n extensionID: this.extensionID,\n messageId: messageId\n }\n window.postMessage(message, '*');\n });\n } catch (error) {\n logger.info('Error checking Reclaim extension installed:', error);\n return false;\n }\n }\n\n private triggerBrowserExtensionFlow(): void {\n const message: ExtensionMessage = {\n action: RECLAIM_EXTENSION_ACTIONS.START_VERIFICATION,\n messageId: this.sessionId,\n data: this.templateData,\n extensionID: this.extensionID\n }\n window.postMessage(message, '*');\n logger.info('Browser extension flow triggered');\n }\n\n private async showQRCodeModal(): Promise<void> {\n try {\n const requestUrl = await createLinkWithTemplateData(this.templateData, this.customSharePageUrl);\n this.modal = new QRCodeModal(this.modalOptions);\n await this.modal.show(requestUrl);\n } catch (error) {\n logger.info('Error showing QR code modal:', error);\n throw error;\n }\n }\n\n private async redirectToInstantApp(options: ReclaimFlowLaunchOptions): Promise<void> {\n try {\n let template = encodeURIComponent(JSON.stringify(this.templateData));\n template = replaceAll(template, '(', '%28');\n template = replaceAll(template, ')', '%29');\n\n let instantAppUrl = this.buildSharePageUrl(template);\n logger.info('Redirecting to Android instant app: ' + instantAppUrl);\n\n const isDeferredDeeplinksFlowEnabled = options.canUseDeferredDeepLinksFlow ?? false;\n\n if (isDeferredDeeplinksFlowEnabled) {\n instantAppUrl = instantAppUrl.replace(\"/verifier\", \"/link\");\n\n // Construct Android intent deep link\n const deepLink = `intent://details?id=org.reclaimprotocol.app&url=${encodeURIComponent(\n instantAppUrl\n )}&template=${template}#Intent;scheme=market;action=android.intent.action.VIEW;package=com.android.vending;end;`;\n\n try {\n const requestUrl = instantAppUrl;\n\n let appInstalled = false;\n let timeoutId: string | number | NodeJS.Timeout | undefined;\n\n // Create hidden iframe to test deep link\n const iframe = document.createElement(\"iframe\");\n iframe.style.display = \"none\";\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n document.body.appendChild(iframe);\n\n // Function to clean up\n const cleanup = () => {\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n // If page becomes hidden, app opened successfully\n const onVisibilityChange = () => {\n if (document.hidden) {\n appInstalled = true;\n cleanup();\n // Open in main window since app is installed\n window.location.href = deepLink;\n }\n };\n\n // Listen for visibility change\n document.addEventListener(\"visibilitychange\", onVisibilityChange, { once: true });\n\n // Test reclaimverifier deep link in iframe\n iframe.src = deepLink.replace('intent:', 'reclaimverifier:');\n\n // After timeout, assume app not installed\n timeoutId = setTimeout(() => {\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n cleanup();\n\n if (!appInstalled) {\n // App not installed - redirect to the store page to install the app\n window.navigator.clipboard.writeText(requestUrl).catch(() => {\n console.error(\"We can't access the clipboard. Please copy this link and open Reclaim Verifier app.\");\n });\n window.location.href = deepLink;\n }\n }, 1500);\n } catch (e) {\n // Final fallback → verifier\n window.location.href = instantAppUrl;\n }\n return;\n }\n\n // Redirect to instant app\n window.location.href = instantAppUrl;\n } catch (error) {\n logger.info('Error redirecting to instant app:', error);\n throw error;\n }\n }\n\n private redirectToAppClip(): void {\n try {\n let template = encodeURIComponent(JSON.stringify(this.templateData));\n template = replaceAll(template, '(', '%28');\n template = replaceAll(template, ')', '%29');\n\n const appClipUrl = this.customAppClipUrl ? `${this.customAppClipUrl}&template=${template}` : `https://appclip.apple.com/id?p=org.reclaimprotocol.app.clip&template=${template}`;\n logger.info('Redirecting to iOS app clip: ' + appClipUrl);\n const verifierUrl = `https://share.reclaimprotocol.org/verifier/?template=${template}`;\n\n // Redirect to app clip\n window.location.href = appClipUrl;\n\n setTimeout(() => {\n window.location.href = verifierUrl;\n // 5 second delay to allow app clip to launch\n }, 5 * 1000);\n } catch (error) {\n logger.info('Error redirecting to app clip:', error);\n throw error;\n }\n }\n\n /**\n * Starts the proof request session and monitors for proof submission\n *\n * This method begins polling the session status to detect when\n * a proof has been generated and submitted. It handles both default Reclaim callbacks\n * and custom callback URLs.\n *\n * For default callbacks: Verifies proofs automatically and passes them to onSuccess\n * For custom callbacks: Monitors submission status and notifies via onSuccess when complete\n *\n * @param onSuccess - Callback function invoked when proof is successfully submitted\n * @param onError - Callback function invoked when an error occurs during the session\n * @returns Promise<void>\n * @throws {SessionNotStartedError} When session ID is not defined\n * @throws {ProofNotVerifiedError} When proof verification fails (default callback only)\n * @throws {ProofSubmissionFailedError} When proof submission fails (custom callback only)\n * @throws {ProviderFailedError} When proof generation fails with timeout\n *\n * @example\n * ```typescript\n * await proofRequest.startSession({\n * onSuccess: (proof) => {\n * console.log('Proof received:', proof);\n * },\n * onError: (error) => {\n * console.error('Error:', error);\n * }\n * });\n * ```\n */\n async startSession({ onSuccess, onError }: StartSessionParams): Promise<void> {\n if (!this.sessionId) {\n const message = \"Session can't be started due to undefined value of sessionId\";\n logger.info(message);\n throw new SessionNotStartedError(message);\n }\n\n logger.info('Starting session');\n\n const sessionUpdatePollingInterval = 3 * 1000;\n const interval = setInterval(async () => {\n try {\n const statusUrlResponse = await fetchStatusUrl(this.sessionId);\n\n if (!statusUrlResponse.session) return;\n\n // Reset failure time if status is not PROOF_GENERATION_FAILED\n if (statusUrlResponse.session.statusV2 !== SessionStatus.PROOF_GENERATION_FAILED) {\n this.lastFailureTime = undefined;\n }\n\n // Check for failure timeout\n if (statusUrlResponse.session.statusV2 === SessionStatus.PROOF_GENERATION_FAILED) {\n const currentTime = Date.now();\n if (!this.lastFailureTime) {\n this.lastFailureTime = currentTime;\n } else if (currentTime - this.lastFailureTime >= this.FAILURE_TIMEOUT) {\n throw new ProviderFailedError('Proof generation failed - timeout reached');\n }\n return; // Continue monitoring if under timeout\n }\n\n const isDefaultCallbackUrl = this.getAppCallbackUrl() === `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`;\n\n if (isDefaultCallbackUrl) {\n if (statusUrlResponse.session.proofs && statusUrlResponse.session.proofs.length > 0) {\n const proofs = statusUrlResponse.session.proofs;\n if (this.claimCreationType === ClaimCreationType.STANDALONE) {\n const verified = await verifyProof(proofs);\n if (!verified) {\n logger.info(`Proofs not verified: ${JSON.stringify(proofs)}`);\n throw new ProofNotVerifiedError();\n }\n }\n // check if the proofs array has only one proof then send the proofs in onSuccess \n if (proofs.length === 1) {\n\n onSuccess(proofs[0]);\n } else {\n onSuccess(proofs);\n }\n this.clearInterval();\n this.modal?.close();\n }\n } else {\n if (statusUrlResponse.session.statusV2 === SessionStatus.PROOF_SUBMISSION_FAILED) {\n throw new ProofSubmissionFailedError();\n }\n if (statusUrlResponse.session.statusV2 === SessionStatus.PROOF_SUBMITTED ||\n statusUrlResponse.session.statusV2 === SessionStatus.AI_PROOF_SUBMITTED) {\n if (onSuccess) {\n onSuccess('Proof submitted successfully to the custom callback url');\n }\n this.clearInterval();\n this.modal?.close();\n }\n }\n } catch (e) {\n if (onError) {\n onError(e as Error);\n }\n this.clearInterval();\n this.modal?.close();\n }\n }, sessionUpdatePollingInterval);\n\n this.intervals.set(this.sessionId, interval);\n scheduleIntervalEndingTask(this.sessionId, this.intervals, onError);\n }\n\n /**\n * Closes the QR code modal if it is currently open\n *\n * This method can be called to programmatically close the modal, for example,\n * when implementing custom UI behavior or cleanup logic.\n *\n * @example\n * ```typescript\n * // Close modal after some condition\n * proofRequest.closeModal();\n * ```\n */\n closeModal(): void {\n if (this.modal) {\n this.modal.close();\n logger.info('Modal closed by user');\n }\n }\n}\n\n","function createErrorClass(name: string) {\n return class extends Error {\n constructor(message?: string, public innerError?: Error) {\n // Include inner error message in the main message if available\n const fullMessage = innerError\n ? `${message || ''} caused by ${innerError.name}: ${innerError.message}`\n : message;\n\n super(fullMessage);\n this.name = name;\n if (innerError) {\n this.stack += `\\nCaused by: ${innerError.stack}`;\n }\n }\n };\n}\n\nexport const TimeoutError = createErrorClass('TimeoutError');\nexport const ProofNotVerifiedError = createErrorClass('ProofNotVerifiedError');\nexport const SessionNotStartedError = createErrorClass('SessionNotStartedError');\nexport const ProviderNotFoundError = createErrorClass('ProviderNotFoundError');\nexport const SignatureGeneratingError = createErrorClass('SignatureGeneratingError');\nexport const SignatureNotFoundError = createErrorClass('SignatureNotFoundError');\nexport const InvalidSignatureError = createErrorClass('InvalidSignatureError');\nexport const UpdateSessionError = createErrorClass('UpdateSessionError');\nexport const InitSessionError = createErrorClass('InitSessionError');\nexport const ProviderFailedError = createErrorClass('ProviderFailedError');\nexport const InvalidParamError = createErrorClass('InvalidParamError');\nexport const ApplicationError = createErrorClass('ApplicationError');\nexport const InitError = createErrorClass('InitError');\nexport const BackendServerError = createErrorClass('BackendServerError');\nexport const GetStatusUrlError = createErrorClass('GetStatusUrlError');\nexport const NoProviderParamsError = createErrorClass('NoProviderParamsError');\nexport const SetParamsError = createErrorClass('SetParamsError');\nexport const SetContextError = createErrorClass('SetContextError');\nexport const SetSignatureError = createErrorClass('SetSignatureError');\nexport const GetAppCallbackUrlError = createErrorClass(\"GetAppCallbackUrlError\");\nexport const StatusUrlError = createErrorClass('StatusUrlError');\nexport const InavlidParametersError = createErrorClass('InavlidParametersError');\nexport const ProofSubmissionFailedError = createErrorClass('ProofSubmissionFailedError');","// Define the possible log levels\nexport type LogLevel = 'info' | 'warn' | 'error' | 'silent';\n\n// Define a simple logger class\nclass SimpleLogger {\n private level: LogLevel = 'info';\n\n setLevel(level: LogLevel) {\n this.level = level;\n }\n\n private shouldLog(messageLevel: LogLevel): boolean {\n const levels: LogLevel[] = ['error', 'warn', 'info', 'silent'];\n return levels.indexOf(this.level) >= levels.indexOf(messageLevel);\n }\n\n private log(level: LogLevel, message: string, ...args: any[]) {\n if (this.shouldLog(level) && this.level !== 'silent') {\n const logFunction = this.getLogFunction(level);\n console.log('current level', this.level);\n logFunction(`[${level.toUpperCase()}]`, message, ...args);\n }\n }\n\n private getLogFunction(level: LogLevel): (message?: any, ...optionalParams: any[]) => void {\n switch (level) {\n case 'error':\n return console.error;\n case 'warn':\n return console.warn;\n case 'info':\n return console.info;\n default:\n return () => {}; // No-op for 'silent'\n }\n }\n\n info(message: string, ...args: any[]) {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]) {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]) {\n this.log('error', message, ...args);\n }\n}\n\n// Create the logger instance\nconst logger = new SimpleLogger();\n\n// Function to set the log level\nexport function setLogLevel(level: LogLevel) {\n logger.setLevel(level);\n}\n\n// Export the logger instance and the setLogLevel function\nexport default {\n logger,\n setLogLevel\n};\n","import { OnError } from './types'\nimport { TimeoutError } from './errors'\nimport loggerModule from './logger'\nconst logger = loggerModule.logger\n\n/**\n * Escapes special characters in a string for use in a regular expression\n * @param string - The input string to escape\n * @returns The input string with special regex characters escaped\n */\nexport function escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Replaces all occurrences of a substring in a string\n * @param str - The original string\n * @param find - The substring to find\n * @param replace - The string to replace the found substrings with\n * @returns A new string with all occurrences of 'find' replaced by 'replace'\n */\nexport function replaceAll(str: string, find: string, replace: string): string {\n if (find === '') return str;\n return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);\n}\n\n/**\n * Schedules a task to end an interval after a specified timeout\n * @param sessionId - The ID of the current session\n * @param intervals - A Map containing the intervals\n * @param onFailureCallback - Callback function to be called on failure\n * @param timeout - Timeout in milliseconds (default: 10 minutes)\n */\nexport function scheduleIntervalEndingTask(\n sessionId: string,\n intervals: Map<string, NodeJS.Timer>,\n onFailureCallback: OnError,\n timeout: number = 1000 * 60 * 10\n): void {\n setTimeout(() => {\n if (intervals.has(sessionId)) {\n const message = 'Interval ended without receiving proofs'\n onFailureCallback(new TimeoutError(message))\n logger.info(message)\n clearInterval(intervals.get(sessionId) as NodeJS.Timeout)\n intervals.delete(sessionId)\n }\n }, timeout)\n}\n","// Base URL for the backend API\nexport let BACKEND_BASE_URL = \"https://api.reclaimprotocol.org\";\n\nexport function setBackendBaseUrl(url: string) {\n BACKEND_BASE_URL = url;\n}\n\n// Constant values used throughout the application\nexport const constants = {\n // Default callback URL for Reclaim protocol\n get DEFAULT_RECLAIM_CALLBACK_URL() {\n return `${BACKEND_BASE_URL}/api/sdk/callback?callbackId=`;\n },\n\n // Default status URL for Reclaim sessions\n get DEFAULT_RECLAIM_STATUS_URL() {\n return `${BACKEND_BASE_URL}/api/sdk/session/`;\n },\n\n // URL for sharing Reclaim templates\n RECLAIM_SHARE_URL: 'https://share.reclaimprotocol.org/verifier/?template=',\n\n // Chrome extension URL for Reclaim Protocol\n CHROME_EXTENSION_URL: 'https://chromewebstore.google.com/detail/reclaim-extension/oafieibbbcepkmenknelhmgaoahamdeh',\n\n // QR Code API base URL\n QR_CODE_API_URL: 'https://api.qrserver.com/v1/create-qr-code/'\n};\n","import { ethers } from \"ethers\";\nimport { InavlidParametersError, InvalidParamError, InvalidSignatureError } from \"./errors\";\nimport canonicalize from 'canonicalize'\nimport { Context } from \"./interfaces\";\nimport loggerModule from './logger';\nimport { ProofRequestOptions, ModalOptions } from \"./types\";\nconst logger = loggerModule.logger;\n\n/**\n * Validates function parameters based on specified criteria\n * @param params - An array of objects containing input, paramName, and optional isString flag\n * @param functionName - The name of the function being validated\n * @throws InvalidParamError if any parameter fails validation\n */\nexport function validateFunctionParams(params: { input: any, paramName: string, isString?: boolean }[], functionName: string): void {\n params.forEach(({ input, paramName, isString }) => {\n if (input == null) {\n logger.info(`Validation failed: ${paramName} in ${functionName} is null or undefined`);\n throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`);\n }\n if (isString && typeof input !== 'string') {\n logger.info(`Validation failed: ${paramName} in ${functionName} is not a string`);\n throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`);\n }\n if (isString && input.trim() === '') {\n logger.info(`Validation failed: ${paramName} in ${functionName} is an empty string`);\n throw new InvalidParamError(`${paramName} passed to ${functionName} must not be an empty string.`);\n }\n });\n}\n\n\n// validate the parameters\n/** \n * Validates the parameters object\n * @param parameters - The parameters object to validate\n * @throws InavlidParametersError if the parameters object is not valid\n */\nexport function validateParameters(parameters: { [key: string]: string }): void {\n try {\n // check if the parameters is an object of key value pairs of string and string\n if (typeof parameters !== 'object' || parameters === null) {\n logger.info(`Parameters validation failed: Provided parameters is not an object`);\n throw new InavlidParametersError(`The provided parameters is not an object`);\n }\n // check each key and value in the parameters object\n for (const [key, value] of Object.entries(parameters)) {\n if (typeof key !== 'string' || typeof value !== 'string') {\n logger.info(`Parameters validation failed: Provided parameters is not an object of key value pairs of string and string`);\n throw new InavlidParametersError(`The provided parameters is not an object of key value pairs of string and string`);\n }\n }\n } catch (e) {\n logger.info(`Parameters validation failed: ${(e as Error).message}`);\n throw new InavlidParametersError(`Invalid parameters passed to validateParameters.`, e as Error);\n }\n}\n\n\n/**\n* Validates a URL string\n* @param url - The URL to validate\n* @param functionName - The name of the function calling this validation\n* @throws InvalidParamError if the URL is invalid or empty\n*/\nexport function validateURL(url: string, functionName: string): void {\n try {\n new URL(url);\n } catch (e) {\n logger.info(`URL validation failed for ${url} in ${functionName}: ${(e as Error).message}`);\n throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e as Error);\n }\n}\n\n/**\n* Validates a signature against the provided application ID\n* @param providerId - The ID of the provider\n* @param signature - The signature to validate\n* @param applicationId - The expected application ID\n* @param timestamp - The timestamp of the signature\n* @throws InvalidSignatureError if the signature is invalid or doesn't match the application ID\n*/\nexport function validateSignature(providerId: string, signature: string, applicationId: string, timestamp: string): void {\n try {\n logger.info(`Starting signature validation for providerId: ${providerId}, applicationId: ${applicationId}, timestamp: ${timestamp}`);\n\n const message = canonicalize({ providerId, timestamp });\n if (!message) {\n logger.info('Failed to canonicalize message for signature validation');\n throw new Error('Failed to canonicalize message');\n }\n const messageHash = ethers.keccak256(new TextEncoder().encode(message));\n let appId = ethers.verifyMessage(\n ethers.getBytes(messageHash),\n ethers.hexlify(signature)\n ).toLowerCase();\n\n if (ethers.getAddress(appId) !== ethers.getAddress(applicationId)) {\n logger.info(`Signature validation failed: Mismatch between derived appId (${appId}) and provided applicationId (${applicationId})`);\n throw new InvalidSignatureError(`Signature does not match the application id: ${appId}`);\n }\n\n logger.info(`Signature validated successfully for applicationId: ${applicationId}`);\n } catch (err) {\n logger.info(`Signature validation failed: ${(err as Error).message}`);\n if (err instanceof InvalidSignatureError) {\n throw err;\n }\n throw new InvalidSignatureError(`Failed to validate signature: ${(err as Error).message}`);\n }\n}\n\n\n/**\n * Validates the context object\n * @param context - The context object to validate\n * @throws InvalidParamError if the context object is not valid\n */\nexport function validateContext(context: Context): void {\n if (!context.contextAddress) {\n logger.info(`Context validation failed: Provided context address in context is not valid`);\n throw new InvalidParamError(`The provided context address in context is not valid`);\n }\n\n if (!context.contextMessage) {\n logger.info(`Context validation failed: Provided context message in context is not valid`);\n throw new InvalidParamError(`The provided context message in context is not valid`);\n }\n\n validateFunctionParams([\n { input: context.contextAddress, paramName: 'contextAddress', isString: true },\n { input: context.contextMessage, paramName: 'contextMessage', isString: true }\n ], 'validateContext');\n}\n\n/**\n * Validates the options object\n * @param options - The options object to validate\n * @throws InvalidParamError if the options object is not valid\n */\nexport function validateOptions(options: ProofRequestOptions): void {\n if (options.acceptAiProviders && typeof options.acceptAiProviders !== 'boolean') {\n logger.info(`Options validation failed: Provided acceptAiProviders in options is not valid`);\n throw new InvalidParamError(`The provided acceptAiProviders in options is not valid`);\n }\n\n if (options.log && typeof options.log !== 'boolean') {\n logger.info(`Options validation failed: Provided log in options is not valid`);\n throw new InvalidParamError(`The provided log in options is not valid`);\n }\n\n if (options.providerVersion && typeof options.providerVersion !== 'string') {\n logger.info(`Options validation failed: Provided providerVersion in options is not valid`);\n throw new InvalidParamError(`The provided providerVersion in options is not valid`);\n }\n}\n\n/**\n * Validates the modalOptions object\n * @param modalOptions - The modalOptions object to validate\n * @param functionName - The name of the function calling this validation\n * @param paramPrefix - Optional prefix for parameter names (e.g., 'modalOptions.')\n * @throws InvalidParamError if the modalOptions object is not valid\n */\nexport function validateModalOptions(modalOptions: ModalOptions, functionName: string, paramPrefix: string = ''): void {\n if (modalOptions.title !== undefined) {\n validateFunctionParams([\n { input: modalOptions.title, paramName: `${paramPrefix}title`, isString: true }\n ], functionName);\n }\n\n if (modalOptions.description !== undefined) {\n validateFunctionParams([\n { input: modalOptions.description, paramName: `${paramPrefix}description`, isString: true }\n ], functionName);\n }\n\n if (modalOptions.extensionUrl !== undefined) {\n validateURL(modalOptions.extensionUrl, functionName);\n validateFunctionParams([\n { input: modalOptions.extensionUrl, paramName: `${paramPrefix}extensionUrl`, isString: true }\n ], functionName);\n }\n\n if (modalOptions.darkTheme !== undefined) {\n if (typeof modalOptions.darkTheme !== 'boolean') {\n throw new InvalidParamError(`${paramPrefix}darkTheme prop must be a boolean`);\n }\n validateFunctionParams([\n { input: modalOptions.darkTheme, paramName: `${paramPrefix}darkTheme` }\n ], functionName);\n }\n\n if (modalOptions.modalPopupTimer !== undefined) {\n if (typeof modalOptions.modalPopupTimer !== 'number' || modalOptions.modalPopupTimer <= 0 || !Number.isInteger(modalOptions.modalPopupTimer)) {\n throw new InvalidParamError(`${paramPrefix}modalPopupTimer prop must be a valid time in minutes`);\n }\n validateFunctionParams([\n { input: modalOptions.modalPopupTimer, paramName: `${paramPrefix}modalPopupTimer` }\n ], functionName);\n }\n\n if (modalOptions.showExtensionInstallButton !== undefined) {\n if (typeof modalOptions.showExtensionInstallButton !== 'boolean') {\n throw new InvalidParamError(`${paramPrefix}showExtensionInstallButton prop must be a boolean`);\n }\n validateFunctionParams([\n { input: modalOptions.showExtensionInstallButton, paramName: `${paramPrefix}showExtensionInstallButton` }\n ], functionName);\n }\n}\n\n\n\n","import {\n InitSessionError,\n UpdateSessionError,\n StatusUrlError\n} from \"./errors\";\nimport { InitSessionResponse, SessionStatus, StatusUrlResponse } from \"./types\";\nimport { validateFunctionParams } from \"./validationUtils\";\nimport { BACKEND_BASE_URL, constants } from './constants';\nimport loggerModule from './logger';\nconst logger = loggerModule.logger;\n\n/**\n * Initializes a session with the provided parameters\n * @param providerId - The ID of the provider\n * @param appId - The ID of the application\n * @param timestamp - The timestamp of the request\n * @param signature - The signature for authentication\n * @returns A promise that resolves to an InitSessionResponse\n * @throws InitSessionError if the session initialization fails\n */\nexport async function initSession(\n providerId: string,\n appId: string,\n timestamp: string,\n signature: string,\n versionNumber?: string\n): Promise<InitSessionResponse> {\n logger.info(`Initializing session for providerId: ${providerId}, appId: ${appId}`);\n try {\n const response = await fetch(`${BACKEND_BASE_URL}/api/sdk/init/session/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ providerId, appId, timestamp, signature, versionNumber })\n });\n\n const res = await response.json();\n\n if (!response.ok) {\n logger.info(`Session initialization failed: ${res.message || 'Unknown error'}`);\n throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`);\n }\n\n return res as InitSessionResponse;\n } catch (err) {\n logger.info(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`, err);\n throw err;\n }\n}\n\n/**\n * Updates the status of an existing session\n * @param sessionId - The ID of the session to update\n * @param status - The new status of the session\n * @returns A promise that resolves to the update response\n * @throws UpdateSessionError if the session update fails\n */\nexport async function updateSession(sessionId: string, status: SessionStatus) {\n logger.info(`Updating session status for sessionId: ${sessionId}, new status: ${status}`);\n validateFunctionParams(\n [{ input: sessionId, paramName: 'sessionId', isString: true }],\n 'updateSession'\n );\n\n try {\n const response = await fetch(`${BACKEND_BASE_URL}/api/sdk/update/session/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ sessionId, status })\n });\n\n const res = await response.json();\n\n if (!response.ok) {\n const errorMessage = `Error updating session with sessionId: ${sessionId}. Status Code: ${response.status}`;\n logger.info(errorMessage, res);\n throw new UpdateSessionError(errorMessage);\n }\n\n logger.info(`Session status updated successfully for sessionId: ${sessionId}`);\n return res;\n } catch (err) {\n const errorMessage = `Failed to update session with sessionId: ${sessionId}`;\n logger.info(errorMessage, err);\n throw new UpdateSessionError(`Error updating session with sessionId: ${sessionId}`);\n }\n}\n\n/**\n * Fetches the status URL for a given session ID\n * @param sessionId - The ID of the session to fetch the status URL for\n * @returns A promise that resolves to a StatusUrlResponse\n * @throws StatusUrlError if the status URL fetch fails\n */\nexport async function fetchStatusUrl(sessionId: string): Promise<StatusUrlResponse> {\n validateFunctionParams(\n [{ input: sessionId, paramName: 'sessionId', isString: true }],\n 'fetchStatusUrl'\n );\n\n try {\n const response = await fetch(`${constants.DEFAULT_RECLAIM_STATUS_URL}${sessionId}`, {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n });\n\n const res = await response.json();\n\n if (!response.ok) {\n const errorMessage = `Error fetching status URL for sessionId: ${sessionId}. Status Code: ${response.status}`;\n logger.info(errorMessage, res);\n throw new StatusUrlError(errorMessage);\n }\n\n return res as StatusUrlResponse;\n } catch (err) {\n const errorMessage = `Failed to fetch status URL for sessionId: ${sessionId}`;\n logger.info(errorMessage, err);\n throw new StatusUrlError(`Error fetching status URL for sessionId: ${sessionId}`);\n }\n}\n\n\n","import { ethers } from \"ethers\";\nimport { WitnessData } from \"./interfaces\";\nimport { SignedClaim, TemplateData } from \"./types\";\nimport { createSignDataForClaim, fetchWitnessListForClaim } from \"../witness\";\nimport { BACKEND_BASE_URL, constants } from \"./constants\";\nimport { replaceAll } from \"./helper\";\nimport { validateURL } from \"./validationUtils\";\nimport { makeBeacon } from \"../smart-contract\";\nimport { ProofNotVerifiedError } from \"./errors\";\nimport loggerModule from './logger';\nconst logger = loggerModule.logger;\n\n\n/**\n * Retrieves a shortened URL for the given URL\n * @param url - The URL to be shortened\n * @returns A promise that resolves to the shortened URL, or the original URL if shortening fails\n */\nexport async function getShortenedUrl(url: string): Promise<string> {\n logger.info(`Attempting to shorten URL: ${url}`);\n try {\n validateURL(url, 'getShortenedUrl')\n const response = await fetch(`${BACKEND_BASE_URL}/api/sdk/shortener`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ fullUrl: url })\n })\n const res = await response.json()\n if (!response.ok) {\n logger.info(`Failed to shorten URL: ${url}, Response: ${JSON.stringify(res)}`);\n return url;\n }\n const shortenedVerificationUrl = res.result.shortUrl\n return shortenedVerificationUrl\n } catch (err) {\n logger.info(`Error shortening URL: ${url}, Error: ${err}`);\n return url\n }\n}\n\n/**\n * Creates a link with embedded template data\n * @param templateData - The data to be embedded in the link\n * @param sharePagePath - The path to the share page (optional)\n * @returns A promise that resolves to the created link (shortened if possible)\n */\nexport async function createLinkWithTemplateData(templateData: TemplateData, sharePagePath?: string): Promise<string> {\n let template = encodeURIComponent(JSON.stringify(templateData))\n template = replaceAll(template, '(', '%28')\n template = replaceAll(template, ')', '%29')\n const fullLink = sharePagePath ? `${sharePagePath}/?template=${template}` : `${constants.RECLAIM_SHARE_URL}${template}`\n try {\n const shortenedLink = await getShortenedUrl(fullLink)\n return shortenedLink;\n } catch (err) {\n logger.info(`Error creating link for sessionId: ${templateData.sessionId}, Error: ${err}`);\n return fullLink;\n }\n}\n\n/**\n * Retrieves the list of witnesses for a given claim\n * @param epoch - The epoch number\n * @param identifier - The claim identifier\n * @param timestampS - The timestamp in seconds\n * @returns A promise that resolves to an array of witness addresses\n * @throws Error if no beacon is available\n */\nexport async function getWitnessesForClaim(\n epoch: number,\n identifier: string,\n timestampS: number\n): Promise<string[]> {\n const beacon = makeBeacon()\n if (!beacon) {\n logger.info('No beacon available for getting witnesses');\n throw new Error('No beacon available');\n }\n const state = await beacon.getState(epoch)\n const witnessList = fetchWitnessListForClaim(state, identifier, timestampS)\n const witnesses = witnessList.map((w: WitnessData) => w.id.toLowerCase())\n return witnesses;\n}\n\n/**\n * Recovers the signers' addresses from a signed claim\n * @param claim - The signed claim object\n * @param signatures - The signatures associated with the claim\n * @returns An array of recovered signer addresses\n */\nexport function recoverSignersOfSignedClaim({\n claim,\n signatures\n}: SignedClaim): string[] {\n const dataStr = createSignDataForClaim({ ...claim })\n const signers = signatures.map(signature =>\n ethers.verifyMessage(dataStr, ethers.hexlify(signature)).toLowerCase()\n )\n return signers;\n}\n\n/**\n * Asserts that a signed claim is valid by checking if all expected witnesses have signed\n * @param claim - The signed claim to validate\n * @param expectedWitnessAddresses - An array of expected witness addresses\n * @throws ProofNotVerifiedError if any expected witness signature is missing\n */\nexport function assertValidSignedClaim(\n claim: SignedClaim,\n expectedWitnessAddresses: string[]\n): void {\n const witnessAddresses = recoverSignersOfSignedClaim(claim)\n const witnessesNotSeen = new Set(expectedWitnessAddresses)\n for (const witness of witnessAddresses) {\n if (witnessesNotSeen.has(witness)) {\n witnessesNotSeen.delete(witness)\n }\n }\n\n if (witnessesNotSeen.size > 0) {\n const missingWitnesses = Array.from(witnessesNotSeen).join(', ');\n logger.info(`Claim validation failed. Missing signatures from: ${missingWitnesses}`);\n throw new ProofNotVerifiedError(\n `Missing signatures from ${missingWitnesses}`\n )\n }\n}","/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n\nimport { Contract } from 'ethers';\n\nconst _abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'address',\n name: 'previousAdmin',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'address',\n name: 'newAdmin',\n type: 'address',\n },\n ],\n name: 'AdminChanged',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'beacon',\n type: 'address',\n },\n ],\n name: 'BeaconUpgraded',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n components: [\n {\n internalType: 'uint32',\n name: 'id',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampStart',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampEnd',\n type: 'uint32',\n },\n {\n components: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n internalType: 'struct Reclaim.Witness[]',\n name: 'witnesses',\n type: 'tuple[]',\n },\n {\n internalType: 'uint8',\n name: 'minimumWitnessesForClaimCreation',\n type: 'uint8',\n },\n ],\n indexed: false,\n internalType: 'struct Reclaim.Epoch',\n name: 'epoch',\n type: 'tuple',\n },\n ],\n name: 'EpochAdded',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'uint8',\n name: 'version',\n type: 'uint8',\n },\n ],\n name: 'Initialized',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'previousOwner',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'newOwner',\n type: 'address',\n },\n ],\n name: 'OwnershipTransferred',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'implementation',\n type: 'address',\n },\n ],\n name: 'Upgraded',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'witnessAddress',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n name: 'addAsWitness',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'addNewEpoch',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint32',\n name: 'epochNum',\n type: 'uint32',\n },\n {\n components: [\n {\n internalType: 'string',\n name: 'provider',\n type: 'string',\n },\n {\n internalType: 'string',\n name: 'parameters',\n type: 'string',\n },\n {\n internalType: 'string',\n name: 'context',\n type: 'string',\n },\n ],\n internalType: 'struct Claims.ClaimInfo',\n name: 'claimInfo',\n type: 'tuple',\n },\n {\n components: [\n {\n internalType: 'bytes32',\n name: 'identifier',\n type: 'bytes32',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n {\n internalType: 'uint32',\n name: 'timestampS',\n type: 'uint32',\n },\n {\n internalType: 'uint256',\n name: 'epoch',\n type: 'uint256',\n },\n ],\n internalType: 'struct Claims.CompleteClaimData',\n name: 'claimData',\n type: 'tuple',\n },\n {\n internalType: 'bytes[]',\n name: 'signatures',\n type: 'bytes[]',\n },\n ],\n name: 'assertValidEpochAndSignedClaim',\n outputs: [],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'currentEpoch',\n outputs: [\n {\n internalType: 'uint32',\n name: '',\n type: 'uint32',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'epochDurationS',\n outputs: [\n {\n internalType: 'uint32',\n name: '',\n type: 'uint32',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'epochs',\n outputs: [\n {\n internalType: 'uint32',\n name: 'id',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampStart',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampEnd',\n type: 'uint32',\n },\n {\n internalType: 'uint8',\n name: 'minimumWitnessesForClaimCreation',\n type: 'uint8',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint32',\n name: 'epoch',\n type: 'uint32',\n },\n ],\n name: 'fetchEpoch',\n outputs: [\n {\n components: [\n {\n internalType: 'uint32',\n name: 'id',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampStart',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampEnd',\n type: 'uint32',\n },\n {\n components: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n internalType: 'struct Reclaim.Witness[]',\n name: 'witnesses',\n type: 'tuple[]',\n },\n {\n internalType: 'uint8',\n name: 'minimumWitnessesForClaimCreation',\n type: 'uint8',\n },\n ],\n internalType: 'struct Reclaim.Epoch',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint32',\n name: 'epoch',\n type: 'uint32',\n },\n {\n internalType: 'bytes32',\n name: 'identifier',\n type: 'bytes32',\n },\n {\n internalType: 'uint32',\n name: 'timestampS',\n type: 'uint32',\n },\n ],\n name: 'fetchWitnessesForClaim',\n outputs: [\n {\n components: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n internalType: 'struct Reclaim.Witness[]',\n name: '',\n type: 'tuple[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'initialize',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'minimumWitnessesForClaimCreation',\n outputs: [\n {\n internalType: 'uint8',\n name: '',\n type: 'uint8',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'owner',\n outputs: [\n {\n internalType: 'address',\n name: '',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'proxiableUUID',\n outputs: [\n {\n internalType: 'bytes32',\n name: '',\n type: 'bytes32',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'witnessAddress',\n type: 'address',\n },\n ],\n name: 'removeAsWitness',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'renounceOwnership',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'newOwner',\n type: 'address',\n },\n ],\n name: 'transferOwnership',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'isWhitelisted',\n type: 'bool',\n },\n ],\n name: 'updateWitnessWhitelist',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'newImplementation',\n type: 'address',\n },\n ],\n name: 'upgradeTo',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'newImplementation',\n type: 'address',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'upgradeToAndCall',\n outputs: [],\n stateMutability: 'payable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'witnesses',\n outputs: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const;\n\nexport class Reclaim__factory {\n static readonly abi = _abi;\n\n static connect(address: string, signerOrProvider: any): Contract {\n return new Contract(address, _abi, signerOrProvider);\n }\n}\n","{\n \"0x1a4\": {\n \"chainName\": \"opt-goerli\",\n \"address\": \"0xF93F605142Fb1Efad7Aa58253dDffF67775b4520\",\n \"rpcUrl\": \"https://opt-goerli.g.alchemy.com/v2/rksDkSUXd2dyk2ANy_zzODknx_AAokui\"\n },\n \"0xaa37dc\": {\n \"chainName\": \"opt-sepolia\",\n \"address\": \"0x6D0f81BDA11995f25921aAd5B43359630E65Ca96\",\n \"rpcUrl\": \"https://opt-sepolia.g.alchemy.com/v2/aO1-SfG4oFRLyAiLREqzyAUu0HTCwHgs\"\n}\n\n}\n","import type { Beacon, BeaconState } from './utils/interfaces';\nimport { Reclaim__factory as ReclaimFactory } from './contract-types';\nimport CONTRACTS_CONFIG from './contract-types/config.json';\nimport { Contract, ethers } from 'ethers';\n\nconst DEFAULT_CHAIN_ID = 11155420;\n\nexport function makeBeacon(chainId?: number): Beacon | undefined {\n chainId = chainId || DEFAULT_CHAIN_ID;\n const contract = getContract(chainId);\n if (contract) {\n return makeBeaconCacheable({\n async getState(epochId: number | undefined): Promise<BeaconState> {\n //@ts-ignore\n const epoch = await contract.fetchEpoch(epochId || 0);\n if (!epoch.id) {\n throw new Error(`Invalid epoch ID: ${epochId}`);\n }\n\n return {\n epoch: epoch.id,\n witnesses: epoch.witnesses.map((w: any) => ({\n id: w.addr.toLowerCase(),\n url: w.host,\n })),\n witnessesRequiredForClaim: epoch.minimumWitnessesForClaimCreation,\n nextEpochTimestampS: epoch.timestampEnd,\n };\n },\n });\n } else {\n return undefined;\n }\n}\n\nexport function makeBeaconCacheable(beacon: Beacon): Beacon {\n const cache: { [epochId: number]: Promise<BeaconState> } = {};\n\n return {\n ...beacon,\n async getState(epochId: number | undefined): Promise<BeaconState> {\n if (!epochId) {\n // TODO: add cache here\n const state = await beacon.getState();\n return state;\n }\n\n const key = epochId;\n\n if (!cache[key]) {\n cache[key] = beacon.getState(epochId);\n }\n\n return cache[key] as unknown as BeaconState;\n },\n };\n}\n\nconst existingContractsMap: { [chain: string]: Contract } = {};\n\nfunction getContract(chainId: number): Contract {\n const chainKey = `0x${chainId.toString(16)}`;\n if (!existingContractsMap[chainKey]) {\n const contractData =\n CONTRACTS_CONFIG[chainKey as keyof typeof CONTRACTS_CONFIG];\n if (!contractData) {\n throw new Error(`Unsupported chain: \"${chainKey}\"`);\n }\n\n const rpcProvider = new ethers.JsonRpcProvider(contractData.rpcUrl);\n existingContractsMap[chainKey] = ReclaimFactory.connect(\n contractData.address,\n rpcProvider\n );\n }\n\n return existingContractsMap[chainKey] as Contract;\n}\n","import loggerModule from './logger';\nimport { ModalOptions } from './types';\nimport { constants } from './constants';\nconst logger = loggerModule.logger;\n\nexport class QRCodeModal {\n private modalId: string;\n private options: ModalOptions;\n private autoCloseTimer?: NodeJS.Timeout;\n private countdownTimer?: NodeJS.Timeout;\n private countdownSeconds: number = 60;\n\n constructor(options: ModalOptions = {}) {\n this.modalId = 'reclaim-qr-modal';\n this.options = {\n title: 'Verify with Reclaim',\n description: 'Scan the QR code with your mobile device to complete verification',\n extensionUrl: constants.CHROME_EXTENSION_URL,\n darkTheme: false,\n modalPopupTimer: 1, // default to 1 minute\n showExtensionInstallButton: false, // default to false\n ...options\n };\n }\n\n async show(requestUrl: string): Promise<void> {\n try {\n // Remove existing modal if present\n this.close();\n\n // Create modal HTML\n const modalHTML = this.createModalHTML();\n\n // Add modal to DOM\n document.body.insertAdjacentHTML('beforeend', modalHTML);\n\n // Generate QR code\n await this.generateQRCode(requestUrl, 'reclaim-qr-code');\n\n // Add event listeners\n this.addEventListeners();\n\n // Start auto-close timer\n this.startAutoCloseTimer();\n\n } catch (error) {\n logger.info('Error showing QR code modal:', error);\n throw error;\n }\n }\n\n close(): void {\n // Clear timers\n if (this.autoCloseTimer) {\n clearTimeout(this.autoCloseTimer);\n this.autoCloseTimer = undefined;\n }\n if (this.countdownTimer) {\n clearInterval(this.countdownTimer);\n this.countdownTimer = undefined;\n }\n\n const modal = document.getElementById(this.modalId);\n if (modal) {\n modal.remove();\n }\n if (this.options.onClose) {\n this.options.onClose();\n }\n }\n\n private getThemeStyles() {\n const isDark = this.options.darkTheme;\n\n return {\n modalBackground: isDark ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.5)',\n cardBackground: isDark ? '#1f2937' : 'white',\n titleColor: isDark ? '#f9fafb' : '#1f2937',\n textColor: isDark ? '#d1d5db' : '#6b7280',\n qrBackground: isDark ? '#374151' : '#f9fafb',\n tipBackground: isDark ? '#1e40af' : '#f0f9ff',\n tipBorder: isDark ? '#1e40af' : '#e0f2fe',\n tipTextColor: isDark ? '#dbeafe' : '#0369a1',\n buttonBackground: isDark ? '#374151' : '#f3f4f6',\n buttonColor: isDark ? '#f9fafb' : '#374151',\n buttonHoverBackground: isDark ? '#4b5563' : '#e5e7eb',\n countdownColor: isDark ? '#6b7280' : '#9ca3af',\n progressBackground: isDark ? '#4b5563' : '#e5e7eb',\n progressGradient: isDark\n ? 'linear-gradient(90deg, #3b82f6 0%, #2563eb 50%, #1d4ed8 100%)'\n : 'linear-gradient(90deg, #2563eb 0%, #1d4ed8 50%, #1e40af 100%)',\n linkColor: isDark ? '#60a5fa' : '#2563eb',\n extensionButtonBackground: isDark ? '#1e40af' : '#2563eb',\n extensionButtonHover: isDark ? '#1d4ed8' : '#1d4ed8'\n };\n }\n\n private createModalHTML(): string {\n const styles = this.getThemeStyles();\n\n return `\n <div id=\"${this.modalId}\" style=\"\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: ${styles.modalBackground};\n display: flex;\n justify-content: center;\n align-items: center;\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n \">\n <div style=\"\n background: ${styles.cardBackground};\n border-radius: 12px;\n padding: 32px;\n max-width: 400px;\n width: 90%;\n text-align: center;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n position: relative;\n \">\n <button id=\"reclaim-close-modal\" style=\"\n position: absolute;\n top: 16px;\n right: 16px;\n background: none;\n border: none;\n cursor: pointer;\n padding: 4px;\n border-radius: 6px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background-color 0.2s;\n width: 32px;\n height: 32px;\n \"\n onmouseover=\"this.style.backgroundColor='${styles.buttonHoverBackground}'\"\n onmouseout=\"this.style.backgroundColor='transparent'\"\n title=\"Close modal\">\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M12 4L4 12M4 4L12 12\" stroke=\"${styles.buttonColor}\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>\n </button>\n \n <h2 style=\"\n margin: 0 0 16px 0;\n font-size: 24px;\n font-weight: 600;\n color: ${styles.titleColor};\n \">${this.options.title}</h2>\n \n <p style=\"\n margin: 0 0 24px 0;\n color: ${styles.textColor};\n font-size: 14px;\n line-height: 1.5;\n \">${this.options.description}</p>\n \n <div id=\"reclaim-qr-code\" style=\"\n margin: 0 auto 24px auto;\n background: ${styles.qrBackground};\n border-radius: 8px;\n display: inline-block;\n \"></div>\n \n ${this.options.showExtensionInstallButton ? `\n <div style=\"\n margin-bottom: 24px;\n padding: 16px;\n background: ${styles.tipBackground};\n border: 1px solid ${styles.tipBorder};\n border-radius: 8px;\n \">\n <p style=\"\n margin: 0 0 12px 0;\n font-size: 14px;\n color: ${styles.tipTextColor};\n font-weight: 500;\n \">💡 For a better experience</p>\n <p style=\"\n margin: 0 0 12px 0;\n font-size: 13px;\n color: ${styles.tipTextColor};\n line-height: 1.4;\n \">Install our browser extension for seamless verification without QR codes</p>\n <a href=\"${this.options.extensionUrl}\" \n target=\"_blank\" \n style=\"\n display: inline-block;\n background: ${styles.extensionButtonBackground};\n color: white;\n text-decoration: none;\n padding: 8px 16px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n transition: background-color 0.2s;\n \"\n onmouseover=\"this.style.backgroundColor='${styles.extensionButtonHover}'\"\n onmouseout=\"this.style.backgroundColor='${styles.extensionButtonBackground}'\">\n Install Extension\n </a>\n </div>` : ''}\n \n <div style=\"margin-top: 16px;\">\n <div id=\"reclaim-countdown\" style=\"\n font-size: 12px;\n color: ${styles.countdownColor};\n font-weight: 400;\n margin-bottom: 8px;\n \">Auto-close in 1:00</div>\n \n <div style=\"\n width: 100%;\n height: 4px;\n background-color: ${styles.progressBackground};\n border-radius: 2px;\n overflow: hidden;\n \">\n <div id=\"reclaim-progress-bar\" style=\"\n width: 100%;\n height: 100%;\n background: ${styles.progressGradient};\n border-radius: 2px;\n transition: width 1s linear;\n \"></div>\n </div>\n </div>\n </div>\n </div>\n `\n }\n\n private async generateQRCode(text: string, containerId: string): Promise<void> {\n try {\n // Simple QR code generation using a public API\n // In production, you might want to use a proper QR code library\n const qrCodeUrl = `${constants.QR_CODE_API_URL}?size=200x200&data=${encodeURIComponent(text)}`;\n\n const container = document.getElementById(containerId);\n const styles = this.getThemeStyles();\n\n if (container) {\n container.innerHTML = `\n <img src=\"${qrCodeUrl}\" \n alt=\"QR Code for Reclaim verification\" \n style=\"width: 200px; height: 200px; border-radius: 4px;\"\n onerror=\"this.style.display='none'; this.nextElementSibling.style.display='block';\">\n <div style=\"display: none; padding: 20px; color: ${styles.textColor}; font-size: 14px;\">\n QR code could not be loaded.<br>\n <a href=\"${text}\" target=\"_blank\" style=\"color: ${styles.linkColor}; text-decoration: underline;\">\n Click here to open verification link\n </a>\n </div>\n `;\n }\n } catch (error) {\n logger.info('Error generating QR code:', error);\n // Fallback to text link\n const container = document.getElementById(containerId);\n const styles = this.getThemeStyles();\n\n if (container) {\n container.innerHTML = `\n <div style=\"padding: 20px; color: ${styles.textColor}; font-size: 14px;\">\n <a href=\"${text}\" target=\"_blank\" style=\"color: ${styles.linkColor}; text-decoration: underline;\">\n Click here to open verification link\n </a>\n </div>\n `;\n }\n }\n }\n\n private addEventListeners(): void {\n const closeButton = document.getElementById('reclaim-close-modal');\n const modal = document.getElementById(this.modalId);\n\n const closeModal = () => {\n this.close();\n };\n\n if (closeButton) {\n closeButton.addEventListener('click', closeModal);\n }\n\n // Close on backdrop click\n if (modal) {\n modal.addEventListener('click', (e) => {\n if (e.target === modal) {\n closeModal();\n }\n });\n }\n\n // Close on escape key\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n closeModal();\n document.removeEventListener('keydown', handleEscape);\n }\n };\n document.addEventListener('keydown', handleEscape);\n }\n\n private startAutoCloseTimer(): void {\n this.countdownSeconds = (this.options.modalPopupTimer || 1) * 60; // default to 1 minute\n\n // Update countdown display immediately\n this.updateCountdownDisplay();\n\n // Start countdown timer (updates every second)\n this.countdownTimer = setInterval(() => {\n this.countdownSeconds--;\n this.updateCountdownDisplay();\n\n if (this.countdownSeconds <= 0) {\n this.close();\n }\n }, 1000);\n\n // Set auto-close timer for the number of minutes specified in the options in milliseconds\n const autoCloseMs = (this.options.modalPopupTimer || 1) * 60 * 1000;\n this.autoCloseTimer = setTimeout(() => {\n this.close();\n }, autoCloseMs);\n }\n\n private updateCountdownDisplay(): void {\n const countdownElement = document.getElementById('reclaim-countdown');\n const progressBar = document.getElementById('reclaim-progress-bar');\n\n if (countdownElement) {\n const minutes = Math.floor(this.countdownSeconds / 60);\n const seconds = this.countdownSeconds % 60;\n const timeString = `${minutes}:${seconds.toString().padStart(2, '0')}`;\n countdownElement.textContent = `Auto-close in ${timeString}`;\n }\n\n if (progressBar) {\n // Calculate progress percentage (reverse: starts at 100%, goes to 0%)\n const totalSeconds = (this.options.modalPopupTimer || 1) * 60;\n const progressPercentage = (this.countdownSeconds / totalSeconds) * 100;\n progressBar.style.width = `${progressPercentage}%`;\n }\n }\n}","import { DeviceType } from \"./types\";\n\nconst navigatorDefined = typeof navigator !== 'undefined';\nconst windowDefined = typeof window !== 'undefined';\n\nconst userAgent = navigatorDefined ? navigator.userAgent.toLowerCase() : '';\nconst userAgentData = navigatorDefined ? (navigator as Navigator & {\n userAgentData?: {\n platform: string;\n brands?: { brand: string; version: string }[];\n }\n}).userAgentData : undefined;\n\n// Cache for device detection results\nlet cachedDeviceType: DeviceType.DESKTOP | DeviceType.MOBILE | null = null;\nlet cachedMobileType: DeviceType.ANDROID | DeviceType.IOS | null = null;\n\n/**\n * Safe wrapper for window.matchMedia\n */\nfunction safeMatchMedia(query: string): boolean {\n try {\n return window.matchMedia?.(query)?.matches || false;\n } catch {\n return false;\n }\n}\n\n/**\n * Safe wrapper for CSS.supports\n */\nfunction safeCSSSupports(property: string, value: string): boolean {\n try {\n return CSS?.supports?.(property, value) || false;\n } catch {\n return false;\n }\n}\n\n/**\n * Safe wrapper for document.querySelector\n */\nfunction safeQuerySelector(selector: string): boolean {\n try {\n return document?.querySelector?.(selector) !== null;\n } catch {\n return false;\n }\n}\n\n/**\n * Highly accurate device type detection - returns only 'desktop' or 'mobile'\n * Uses multiple detection methods and scoring system for maximum accuracy\n * @returns {DeviceType.DESKTOP | DeviceType.MOBILE} The detected device type\n */\nexport function getDeviceType(): DeviceType.DESKTOP | DeviceType.MOBILE {\n // Return cached result if available\n if (cachedDeviceType !== null) {\n return cachedDeviceType;\n }\n\n // Early return for server-side rendering - assume desktop\n if (!navigatorDefined || !windowDefined) {\n return DeviceType.DESKTOP;\n }\n\n let mobileScore = 0;\n const CONFIDENCE_THRESHOLD = 3; // Need at least 3 points to be considered mobile\n \n // ====== Device Characteristics ======\n \n // Screen dimensions\n const screenWidth = window.innerWidth || window.screen?.width || 0;\n const screenHeight = window.innerHeight || window.screen?.height || 0;\n const hasSmallScreen = screenWidth <= 480 || screenHeight <= 480;\n const hasLargeScreen = screenWidth > 1024 && screenHeight > 768;\n \n // Touch capabilities\n const hasTouch = 'ontouchstart' in window || \n (navigatorDefined && navigator.maxTouchPoints > 0);\n const hasPreciseMouse = safeMatchMedia('(pointer: fine)');\n const canHover = safeMatchMedia('(hover: hover)');\n const hasMouseAndTouch = hasTouch && hasPreciseMouse; // Touchscreen laptop\n \n // Windows touch laptop detection (used for exceptions)\n const isWindowsTouchLaptop = /Windows/i.test(userAgent) && \n hasPreciseMouse && \n hasTouch;\n \n // ====== Mobile Indicators (Add Points) ======\n \n // Touch without mouse = likely mobile (+2 points)\n // Touch with mouse = touchscreen laptop (+1 point)\n if (hasTouch && !hasMouseAndTouch) {\n mobileScore += 2;\n } else if (hasMouseAndTouch) {\n mobileScore += 1;\n }\n \n // Small screen is mobile indicator (+2 points)\n // Exception: Windows touch laptops with precise mouse should not be penalized for small screens\n if (hasSmallScreen && !isWindowsTouchLaptop) {\n mobileScore += 2;\n }\n \n // Mobile user agent is strong indicator (+3 points)\n const hasMobileUserAgent = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(userAgent);\n if (hasMobileUserAgent) {\n mobileScore += 3;\n }\n \n // Mobile APIs only count if combined with other mobile signs (+2 points)\n // Exception: Desktop Safari and Windows touch laptops have mobile APIs but should not be considered mobile\n const hasMobileAPIs = 'orientation' in window || \n 'DeviceMotionEvent' in window ||\n 'DeviceOrientationEvent' in window;\n const isDesktopSafari = /Safari/i.test(userAgent) && \n !/Mobile/i.test(userAgent) && \n /Mac|Intel/i.test(userAgent);\n if (hasMobileAPIs && (hasSmallScreen || hasMobileUserAgent) && !isDesktopSafari && !isWindowsTouchLaptop) {\n mobileScore += 2;\n }\n \n // High DPI with small screen = mobile (+1 point)\n const hasHighDPI = window.devicePixelRatio > 1.5;\n if (hasHighDPI && hasSmallScreen) {\n mobileScore += 1;\n }\n \n // Viewport meta tag with small screen = mobile optimized (+1 point)\n const hasViewportMeta = safeQuerySelector('meta[name=\"viewport\"]');\n if (hasViewportMeta && hasSmallScreen) {\n mobileScore += 1;\n }\n \n // iPad Pro special case: Mac user agent with touch (+2 points)\n const isPadProInDesktopMode = userAgent.includes('macintosh') && hasTouch;\n if (isPadProInDesktopMode) {\n mobileScore += 2;\n }\n \n // ====== Desktop Indicators (Subtract Points) ======\n \n // Large screen with mouse = desktop (-3 points)\n if (hasLargeScreen && hasPreciseMouse) {\n mobileScore -= 3;\n } \n // Large screen without touch = desktop (-2 points)\n else if (hasLargeScreen && !hasTouch) {\n mobileScore -= 2;\n }\n \n // Can hover with precise pointer = has real mouse (-2 points)\n if (hasPreciseMouse && canHover) {\n mobileScore -= 2;\n }\n \n // Windows user agent = strong desktop indicator (-3 points)\n const isWindowsDesktop = /Windows/i.test(userAgent) && !hasMobileUserAgent;\n if (isWindowsDesktop) {\n mobileScore -= 3;\n }\n\n // Cache and return the result\n cachedDeviceType = mobileScore >= CONFIDENCE_THRESHOLD ? DeviceType.MOBILE : DeviceType.DESKTOP;\n return cachedDeviceType;\n}\n\n/**\n * Highly accurate mobile device type detection - returns only 'android' or 'ios'\n * Should only be called when getDeviceType() returns 'mobile'\n * @returns {DeviceType.ANDROID | DeviceType.IOS} The detected mobile device type\n */\nexport function getMobileDeviceType(): DeviceType.ANDROID | DeviceType.IOS {\n // Return cached result if available\n if (cachedMobileType !== null) {\n return cachedMobileType;\n }\n\n // Early return for server-side rendering - default to Android\n if (!navigatorDefined || !windowDefined) {\n return DeviceType.ANDROID;\n }\n\n const ua = navigator.userAgent;\n \n // ====== iOS Detection ======\n \n // Direct iOS device detection\n const hasIOSDeviceName = /iPad|iPhone|iPod/i.test(ua);\n if (hasIOSDeviceName) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // iPad Pro detection (reports as Mac but has touch)\n const isMacWithTouch = /Macintosh|MacIntel/i.test(ua) && 'ontouchstart' in window;\n const isMacOSWithTouch = userAgentData?.platform === 'macOS' && 'ontouchstart' in window;\n if (isMacWithTouch || isMacOSWithTouch) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // iOS-specific APIs\n const hasIOSPermissionAPI = typeof (window as any).DeviceMotionEvent?.requestPermission === 'function';\n const hasIOSTouchCallout = safeCSSSupports('-webkit-touch-callout', 'none');\n if (hasIOSPermissionAPI || hasIOSTouchCallout) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // Safari without Chrome (iOS WebKit) - but not desktop Safari\n const isIOSWebKit = /WebKit/i.test(ua) && \n !/Chrome|CriOS|Android/i.test(ua) && \n !/Macintosh|MacIntel/i.test(ua);\n if (isIOSWebKit) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // ====== Android Detection ======\n \n // Direct Android detection\n const hasAndroidKeyword = /Android/i.test(ua);\n if (hasAndroidKeyword) {\n cachedMobileType = DeviceType.ANDROID;\n return cachedMobileType;\n }\n \n // Mobile Chrome (usually Android)\n const isChromeOnMobile = (window as any).chrome && /Mobile/i.test(ua);\n if (isChromeOnMobile) {\n cachedMobileType = DeviceType.ANDROID;\n return cachedMobileType;\n }\n \n // Default fallback - Android is more common globally\n cachedMobileType = DeviceType.ANDROID;\n return cachedMobileType;\n}\n\n/**\n * Convenience method to check if current device is mobile\n * @returns {boolean} True if device is mobile\n */\nexport function isMobileDevice(): boolean {\n return getDeviceType() === DeviceType.MOBILE;\n}\n\n/**\n * Convenience method to check if current device is desktop\n * @returns {boolean} True if device is desktop\n */\nexport function isDesktopDevice(): boolean {\n return getDeviceType() === DeviceType.DESKTOP;\n}\n\n/**\n * Clear cached device detection results (useful for testing)\n */\nexport function clearDeviceCache(): void {\n cachedDeviceType = null;\n cachedMobileType = null;\n}\n\n// Export safe wrappers for testing\nexport { safeMatchMedia, safeCSSSupports, safeQuerySelector };"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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OAAO,SAAS,GAAG;AACjF,oBAAM,SAAS,kBAAkB,QAAQ;AACzC,kBAAI,KAAK,sDAAoD;AACzD,sBAAM,WAAW,MAAM,YAAY,MAAM;AACzC,oBAAI,CAAC,UAAU;AACX,kBAAAA,QAAO,KAAK,wBAAwB,KAAK,UAAU,MAAM,CAAC,EAAE;AAC5D,wBAAM,IAAI,sBAAsB;AAAA,gBACpC;AAAA,cACJ;AAEA,kBAAI,OAAO,WAAW,GAAG;AAErB,0BAAU,OAAO,CAAC,CAAC;AAAA,cACvB,OAAO;AACH,0BAAU,MAAM;AAAA,cACpB;AACA,mBAAK,cAAc;AACnB,yBAAK,UAAL,mBAAY;AAAA,YAChB;AAAA,UACJ,OAAO;AACH,gBAAI,kBAAkB,QAAQ,sEAAoD;AAC9E,oBAAM,IAAI,2BAA2B;AAAA,YACzC;AACA,gBAAI,kBAAkB,QAAQ,wDAC1B,kBAAkB,QAAQ,4DAA+C;AACzE,kBAAI,WAAW;AACX,0BAAU,yDAAyD;AAAA,cACvE;AACA,mBAAK,cAAc;AACnB,yBAAK,UAAL,mBAAY;AAAA,YAChB;AAAA,UACJ;AAAA,QACJ,SAAS,GAAG;AACR,cAAI,SAAS;AACT,oBAAQ,CAAU;AAAA,UACtB;AACA,eAAK,cAAc;AACnB,qBAAK,UAAL,mBAAY;AAAA,QAChB;AAAA,MACJ,IAAG,4BAA4B;AAE/B,WAAK,UAAU,IAAI,KAAK,WAAW,QAAQ;AAC3C,iCAA2B,KAAK,WAAW,KAAK,WAAW,OAAO;AAAA,IACtE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,aAAmB;AACf,QAAI,KAAK,OAAO;AACZ,WAAK,MAAM,MAAM;AACjB,MAAAA,QAAO,KAAK,sBAAsB;AAAA,IACtC;AAAA,EACJ;AACJ;","names":["exports","module","canonicalize","ClaimCreationType","DeviceType","import_ethers","import_canonicalize","logger","import_ethers","import_canonicalize","logger","canonicalize","logger","import_ethers","import_ethers","import_ethers","logger","logger","logger","proof","canonicalize","sdkVersion"]}
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/index.ts","../src/utils/interfaces.ts","../src/witness.ts","../src/utils/strings.ts","../src/utils/types.ts","../src/Reclaim.ts","../src/utils/errors.ts","../src/utils/logger.ts","../src/utils/helper.ts","../src/utils/constants.ts","../src/utils/validationUtils.ts","../src/utils/sessionUtils.ts","../src/utils/proofUtils.ts","../src/contract-types/contracts/factories/Reclaim__factory.ts","../src/contract-types/config.json","../src/smart-contract.ts","../src/utils/modalUtils.ts","../src/utils/device.ts"],"sourcesContent":["{\n \"name\": \"@reclaimprotocol/js-sdk\",\n \"version\": \"4.7.0\",\n \"description\": \"Designed to request proofs from the Reclaim protocol and manage the flow of claims and witness interactions.\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"keywords\": [\n \"reclaim\",\n \"protocol\",\n \"blockchain\",\n \"proof\",\n \"verification\",\n \"identity\",\n \"claims\",\n \"witness\",\n \"sdk\",\n \"javascript\",\n \"typescript\",\n \"decentralized\",\n \"web3\"\n ],\n \"files\": [\n \"dist\"\n ],\n \"tsup\": {\n \"entry\": [\n \"src/index.ts\"\n ],\n \"splitting\": false,\n \"sourcemap\": true,\n \"clean\": true\n },\n \"scripts\": {\n \"build\": \"sh scripts/build.sh\",\n \"release\": \"release-it\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:coverage\": \"jest --coverage\",\n \"commitlint\": \"commitlint --edit\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/reclaimprotocol/reclaim-js-sdk\"\n },\n \"author\": \"ali <ali@creatoros.co>\",\n \"license\": \"See License in <https://github.com/reclaimprotocol/.github/blob/main/LICENSE>\",\n \"bugs\": {\n \"url\": \"https://github.com/reclaimprotocol/reclaim-js-sdk/issues\"\n },\n \"homepage\": \"https://github.com/reclaimprotocol/reclaim-js-sdk/\",\n \"publishConfig\": {\n \"registry\": \"https://registry.npmjs.org/\",\n \"access\": \"public\"\n },\n \"release-it\": {\n \"git\": {\n \"commitMessage\": \"chore: release ${version}\",\n \"tagName\": \"v${version}\"\n },\n \"npm\": {\n \"publish\": true,\n \"tag\": \"latest\"\n },\n \"github\": {\n \"release\": true\n },\n \"plugins\": {\n \"@release-it/conventional-changelog\": {\n \"preset\": \"angular\"\n }\n }\n },\n \"devDependencies\": {\n \"@commitlint/cli\": \"^17.7.1\",\n \"@commitlint/config-conventional\": \"^17.7.0\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/qs\": \"^6.9.11\",\n \"@types/url-parse\": \"^1.4.11\",\n \"@types/uuid\": \"^9.0.7\",\n \"jest\": \"^30.1.3\",\n \"jest-environment-jsdom\": \"^30.1.2\",\n \"ts-jest\": \"^29.4.1\",\n \"tsup\": \"^8.0.1\",\n \"typescript\": \"^5.3.3\"\n },\n \"dependencies\": {\n \"@release-it/conventional-changelog\": \"^10.0.1\",\n \"canonicalize\": \"^2.0.0\",\n \"ethers\": \"^6.9.1\",\n \"qs\": \"^6.11.2\",\n \"release-it\": \"^19.0.4\",\n \"url-parse\": \"^1.5.10\",\n \"uuid\": \"^9.0.1\"\n },\n \"overrides\": {\n \"@conventional-changelog/git-client\": \"^2.0.0\"\n }\n}","export * from './Reclaim';\nexport * from './utils/interfaces';\nexport { ClaimCreationType, ModalOptions, DeviceType, ProofPropertiesJSON } from './utils/types';\n// Export device detection utilities for debugging (optional)\nexport { \n getDeviceType, \n getMobileDeviceType, \n isMobileDevice, \n isDesktopDevice,\n clearDeviceCache \n} from './utils/device';","// Proof-related interfaces\nexport interface Proof {\n identifier: string;\n claimData: ProviderClaimData;\n signatures: string[];\n witnesses: WitnessData[];\n extractedParameterValues: any;\n publicData?: { [key: string]: string };\n taskId?: number;\n}\n\n// Extension Interactions\nexport const RECLAIM_EXTENSION_ACTIONS = {\n CHECK_EXTENSION: 'RECLAIM_EXTENSION_CHECK',\n EXTENSION_RESPONSE: 'RECLAIM_EXTENSION_RESPONSE',\n START_VERIFICATION: 'RECLAIM_START_VERIFICATION',\n STATUS_UPDATE: 'RECLAIM_STATUS_UPDATE',\n};\n\nexport interface ExtensionMessage {\n action: string;\n messageId: string;\n data?: any;\n extensionID?: string;\n}\n\nexport interface WitnessData {\n id: string;\n url: string;\n}\n\nexport interface ProviderClaimData {\n provider: string;\n parameters: string;\n owner: string;\n timestampS: number;\n context: string;\n identifier: string;\n epoch: number;\n}\n\n// Context and Beacon interfaces\nexport interface Context {\n contextAddress: string;\n contextMessage: string;\n}\n\nexport interface Beacon {\n getState(epoch?: number): Promise<BeaconState>;\n close?(): Promise<void>;\n}\n\nexport type BeaconState = {\n witnesses: WitnessData[];\n epoch: number;\n witnessesRequiredForClaim: number;\n nextEpochTimestampS: number;\n};\n\n\n","import { ethers } from 'ethers';\nimport type { WitnessData } from './utils/interfaces';\nimport type { ClaimID, ClaimInfo, CompleteClaimData } from './utils/types';\nimport { canonicalStringify } from './utils/strings';\n\ntype BeaconState = {\n witnesses: WitnessData[];\n epoch: number;\n witnessesRequiredForClaim: number;\n nextEpochTimestampS: number;\n};\n\nexport function fetchWitnessListForClaim(\n { witnesses, witnessesRequiredForClaim, epoch }: BeaconState,\n params: string | ClaimInfo,\n timestampS: number\n): WitnessData[] {\n const identifier: ClaimID =\n typeof params === 'string' ? params : getIdentifierFromClaimInfo(params);\n const completeInput: string = [\n identifier,\n epoch.toString(),\n witnessesRequiredForClaim.toString(),\n timestampS.toString(),\n ].join('\\n');\n const completeHashStr: string = ethers.keccak256(strToUint8Array(completeInput));\n const completeHash: Uint8Array = ethers.getBytes(completeHashStr);\n const completeHashView: DataView = uint8ArrayToDataView(completeHash);\n const witnessesLeft: WitnessData[] = [...witnesses];\n const selectedWitnesses: WitnessData[] = [];\n let byteOffset: number = 0;\n for (let i = 0; i < witnessesRequiredForClaim; i++) {\n const randomSeed: number = completeHashView.getUint32(byteOffset);\n const witnessIndex: number = randomSeed % witnessesLeft.length;\n const witness: WitnessData = witnessesLeft[witnessIndex];\n selectedWitnesses.push(witness);\n\n witnessesLeft[witnessIndex] = witnessesLeft[witnessesLeft.length - 1];\n witnessesLeft.pop();\n byteOffset = (byteOffset + 4) % completeHash.length;\n }\n\n return selectedWitnesses;\n}\n\n\nexport function getIdentifierFromClaimInfo(info: ClaimInfo): ClaimID {\n // re-canonicalize context if it's not empty\n let canonicalContext = info.context || '';\n if (canonicalContext.length > 0) {\n try {\n const ctx = JSON.parse(canonicalContext);\n canonicalContext = canonicalStringify(ctx);\n } catch (e) {\n throw new Error('unable to parse non-empty context. Must be JSON');\n }\n }\n\n const str = `${info.provider}\\n${info.parameters}\\n${canonicalContext}`;\n return ethers.keccak256(strToUint8Array(str)).toLowerCase();\n}\n\nexport function strToUint8Array(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\nexport function uint8ArrayToDataView(arr: Uint8Array): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\nexport function createSignDataForClaim(data: CompleteClaimData): string {\n const identifier: ClaimID =\n 'identifier' in data ? data.identifier : getIdentifierFromClaimInfo(data);\n const lines: string[] = [\n identifier,\n data.owner.toLowerCase(),\n data.timestampS.toString(),\n data.epoch.toString(),\n ];\n\n return lines.join('\\n');\n}\n","import canonicalize from \"canonicalize\"\n\n/**\n * Canonically stringifies an object, so that the same object will always\n * produce the same string despite the order of keys\n */\nexport function canonicalStringify(params: { [key: string]: any } | undefined) {\n\tif(!params) {\n\t\treturn ''\n\t}\n\n\t// have to cast as ESM isn't correctly typing this\n\treturn (canonicalize as unknown as ((p: unknown) => string))(params) || ''\n}","import type { Context, Proof, ProviderClaimData } from './interfaces';\n\n// Claim-related types\nexport type ClaimID = ProviderClaimData['identifier'];\n\nexport type ClaimInfo = Pick<ProviderClaimData, 'context' | 'provider' | 'parameters'>;\n\nexport type AnyClaimInfo = ClaimInfo | { identifier: ClaimID };\n\nexport type CompleteClaimData = Pick<ProviderClaimData, 'owner' | 'timestampS' | 'epoch'> & AnyClaimInfo;\n\nexport type SignedClaim = {\n claim: CompleteClaimData;\n signatures: Uint8Array[];\n};\n\n// Request and session-related types\nexport type CreateVerificationRequest = {\n providerIds: string[];\n applicationSecret?: string;\n};\n\nexport type StartSessionParams = {\n onSuccess: OnSuccess;\n onError: OnError;\n};\n\nexport type OnSuccess = (proof?: Proof | Proof[] | string) => void;\nexport type OnError = (error: Error) => void;\n\nexport type ProofRequestOptions = {\n /**\n * Enables troubleshooting mode and more verbose logging\n */\n log?: boolean;\n /**\n * Accepts AI providers in the verification flow\n */\n acceptAiProviders?: boolean;\n useAppClip?: boolean;\n device?: string;\n envUrl?: string;\n useBrowserExtension?: boolean;\n extensionID?: string;\n providerVersion?: string;\n customSharePageUrl?: string;\n customAppClipUrl?: string;\n launchOptions?: ReclaimFlowLaunchOptions;\n /**\n * Whether the verification client should automatically submit necessary proofs once they are generated.\n * If set to false, the user must manually click a button to submit.\n * \n * @since 4.7.0\n * @default true\n */\n canAutoSubmit?: boolean;\n /**\n * Additional metadata to pass to the verification client.\n * This can be used to customize the client experience, such as customizing themes or UI by passing context-specific information.\n * The keys and values must be strings. For most clients, this is not required and goes unused.\n * \n * This has no effect on the verification process.\n * \n * Example: `{ theme: 'dark', verify_another_way_link: 'https://exampe.org/alternative-verification?id=1234' }`\n * \n * @since 4.7.0\n */\n metadata?: Record<string, string>;\n};\n\nexport type ReclaimFlowLaunchOptions = {\n /**\n * Enables deferred deep links for the Reclaim verification flow.\n *\n * When enabled, users without the verifier app installed will receive a deferred deep link\n * that automatically launches the verification flow after they install the app, ensuring\n * a seamless continuation of the verification process.\n *\n * **Platform Support:** Currently Android only\n *\n * **Default Behavior:** Opt-in during rollout phase. Will default to `true` for all apps\n * once fully released. See: https://blog.reclaimprotocol.org/posts/moving-beyond-google-play-instant\n */\n canUseDeferredDeepLinksFlow?: boolean;\n}\n\n// Modal customization options\nexport type ModalOptions = {\n title?: string;\n description?: string;\n extensionUrl?: string;\n darkTheme?: boolean;\n modalPopupTimer?: number;\n showExtensionInstallButton?: boolean;\n onClose?: () => void;\n};\n\n// JSON-safe modal options (excludes non-serializable functions)\nexport type SerializableModalOptions = Omit<ModalOptions, 'onClose'>;\n\n// Claim creation type enum\nexport enum ClaimCreationType {\n STANDALONE = 'createClaim',\n ON_ME_CHAIN = 'createClaimOnMechain'\n}\n\n// Device type enum \nexport enum DeviceType {\n ANDROID = 'android',\n IOS = 'ios',\n DESKTOP = 'desktop',\n MOBILE = 'mobile'\n}\n\n\n// Session and response types\nexport type InitSessionResponse = {\n sessionId: string;\n resolvedProviderVersion: string;\n};\n\nexport interface UpdateSessionResponse {\n success: boolean;\n message?: string;\n};\n\nexport enum SessionStatus {\n SESSION_INIT = 'SESSION_INIT',\n SESSION_STARTED = 'SESSION_STARTED',\n USER_INIT_VERIFICATION = 'USER_INIT_VERIFICATION',\n USER_STARTED_VERIFICATION = 'USER_STARTED_VERIFICATION',\n PROOF_GENERATION_STARTED = 'PROOF_GENERATION_STARTED',\n PROOF_GENERATION_SUCCESS = 'PROOF_GENERATION_SUCCESS',\n PROOF_GENERATION_FAILED = 'PROOF_GENERATION_FAILED',\n PROOF_SUBMITTED = 'PROOF_SUBMITTED',\n AI_PROOF_SUBMITTED = 'AI_PROOF_SUBMITTED',\n PROOF_SUBMISSION_FAILED = 'PROOF_SUBMISSION_FAILED',\n PROOF_MANUAL_VERIFICATION_SUBMITED = 'PROOF_MANUAL_VERIFICATION_SUBMITED',\n};\n\n// JSON and template-related types\nexport type ProofPropertiesJSON = {\n applicationId: string;\n providerId: string;\n sessionId: string;\n context: Context;\n signature: string;\n redirectUrl?: string;\n parameters: { [key: string]: string };\n /**\n * @deprecated use timestamp instead (maintained for compatibility)\n */\n timeStamp?: string;\n timestamp?: string; // new timestamp field\n appCallbackUrl?: string;\n claimCreationType?: ClaimCreationType;\n options?: ProofRequestOptions;\n sdkVersion: string;\n jsonProofResponse?: boolean;\n resolvedProviderVersion: string;\n modalOptions?: SerializableModalOptions;\n};\n\nexport type TemplateData = {\n sessionId: string;\n providerId: string;\n applicationId: string;\n signature: string;\n timestamp: string;\n callbackUrl: string;\n context: string;\n parameters: { [key: string]: string };\n redirectUrl: string;\n acceptAiProviders: boolean;\n sdkVersion: string;\n jsonProofResponse?: boolean;\n providerVersion?: string;\n resolvedProviderVersion: string;\n log?: boolean;\n canAutoSubmit?: boolean;\n metadata?: Record<string, string>;\n};\n\n// Add the new StatusUrlResponse type\nexport type StatusUrlResponse = {\n message: string;\n session?: {\n id: string;\n appId: string;\n httpProviderId: string[];\n sessionId: string;\n proofs?: Proof[];\n statusV2: string;\n };\n providerId?: string;\n};","import { type Proof, type Context, RECLAIM_EXTENSION_ACTIONS, ExtensionMessage } from './utils/interfaces'\nimport { getIdentifierFromClaimInfo } from './witness'\nimport {\n SignedClaim,\n ProofRequestOptions,\n StartSessionParams,\n ProofPropertiesJSON,\n TemplateData,\n InitSessionResponse,\n ClaimCreationType,\n ModalOptions,\n ReclaimFlowLaunchOptions,\n} from './utils/types'\nimport { SessionStatus, DeviceType } from './utils/types'\nimport { ethers } from 'ethers'\nimport canonicalize from 'canonicalize'\nimport {\n replaceAll,\n scheduleIntervalEndingTask\n} from './utils/helper'\nimport { constants, setBackendBaseUrl } from './utils/constants'\nimport {\n SetContextError,\n GetAppCallbackUrlError,\n GetStatusUrlError,\n InitError,\n InvalidParamError,\n ProofNotVerifiedError,\n ProofSubmissionFailedError,\n ProviderFailedError,\n SessionNotStartedError,\n SetParamsError,\n SetSignatureError,\n SignatureGeneratingError,\n SignatureNotFoundError\n} from './utils/errors'\nimport { validateContext, validateFunctionParams, validateParameters, validateSignature, validateURL, validateModalOptions } from './utils/validationUtils'\nimport { fetchStatusUrl, initSession, updateSession } from './utils/sessionUtils'\nimport { assertValidSignedClaim, createLinkWithTemplateData, getWitnessesForClaim } from './utils/proofUtils'\nimport { QRCodeModal } from './utils/modalUtils'\nimport loggerModule from './utils/logger';\nimport { getDeviceType, getMobileDeviceType, isMobileDevice } from './utils/device'\nimport { canonicalStringify } from './utils/strings'\nconst logger = loggerModule.logger\n\nconst sdkVersion = require('../package.json').version;\n\n/**\n * Verifies one or more Reclaim proofs by validating signatures and witness information\n *\n * @param proofOrProofs - A single proof object or an array of proof objects to verify\n * @param allowAiWitness - Optional flag to allow AI witness verification. Defaults to false\n * @returns Promise<boolean> - Returns true if all proofs are valid, false otherwise\n * @throws {SignatureNotFoundError} When proof has no signatures\n * @throws {ProofNotVerifiedError} When identifier mismatch occurs\n *\n * @example\n * ```typescript\n * const isValid = await verifyProof(proof);\n * const areAllValid = await verifyProof([proof1, proof2, proof3]);\n * const isValidWithAI = await verifyProof(proof, true);\n * ```\n */\nexport async function verifyProof(proofOrProofs: Proof | Proof[], allowAiWitness?: boolean): Promise<boolean> {\n // If input is an array of proofs\n if (Array.isArray(proofOrProofs)) {\n for (const proof of proofOrProofs) {\n const isVerified = await verifyProof(proof, allowAiWitness);\n if (!isVerified) {\n return false;\n }\n }\n return true;\n }\n\n // Single proof verification logic\n const proof = proofOrProofs;\n if (!proof.signatures.length) {\n throw new SignatureNotFoundError('No signatures')\n }\n\n try {\n // check if witness array exist and first element is ai-witness\n let witnesses = []\n if (proof.witnesses.length && proof.witnesses[0]?.url === 'ai-witness' && allowAiWitness === true) {\n witnesses.push(proof.witnesses[0].id)\n } else {\n witnesses = await getWitnessesForClaim(\n proof.claimData.epoch,\n proof.identifier,\n proof.claimData.timestampS\n )\n }\n // then hash the claim info with the encoded ctx to get the identifier\n const calculatedIdentifier = getIdentifierFromClaimInfo({\n parameters: JSON.parse(\n canonicalize(proof.claimData.parameters) as string\n ),\n provider: proof.claimData.provider,\n context: proof.claimData.context\n })\n proof.identifier = replaceAll(proof.identifier, '\"', '')\n // check if the identifier matches the one in the proof\n if (calculatedIdentifier !== proof.identifier) {\n throw new ProofNotVerifiedError('Identifier Mismatch')\n }\n\n const signedClaim: SignedClaim = {\n claim: {\n ...proof.claimData\n },\n signatures: proof.signatures.map(signature => {\n return ethers.getBytes(signature)\n })\n }\n\n assertValidSignedClaim(signedClaim, witnesses)\n } catch (e: Error | unknown) {\n logger.info(`Error verifying proof: ${e instanceof Error ? e.message : String(e)}`)\n return false\n }\n\n return true\n}\n\n/**\n * Transforms a Reclaim proof into a format suitable for on-chain verification\n *\n * @param proof - The proof object to transform\n * @returns Object containing claimInfo and signedClaim formatted for blockchain contracts\n *\n * @example\n * ```typescript\n * const { claimInfo, signedClaim } = transformForOnchain(proof);\n * // Use claimInfo and signedClaim with smart contract verification\n * ```\n */\nexport function transformForOnchain(proof: Proof): { claimInfo: any, signedClaim: any } {\n const claimInfoBuilder = new Map([\n ['context', proof.claimData.context],\n ['parameters', proof.claimData.parameters],\n ['provider', proof.claimData.provider],\n ]);\n const claimInfo = Object.fromEntries(claimInfoBuilder);\n const claimBuilder = new Map<string, number | string>([\n ['epoch', proof.claimData.epoch],\n ['identifier', proof.claimData.identifier],\n ['owner', proof.claimData.owner],\n ['timestampS', proof.claimData.timestampS],\n ]);\n const signedClaim = {\n claim: Object.fromEntries(claimBuilder),\n signatures: proof.signatures,\n };\n return { claimInfo, signedClaim };\n}\n\n// create a empty template data object to assign to templateData\nconst emptyTemplateData: TemplateData = {\n sessionId: '',\n providerId: '',\n applicationId: '',\n signature: '',\n timestamp: '',\n callbackUrl: '',\n context: '',\n parameters: {},\n redirectUrl: '',\n acceptAiProviders: false,\n sdkVersion: '',\n providerVersion: '',\n resolvedProviderVersion: '',\n jsonProofResponse: false,\n log: false\n}\nexport class ReclaimProofRequest {\n private applicationId: string;\n private signature?: string;\n private appCallbackUrl?: string;\n private sessionId: string;\n private options?: ProofRequestOptions;\n private context: Context = { contextAddress: '0x0', contextMessage: 'sample context' };\n private claimCreationType?: ClaimCreationType = ClaimCreationType.STANDALONE;\n private providerId: string;\n private resolvedProviderVersion?: string;\n private parameters: { [key: string]: string };\n private redirectUrl?: string;\n private intervals: Map<string, NodeJS.Timer> = new Map();\n private timeStamp: string;\n private sdkVersion: string;\n private jsonProofResponse: boolean = false;\n private lastFailureTime?: number;\n private templateData: TemplateData;\n private extensionID: string = \"reclaim-extension\";\n private customSharePageUrl?: string;\n private customAppClipUrl?: string;\n private modalOptions?: ModalOptions;\n private modal?: QRCodeModal;\n private readonly FAILURE_TIMEOUT = 30 * 1000; // 30 seconds timeout, can be adjusted\n\n private constructor(applicationId: string, providerId: string, options?: ProofRequestOptions) {\n this.providerId = providerId;\n this.timeStamp = Date.now().toString();\n this.applicationId = applicationId;\n this.sessionId = \"\";\n // keep template data as empty object \n this.templateData = emptyTemplateData;\n this.parameters = {};\n\n if (!options) {\n options = {};\n }\n\n options.useBrowserExtension = options.useBrowserExtension ?? true;\n\n if (options?.log) {\n loggerModule.setLogLevel('info');\n } else {\n loggerModule.setLogLevel('silent');\n }\n\n if (options.useAppClip === undefined) {\n options.useAppClip = true;\n }\n\n if (options?.envUrl) {\n setBackendBaseUrl(options.envUrl);\n }\n\n if (options.extensionID) {\n this.extensionID = options.extensionID;\n }\n\n if (options?.customSharePageUrl) {\n this.customSharePageUrl = options.customSharePageUrl;\n }\n\n if (options?.customAppClipUrl) {\n this.customAppClipUrl = options.customAppClipUrl;\n }\n\n this.options = options;\n // Fetch sdk version from package.json\n this.sdkVersion = 'js-' + sdkVersion;\n logger.info(`Initializing client with applicationId: ${this.applicationId}`);\n }\n\n /**\n * Initializes a new Reclaim proof request instance with automatic signature generation and session creation\n *\n * @param applicationId - Your Reclaim application ID\n * @param appSecret - Your application secret key for signing requests\n * @param providerId - The ID of the provider to use for proof generation\n * @param options - Optional configuration options for the proof request\n * @returns Promise<ReclaimProofRequest> - A fully initialized proof request instance\n * @throws {InitError} When initialization fails due to invalid parameters or session creation errors\n *\n * @example\n * ```typescript\n * const proofRequest = await ReclaimProofRequest.init(\n * 'your-app-id',\n * 'your-app-secret',\n * 'provider-id',\n * { log: true, acceptAiProviders: true }\n * );\n * ```\n */\n static async init(applicationId: string, appSecret: string, providerId: string, options?: ProofRequestOptions): Promise<ReclaimProofRequest> {\n try {\n validateFunctionParams([\n { paramName: 'applicationId', input: applicationId, isString: true },\n { paramName: 'providerId', input: providerId, isString: true },\n { paramName: 'appSecret', input: appSecret, isString: true }\n ], 'the constructor')\n\n // check if options is provided and validate each property of options\n if (options) {\n if (options.acceptAiProviders) {\n validateFunctionParams([\n { paramName: 'acceptAiProviders', input: options.acceptAiProviders }\n ], 'the constructor')\n }\n if (options.providerVersion) {\n validateFunctionParams([\n { paramName: 'providerVersion', input: options.providerVersion, isString: true }\n ], 'the constructor')\n }\n if (options.log) {\n validateFunctionParams([\n { paramName: 'log', input: options.log }\n ], 'the constructor')\n }\n if (options.useAppClip) {\n validateFunctionParams([\n { paramName: 'useAppClip', input: options.useAppClip }\n ], 'the constructor')\n }\n if (options.device) {\n validateFunctionParams([\n { paramName: 'device', input: options.device, isString: true }\n ], 'the constructor')\n }\n if (options.useBrowserExtension) {\n validateFunctionParams([\n { paramName: 'useBrowserExtension', input: options.useBrowserExtension }\n ], 'the constructor')\n }\n if (options.extensionID) {\n validateFunctionParams([\n { paramName: 'extensionID', input: options.extensionID, isString: true }\n ], 'the constructor')\n }\n if (options.envUrl) {\n validateFunctionParams([\n { paramName: 'envUrl', input: options.envUrl, isString: true }\n ], 'the constructor')\n }\n if (options.customSharePageUrl) {\n validateFunctionParams([\n { paramName: 'customSharePageUrl', input: options.customSharePageUrl, isString: true }\n ], 'the constructor')\n }\n if (options.customAppClipUrl) {\n validateFunctionParams([\n { paramName: 'customAppClipUrl', input: options.customAppClipUrl, isString: true }\n ], 'the constructor')\n }\n }\n\n const proofRequestInstance = new ReclaimProofRequest(applicationId, providerId, options)\n\n const signature = await proofRequestInstance.generateSignature(appSecret)\n proofRequestInstance.setSignature(signature)\n\n const data: InitSessionResponse = await initSession(providerId, applicationId, proofRequestInstance.timeStamp, signature, options?.providerVersion);\n proofRequestInstance.sessionId = data.sessionId\n proofRequestInstance.resolvedProviderVersion = data.resolvedProviderVersion\n\n return proofRequestInstance\n } catch (error) {\n logger.info('Failed to initialize ReclaimProofRequest', error as Error);\n throw new InitError('Failed to initialize ReclaimProofRequest', error as Error)\n }\n }\n\n /**\n * Creates a ReclaimProofRequest instance from a JSON string representation\n *\n * This method deserializes a previously exported proof request (via toJsonString) and reconstructs\n * the instance with all its properties. Useful for recreating requests on the frontend or across different contexts.\n *\n * @param jsonString - JSON string containing the serialized proof request data\n * @returns {Promise<ReclaimProofRequest>} - Reconstructed proof request instance\n * @throws {InvalidParamError} When JSON string is invalid or contains invalid parameters\n *\n * @example\n * ```typescript\n * const jsonString = proofRequest.toJsonString();\n * const reconstructed = await ReclaimProofRequest.fromJsonString(jsonString);\n * // Can also be used with InApp SDK's startVerificationFromJson method\n * ```\n */\n static async fromJsonString(jsonString: string): Promise<ReclaimProofRequest> {\n try {\n const {\n applicationId,\n providerId,\n sessionId,\n context,\n parameters,\n signature,\n redirectUrl,\n timeStamp,\n timestamp,\n appCallbackUrl,\n claimCreationType,\n options,\n sdkVersion,\n jsonProofResponse,\n resolvedProviderVersion,\n modalOptions\n }: ProofPropertiesJSON = JSON.parse(jsonString)\n\n // Prefer 'timestamp' over 'timeStamp' for backward compatibility (remove in future versions)\n const resolvedTimestamp = timestamp || timeStamp;\n\n validateFunctionParams([\n { input: applicationId, paramName: 'applicationId', isString: true },\n { input: providerId, paramName: 'providerId', isString: true },\n { input: signature, paramName: 'signature', isString: true },\n { input: sessionId, paramName: 'sessionId', isString: true },\n { input: resolvedTimestamp, paramName: 'timestamp', isString: true },\n { input: sdkVersion, paramName: 'sdkVersion', isString: true },\n ], 'fromJsonString');\n\n if (modalOptions) {\n validateModalOptions(modalOptions, 'fromJsonString', 'modalOptions.');\n }\n\n if (redirectUrl) {\n validateURL(redirectUrl, 'fromJsonString');\n }\n\n if (appCallbackUrl) {\n validateURL(appCallbackUrl, 'fromJsonString');\n }\n\n if (context) {\n validateContext(context);\n }\n\n if (parameters) {\n validateParameters(parameters);\n }\n\n if (claimCreationType) {\n validateFunctionParams([\n { input: claimCreationType, paramName: 'claimCreationType' }\n ], 'fromJsonString');\n }\n\n if (jsonProofResponse !== undefined) {\n validateFunctionParams([\n { input: jsonProofResponse, paramName: 'jsonProofResponse' }\n ], 'fromJsonString');\n }\n\n\n if (options?.providerVersion) {\n validateFunctionParams([\n { input: options.providerVersion, paramName: 'providerVersion', isString: true }\n ], 'fromJsonString');\n }\n\n if (resolvedProviderVersion) {\n validateFunctionParams([\n { input: resolvedProviderVersion, paramName: 'resolvedProviderVersion', isString: true }\n ], 'fromJsonString');\n }\n\n const proofRequestInstance = new ReclaimProofRequest(applicationId, providerId, options);\n proofRequestInstance.sessionId = sessionId;\n proofRequestInstance.context = context;\n proofRequestInstance.parameters = parameters;\n proofRequestInstance.appCallbackUrl = appCallbackUrl\n proofRequestInstance.redirectUrl = redirectUrl\n proofRequestInstance.timeStamp = resolvedTimestamp!\n proofRequestInstance.signature = signature\n proofRequestInstance.sdkVersion = sdkVersion;\n proofRequestInstance.resolvedProviderVersion = resolvedProviderVersion;\n proofRequestInstance.modalOptions = modalOptions;\n proofRequestInstance.jsonProofResponse = jsonProofResponse ?? false;\n return proofRequestInstance\n } catch (error) {\n logger.info('Failed to parse JSON string in fromJsonString:', error);\n throw new InvalidParamError('Invalid JSON string provided to fromJsonString');\n }\n }\n\n /**\n * Sets a custom callback URL where proofs will be submitted via HTTP POST\n *\n * By default, proofs are posted as `application/x-www-form-urlencoded`.\n * When a custom callback URL is set, Reclaim will no longer receive proofs upon submission,\n * and listeners on the startSession method will not be triggered. Your application must\n * coordinate with your backend to receive and verify proofs using verifyProof().\n *\n * Note: InApp SDKs are unaffected by this property as they do not handle proof submission.\n *\n * @param url - The URL where proofs should be submitted via HTTP POST\n * @param jsonProofResponse - Optional. Set to true to submit proofs as `application/json`. Defaults to false\n * @throws {InvalidParamError} When URL is invalid\n *\n * @example\n * ```typescript\n * proofRequest.setAppCallbackUrl('https://your-backend.com/callback');\n * // Or with JSON format\n * proofRequest.setAppCallbackUrl('https://your-backend.com/callback', true);\n * ```\n */\n setAppCallbackUrl(url: string, jsonProofResponse?: boolean): void {\n validateURL(url, 'setAppCallbackUrl')\n this.appCallbackUrl = url\n this.jsonProofResponse = jsonProofResponse ?? false\n }\n\n /**\n * Sets a redirect URL where users will be redirected after successfully acquiring and submitting proof\n *\n * @param url - The URL where users should be redirected after successful proof generation\n * @throws {InvalidParamError} When URL is invalid\n *\n * @example\n * ```typescript\n * proofRequest.setRedirectUrl('https://your-app.com/success');\n * ```\n */\n setRedirectUrl(url: string): void {\n validateURL(url, 'setRedirectUrl');\n this.redirectUrl = url;\n }\n\n /**\n * Sets the claim creation type for the proof request\n *\n * @param claimCreationType - The type of claim creation (e.g., STANDALONE)\n *\n * @example\n * ```typescript\n * proofRequest.setClaimCreationType(ClaimCreationType.STANDALONE);\n * ```\n */\n setClaimCreationType(claimCreationType: ClaimCreationType): void {\n this.claimCreationType = claimCreationType;\n }\n\n /**\n * Sets custom options for the QR code modal display\n *\n * @param options - Modal configuration options including title, description, theme, etc.\n * @throws {SetParamsError} When modal options are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setModalOptions({\n * title: 'Scan QR Code',\n * description: 'Scan with your mobile device',\n * darkTheme: true\n * });\n * ```\n */\n setModalOptions(options: ModalOptions): void {\n try {\n // Validate modal options\n validateModalOptions(options, 'setModalOptions');\n\n this.modalOptions = { ...this.modalOptions, ...options };\n logger.info('Modal options set successfully');\n } catch (error) {\n logger.info('Error setting modal options:', error);\n throw new SetParamsError('Error setting modal options', error as Error);\n }\n }\n\n /**\n * Sets additional context data to be stored with the claim\n *\n * This allows you to associate custom data (address and message) with the proof claim.\n * The context can be retrieved and validated when verifying the proof. \n * \n * Also see [setContext] which is an alternate way to set context that has an address & message.\n *\n * @param context - Any additional data you want to store with the claim. Should be serializable to a JSON string.\n * @throws {SetContextError} When context parameters are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setJsonContext({foo: 'bar'});\n * ```\n */\n setJsonContext(context: Record<string, any>) {\n try {\n validateFunctionParams([\n { input: context, paramName: 'context', isString: false }\n ], 'setJsonContext');\n // ensure context is canonically json serializable\n this.context = JSON.parse(canonicalStringify(context));\n } catch (error) {\n logger.info(\"Error setting context\", error)\n throw new SetContextError(\"Error setting context\", error as Error)\n }\n }\n\n /**\n * Sets additional context data to be stored with the claim\n *\n * This allows you to associate custom data (address and message) with the proof claim.\n * The context can be retrieved and validated when verifying the proof.\n *\n * @param address - Context address identifier\n * @param message - Additional data to associate with the address\n * @throws {SetContextError} When context parameters are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setContext('0x1234...', 'User verification for premium access');\n * ```\n */\n setContext(address: string, message: string): void {\n try {\n validateFunctionParams([\n { input: address, paramName: 'address', isString: true },\n { input: message, paramName: 'message', isString: true }\n ], 'setContext');\n this.context = { contextAddress: address, contextMessage: message };\n } catch (error) {\n logger.info(\"Error setting context\", error)\n throw new SetContextError(\"Error setting context\", error as Error)\n }\n }\n\n /**\n * @deprecated use setContext instead\n *\n * @param address \n * @param message additional data you want associated with the [address] \n */\n addContext(address: string, message: string): void {\n this.setContext(address, message);\n }\n\n /**\n * Sets provider-specific parameters for the proof request\n *\n * These parameters are passed to the provider and may include configuration options,\n * filters, or other provider-specific settings required for proof generation.\n *\n * @param params - Key-value pairs of parameters to set\n * @throws {SetParamsError} When parameters are invalid\n *\n * @example\n * ```typescript\n * proofRequest.setParams({\n * minFollowers: '1000',\n * platform: 'twitter'\n * });\n * ```\n */\n setParams(params: { [key: string]: string }): void {\n try {\n validateParameters(params);\n this.parameters = { ...this.parameters, ...params }\n } catch (error) {\n logger.info('Error Setting Params:', error);\n throw new SetParamsError(\"Error setting params\", error as Error)\n }\n }\n\n /**\n * Returns the currently configured app callback URL\n *\n * If no custom callback URL was set via setAppCallbackUrl(), this returns the default\n * Reclaim service callback URL with the current session ID.\n *\n * @returns The callback URL where proofs will be submitted\n * @throws {GetAppCallbackUrlError} When unable to retrieve the callback URL\n *\n * @example\n * ```typescript\n * const callbackUrl = proofRequest.getAppCallbackUrl();\n * console.log('Proofs will be sent to:', callbackUrl);\n * ```\n */\n getAppCallbackUrl(): string {\n try {\n validateFunctionParams([{ input: this.sessionId, paramName: 'sessionId', isString: true }], 'getAppCallbackUrl');\n return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`\n } catch (error) {\n logger.info(\"Error getting app callback url\", error)\n throw new GetAppCallbackUrlError(\"Error getting app callback url\", error as Error)\n }\n }\n\n /**\n * Returns the status URL for monitoring the current session\n *\n * This URL can be used to check the status of the proof request session.\n *\n * @returns The status monitoring URL for the current session\n * @throws {GetStatusUrlError} When unable to retrieve the status URL\n *\n * @example\n * ```typescript\n * const statusUrl = proofRequest.getStatusUrl();\n * // Use this URL to poll for session status updates\n * ```\n */\n getStatusUrl(): string {\n try {\n validateFunctionParams([{ input: this.sessionId, paramName: 'sessionId', isString: true }], 'getStatusUrl');\n return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`\n } catch (error) {\n logger.info(\"Error fetching Status Url\", error)\n throw new GetStatusUrlError(\"Error fetching status url\", error as Error)\n }\n }\n\n /**\n * Returns the session ID associated with this proof request\n *\n * The session ID is automatically generated during initialization and uniquely\n * identifies this proof request session.\n *\n * @returns The session ID string\n * @throws {SessionNotStartedError} When session ID is not set\n *\n * @example\n * ```typescript\n * const sessionId = proofRequest.getSessionId();\n * console.log('Session ID:', sessionId);\n * ```\n */\n getSessionId(): string {\n if (!this.sessionId) {\n throw new SessionNotStartedError(\"SessionId is not set\");\n }\n return this.sessionId;\n }\n\n // Private helper methods\n private setSignature(signature: string): void {\n try {\n validateFunctionParams([{ input: signature, paramName: 'signature', isString: true }], 'setSignature');\n this.signature = signature;\n logger.info(`Signature set successfully for applicationId: ${this.applicationId}`);\n } catch (error) {\n logger.info(\"Error setting signature\", error)\n throw new SetSignatureError(\"Error setting signature\", error as Error)\n }\n }\n\n private async generateSignature(applicationSecret: string): Promise<string> {\n try {\n const wallet = new ethers.Wallet(applicationSecret)\n const canonicalData = canonicalize({ providerId: this.providerId, timestamp: this.timeStamp });\n\n\n if (!canonicalData) {\n throw new SignatureGeneratingError('Failed to canonicalize data for signing.');\n }\n\n const messageHash = ethers.keccak256(new TextEncoder().encode(canonicalData));\n\n return await wallet.signMessage(ethers.getBytes(messageHash));\n } catch (err) {\n logger.info(`Error generating proof request for applicationId: ${this.applicationId}, providerId: ${this.providerId}, signature: ${this.signature}, timeStamp: ${this.timeStamp}`, err);\n throw new SignatureGeneratingError(`Error generating signature for applicationSecret: ${applicationSecret}`)\n }\n }\n\n private clearInterval(): void {\n if (this.sessionId && this.intervals.has(this.sessionId)) {\n clearInterval(this.intervals.get(this.sessionId) as NodeJS.Timeout)\n this.intervals.delete(this.sessionId)\n }\n }\n\n private buildSharePageUrl(template: string): string {\n const baseUrl = 'https://share.reclaimprotocol.org/verify';\n\n if (this.customSharePageUrl) {\n return `${this.customSharePageUrl}/?template=${template}`;\n }\n\n return `${baseUrl}/?template=${template}`;\n }\n\n /**\n * Exports the Reclaim proof verification request as a JSON string\n *\n * This serialized format can be sent to the frontend to recreate this request using\n * ReclaimProofRequest.fromJsonString() or any InApp SDK's startVerificationFromJson()\n * method to initiate the verification journey.\n *\n * @returns JSON string representation of the proof request. Note: The JSON includes both `timestamp` and `timeStamp` (deprecated) for backward compatibility.\n *\n * @example\n * ```typescript\n * const jsonString = proofRequest.toJsonString();\n * // Send to frontend or store for later use\n * // Can be reconstructed with: ReclaimProofRequest.fromJsonString(jsonString)\n * ```\n */\n toJsonString(): string {\n return JSON.stringify({\n applicationId: this.applicationId,\n providerId: this.providerId,\n sessionId: this.sessionId,\n context: this.context,\n appCallbackUrl: this.appCallbackUrl,\n claimCreationType: this.claimCreationType,\n parameters: this.parameters,\n signature: this.signature,\n redirectUrl: this.redirectUrl,\n timestamp: this.timeStamp, // New field with correct spelling\n timeStamp: this.timeStamp, // @deprecated: Remove in future versions \n options: this.options,\n sdkVersion: this.sdkVersion,\n jsonProofResponse: this.jsonProofResponse,\n resolvedProviderVersion: this.resolvedProviderVersion ?? '',\n modalOptions: this.modalOptions ? {\n title: this.modalOptions.title,\n description: this.modalOptions.description,\n extensionUrl: this.modalOptions.extensionUrl,\n darkTheme: this.modalOptions.darkTheme,\n modalPopupTimer: this.modalOptions.modalPopupTimer,\n showExtensionInstallButton: this.modalOptions.showExtensionInstallButton\n // onClose is intentionally excluded as functions cannot be serialized\n } : undefined\n })\n }\n\n /**\n * Validates signature and returns template data\n * @returns \n */\n private getTemplateData = (): TemplateData => {\n if (!this.signature) {\n throw new SignatureNotFoundError('Signature is not set.')\n }\n validateSignature(this.providerId, this.signature, this.applicationId, this.timeStamp)\n const templateData: TemplateData = {\n sessionId: this.sessionId,\n providerId: this.providerId,\n applicationId: this.applicationId,\n signature: this.signature,\n timestamp: this.timeStamp,\n callbackUrl: this.getAppCallbackUrl(),\n context: canonicalStringify(this.context),\n providerVersion: this.options?.providerVersion ?? '',\n resolvedProviderVersion: this.resolvedProviderVersion ?? '',\n parameters: this.parameters,\n redirectUrl: this.redirectUrl ?? '',\n acceptAiProviders: this.options?.acceptAiProviders ?? false,\n sdkVersion: this.sdkVersion,\n jsonProofResponse: this.jsonProofResponse,\n log: this.options?.log ?? false,\n canAutoSubmit: this.options?.canAutoSubmit ?? true,\n metadata: this.options?.metadata,\n }\n\n return templateData;\n }\n\n /**\n * Generates and returns the request URL for proof verification\n *\n * This URL can be shared with users to initiate the proof generation process.\n * The URL format varies based on device type:\n * - Mobile iOS: Returns App Clip URL (if useAppClip is enabled)\n * - Mobile Android: Returns Instant App URL (if useAppClip is enabled)\n * - Desktop/Other: Returns standard verification URL\n *\n * @param launchOptions - Optional launch configuration to override default behavior\n * @returns Promise<string> - The generated request URL\n * @throws {SignatureNotFoundError} When signature is not set\n *\n * @example\n * ```typescript\n * const requestUrl = await proofRequest.getRequestUrl();\n * // Share this URL with users or display as QR code\n * ```\n */\n async getRequestUrl(launchOptions?: ReclaimFlowLaunchOptions): Promise<string> {\n const options = launchOptions || this.options?.launchOptions || {};\n\n logger.info('Creating Request Url')\n if (!this.signature) {\n throw new SignatureNotFoundError('Signature is not set.')\n }\n\n try {\n const templateData = this.getTemplateData()\n await updateSession(this.sessionId, SessionStatus.SESSION_STARTED)\n const deviceType = getDeviceType();\n if (this.options?.useAppClip && deviceType === DeviceType.MOBILE) {\n let template = encodeURIComponent(JSON.stringify(templateData));\n template = replaceAll(template, '(', '%28');\n template = replaceAll(template, ')', '%29');\n\n // check if the app is running on iOS or Android\n const isIos = getMobileDeviceType() === DeviceType.IOS;\n if (!isIos) {\n let instantAppUrl = this.buildSharePageUrl(template);\n const isDeferredDeeplinksFlowEnabled = options.canUseDeferredDeepLinksFlow ?? false;\n\n if (isDeferredDeeplinksFlowEnabled) {\n instantAppUrl = instantAppUrl.replace(\"/verifier\", \"/link\");\n }\n logger.info('Instant App Url created successfully: ' + instantAppUrl);\n return instantAppUrl;\n } else {\n const appClipUrl = this.customAppClipUrl ? `${this.customAppClipUrl}&template=${template}` : `https://appclip.apple.com/id?p=org.reclaimprotocol.app.clip&template=${template}`;\n logger.info('App Clip Url created successfully: ' + appClipUrl);\n return appClipUrl;\n }\n } else {\n const link = await createLinkWithTemplateData(templateData, this.customSharePageUrl)\n logger.info('Request Url created successfully: ' + link);\n return link;\n }\n } catch (error) {\n logger.info('Error creating Request Url:', error)\n throw error\n }\n }\n\n /**\n * Triggers the appropriate Reclaim verification flow based on device type and configuration\n *\n * This method automatically detects the device type and initiates the optimal verification flow:\n * - Desktop with browser extension: Triggers extension flow\n * - Desktop without extension: Shows QR code modal\n * - Mobile Android: Redirects to Instant App\n * - Mobile iOS: Redirects to App Clip\n *\n * @param launchOptions - Optional launch configuration to override default behavior\n * @returns Promise<void>\n * @throws {SignatureNotFoundError} When signature is not set\n *\n * @example\n * ```typescript\n * await proofRequest.triggerReclaimFlow();\n * // The appropriate verification method will be triggered automatically\n * ```\n */\n async triggerReclaimFlow(launchOptions?: ReclaimFlowLaunchOptions): Promise<void> {\n const options = launchOptions || this.options?.launchOptions || {};\n\n if (!this.signature) {\n throw new SignatureNotFoundError('Signature is not set.')\n }\n\n try {\n const templateData = this.getTemplateData()\n\n this.templateData = templateData;\n\n logger.info('Triggering Reclaim flow');\n\n // Get device type\n const deviceType = getDeviceType();\n updateSession(this.sessionId, SessionStatus.SESSION_STARTED)\n\n if (deviceType === DeviceType.DESKTOP) {\n const extensionAvailable = await this.isBrowserExtensionAvailable();\n // Desktop flow\n if (this.options?.useBrowserExtension && extensionAvailable) {\n logger.info('Triggering browser extension flow');\n this.triggerBrowserExtensionFlow();\n return;\n } else {\n // Show QR code popup modal\n logger.info('Browser extension not available, showing QR code modal');\n await this.showQRCodeModal();\n }\n } else if (deviceType === DeviceType.MOBILE) {\n // Mobile flow\n const mobileDeviceType = getMobileDeviceType();\n\n if (mobileDeviceType === DeviceType.ANDROID) {\n // Redirect to instant app URL\n logger.info('Redirecting to Android instant app');\n await this.redirectToInstantApp(options);\n } else if (mobileDeviceType === DeviceType.IOS) {\n // Redirect to app clip URL\n logger.info('Redirecting to iOS app clip');\n this.redirectToAppClip();\n }\n }\n } catch (error) {\n logger.info('Error triggering Reclaim flow:', error);\n throw error;\n }\n }\n\n\n /**\n * Checks if the Reclaim browser extension is installed and available\n *\n * This method attempts to communicate with the browser extension to verify its availability.\n * It uses a timeout mechanism to quickly determine if the extension responds.\n *\n * @param timeout - Timeout in milliseconds to wait for extension response. Defaults to 200ms\n * @returns Promise<boolean> - True if extension is available, false otherwise\n *\n * @example\n * ```typescript\n * const hasExtension = await proofRequest.isBrowserExtensionAvailable();\n * if (hasExtension) {\n * console.log('Browser extension is installed');\n * }\n * ```\n */\n async isBrowserExtensionAvailable(timeout = 200): Promise<boolean> {\n try {\n return new Promise<boolean>((resolve) => {\n const messageId = `reclaim-check-${Date.now()}`;\n\n const timeoutId = setTimeout(() => {\n window.removeEventListener('message', messageListener);\n resolve(false);\n }, timeout);\n\n const messageListener = (event: MessageEvent) => {\n if (event.data?.action === RECLAIM_EXTENSION_ACTIONS.EXTENSION_RESPONSE &&\n event.data?.messageId === messageId) {\n clearTimeout(timeoutId);\n window.removeEventListener('message', messageListener);\n resolve(!!event.data.installed);\n }\n };\n\n window.addEventListener('message', messageListener);\n const message: ExtensionMessage = {\n action: RECLAIM_EXTENSION_ACTIONS.CHECK_EXTENSION,\n extensionID: this.extensionID,\n messageId: messageId\n }\n window.postMessage(message, '*');\n });\n } catch (error) {\n logger.info('Error checking Reclaim extension installed:', error);\n return false;\n }\n }\n\n private triggerBrowserExtensionFlow(): void {\n const message: ExtensionMessage = {\n action: RECLAIM_EXTENSION_ACTIONS.START_VERIFICATION,\n messageId: this.sessionId,\n data: this.templateData,\n extensionID: this.extensionID\n }\n window.postMessage(message, '*');\n logger.info('Browser extension flow triggered');\n }\n\n private async showQRCodeModal(): Promise<void> {\n try {\n const requestUrl = await createLinkWithTemplateData(this.templateData, this.customSharePageUrl);\n this.modal = new QRCodeModal(this.modalOptions);\n await this.modal.show(requestUrl);\n } catch (error) {\n logger.info('Error showing QR code modal:', error);\n throw error;\n }\n }\n\n private async redirectToInstantApp(options: ReclaimFlowLaunchOptions): Promise<void> {\n try {\n let template = encodeURIComponent(JSON.stringify(this.templateData));\n template = replaceAll(template, '(', '%28');\n template = replaceAll(template, ')', '%29');\n\n let instantAppUrl = this.buildSharePageUrl(template);\n logger.info('Redirecting to Android instant app: ' + instantAppUrl);\n\n const isDeferredDeeplinksFlowEnabled = options.canUseDeferredDeepLinksFlow ?? false;\n\n if (isDeferredDeeplinksFlowEnabled) {\n instantAppUrl = instantAppUrl.replace(\"/verifier\", \"/link\");\n\n // Construct Android intent deep link\n const deepLink = `intent://details?id=org.reclaimprotocol.app&url=${encodeURIComponent(\n instantAppUrl\n )}&template=${template}#Intent;scheme=market;action=android.intent.action.VIEW;package=com.android.vending;end;`;\n\n try {\n const requestUrl = instantAppUrl;\n\n let appInstalled = false;\n let timeoutId: string | number | NodeJS.Timeout | undefined;\n\n // Create hidden iframe to test deep link\n const iframe = document.createElement(\"iframe\");\n iframe.style.display = \"none\";\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n document.body.appendChild(iframe);\n\n // Function to clean up\n const cleanup = () => {\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n // If page becomes hidden, app opened successfully\n const onVisibilityChange = () => {\n if (document.hidden) {\n appInstalled = true;\n cleanup();\n // Open in main window since app is installed\n window.location.href = deepLink;\n }\n };\n\n // Listen for visibility change\n document.addEventListener(\"visibilitychange\", onVisibilityChange, { once: true });\n\n // Test reclaimverifier deep link in iframe\n iframe.src = deepLink.replace('intent:', 'reclaimverifier:');\n\n // After timeout, assume app not installed\n timeoutId = setTimeout(() => {\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n cleanup();\n\n if (!appInstalled) {\n // App not installed - redirect to the store page to install the app\n window.navigator.clipboard.writeText(requestUrl).catch(() => {\n console.error(\"We can't access the clipboard. Please copy this link and open Reclaim Verifier app.\");\n });\n window.location.href = deepLink;\n }\n }, 1500);\n } catch (e) {\n // Final fallback → verifier\n window.location.href = instantAppUrl;\n }\n return;\n }\n\n // Redirect to instant app\n window.location.href = instantAppUrl;\n } catch (error) {\n logger.info('Error redirecting to instant app:', error);\n throw error;\n }\n }\n\n private redirectToAppClip(): void {\n try {\n let template = encodeURIComponent(JSON.stringify(this.templateData));\n template = replaceAll(template, '(', '%28');\n template = replaceAll(template, ')', '%29');\n\n const appClipUrl = this.customAppClipUrl ? `${this.customAppClipUrl}&template=${template}` : `https://appclip.apple.com/id?p=org.reclaimprotocol.app.clip&template=${template}`;\n logger.info('Redirecting to iOS app clip: ' + appClipUrl);\n const verifierUrl = `https://share.reclaimprotocol.org/verifier/?template=${template}`;\n\n // Redirect to app clip\n window.location.href = appClipUrl;\n\n setTimeout(() => {\n window.location.href = verifierUrl;\n // 5 second delay to allow app clip to launch\n }, 5 * 1000);\n } catch (error) {\n logger.info('Error redirecting to app clip:', error);\n throw error;\n }\n }\n\n /**\n * Starts the proof request session and monitors for proof submission\n *\n * This method begins polling the session status to detect when\n * a proof has been generated and submitted. It handles both default Reclaim callbacks\n * and custom callback URLs.\n *\n * For default callbacks: Verifies proofs automatically and passes them to onSuccess\n * For custom callbacks: Monitors submission status and notifies via onSuccess when complete\n *\n * @param onSuccess - Callback function invoked when proof is successfully submitted\n * @param onError - Callback function invoked when an error occurs during the session\n * @returns Promise<void>\n * @throws {SessionNotStartedError} When session ID is not defined\n * @throws {ProofNotVerifiedError} When proof verification fails (default callback only)\n * @throws {ProofSubmissionFailedError} When proof submission fails (custom callback only)\n * @throws {ProviderFailedError} When proof generation fails with timeout\n *\n * @example\n * ```typescript\n * await proofRequest.startSession({\n * onSuccess: (proof) => {\n * console.log('Proof received:', proof);\n * },\n * onError: (error) => {\n * console.error('Error:', error);\n * }\n * });\n * ```\n */\n async startSession({ onSuccess, onError }: StartSessionParams): Promise<void> {\n if (!this.sessionId) {\n const message = \"Session can't be started due to undefined value of sessionId\";\n logger.info(message);\n throw new SessionNotStartedError(message);\n }\n\n logger.info('Starting session');\n\n const sessionUpdatePollingInterval = 3 * 1000;\n const interval = setInterval(async () => {\n try {\n const statusUrlResponse = await fetchStatusUrl(this.sessionId);\n\n if (!statusUrlResponse.session) return;\n\n // Reset failure time if status is not PROOF_GENERATION_FAILED\n if (statusUrlResponse.session.statusV2 !== SessionStatus.PROOF_GENERATION_FAILED) {\n this.lastFailureTime = undefined;\n }\n\n // Check for failure timeout\n if (statusUrlResponse.session.statusV2 === SessionStatus.PROOF_GENERATION_FAILED) {\n const currentTime = Date.now();\n if (!this.lastFailureTime) {\n this.lastFailureTime = currentTime;\n } else if (currentTime - this.lastFailureTime >= this.FAILURE_TIMEOUT) {\n throw new ProviderFailedError('Proof generation failed - timeout reached');\n }\n return; // Continue monitoring if under timeout\n }\n\n const isDefaultCallbackUrl = this.getAppCallbackUrl() === `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`;\n\n if (isDefaultCallbackUrl) {\n if (statusUrlResponse.session.proofs && statusUrlResponse.session.proofs.length > 0) {\n const proofs = statusUrlResponse.session.proofs;\n if (this.claimCreationType === ClaimCreationType.STANDALONE) {\n const verified = await verifyProof(proofs);\n if (!verified) {\n logger.info(`Proofs not verified: ${JSON.stringify(proofs)}`);\n throw new ProofNotVerifiedError();\n }\n }\n // check if the proofs array has only one proof then send the proofs in onSuccess \n if (proofs.length === 1) {\n\n onSuccess(proofs[0]);\n } else {\n onSuccess(proofs);\n }\n this.clearInterval();\n this.modal?.close();\n }\n } else {\n if (statusUrlResponse.session.statusV2 === SessionStatus.PROOF_SUBMISSION_FAILED) {\n throw new ProofSubmissionFailedError();\n }\n if (statusUrlResponse.session.statusV2 === SessionStatus.PROOF_SUBMITTED ||\n statusUrlResponse.session.statusV2 === SessionStatus.AI_PROOF_SUBMITTED) {\n if (onSuccess) {\n onSuccess('Proof submitted successfully to the custom callback url');\n }\n this.clearInterval();\n this.modal?.close();\n }\n }\n } catch (e) {\n if (onError) {\n onError(e as Error);\n }\n this.clearInterval();\n this.modal?.close();\n }\n }, sessionUpdatePollingInterval);\n\n this.intervals.set(this.sessionId, interval);\n scheduleIntervalEndingTask(this.sessionId, this.intervals, onError);\n }\n\n /**\n * Closes the QR code modal if it is currently open\n *\n * This method can be called to programmatically close the modal, for example,\n * when implementing custom UI behavior or cleanup logic.\n *\n * @example\n * ```typescript\n * // Close modal after some condition\n * proofRequest.closeModal();\n * ```\n */\n closeModal(): void {\n if (this.modal) {\n this.modal.close();\n logger.info('Modal closed by user');\n }\n }\n\n /**\n * Returns whether proofs will be submitted as JSON format\n *\n * @returns boolean - True if proofs are sent as application/json, false for application/x-www-form-urlencoded\n *\n * @example\n * ```typescript\n * const isJson = proofRequest.getJsonProofResponse();\n * console.log('JSON format:', isJson);\n * ```\n */\n getJsonProofResponse(): boolean {\n return this.jsonProofResponse;\n }\n}\n\n","function createErrorClass(name: string) {\n return class extends Error {\n constructor(message?: string, public innerError?: Error) {\n // Include inner error message in the main message if available\n const fullMessage = innerError\n ? `${message || ''} caused by ${innerError.name}: ${innerError.message}`\n : message;\n\n super(fullMessage);\n this.name = name;\n if (innerError) {\n this.stack += `\\nCaused by: ${innerError.stack}`;\n }\n }\n };\n}\n\nexport const TimeoutError = createErrorClass('TimeoutError');\nexport const ProofNotVerifiedError = createErrorClass('ProofNotVerifiedError');\nexport const SessionNotStartedError = createErrorClass('SessionNotStartedError');\nexport const ProviderNotFoundError = createErrorClass('ProviderNotFoundError');\nexport const SignatureGeneratingError = createErrorClass('SignatureGeneratingError');\nexport const SignatureNotFoundError = createErrorClass('SignatureNotFoundError');\nexport const InvalidSignatureError = createErrorClass('InvalidSignatureError');\nexport const UpdateSessionError = createErrorClass('UpdateSessionError');\nexport const InitSessionError = createErrorClass('InitSessionError');\nexport const ProviderFailedError = createErrorClass('ProviderFailedError');\nexport const InvalidParamError = createErrorClass('InvalidParamError');\nexport const ApplicationError = createErrorClass('ApplicationError');\nexport const InitError = createErrorClass('InitError');\nexport const BackendServerError = createErrorClass('BackendServerError');\nexport const GetStatusUrlError = createErrorClass('GetStatusUrlError');\nexport const NoProviderParamsError = createErrorClass('NoProviderParamsError');\nexport const SetParamsError = createErrorClass('SetParamsError');\nexport const SetContextError = createErrorClass('SetContextError');\nexport const SetSignatureError = createErrorClass('SetSignatureError');\nexport const GetAppCallbackUrlError = createErrorClass(\"GetAppCallbackUrlError\");\nexport const StatusUrlError = createErrorClass('StatusUrlError');\nexport const InavlidParametersError = createErrorClass('InavlidParametersError');\nexport const ProofSubmissionFailedError = createErrorClass('ProofSubmissionFailedError');","// Define the possible log levels\nexport type LogLevel = 'info' | 'warn' | 'error' | 'silent';\n\n// Define a simple logger class\nclass SimpleLogger {\n private level: LogLevel = 'info';\n\n setLevel(level: LogLevel) {\n this.level = level;\n }\n\n private shouldLog(messageLevel: LogLevel): boolean {\n const levels: LogLevel[] = ['error', 'warn', 'info', 'silent'];\n return levels.indexOf(this.level) >= levels.indexOf(messageLevel);\n }\n\n private log(level: LogLevel, message: string, ...args: any[]) {\n if (this.shouldLog(level) && this.level !== 'silent') {\n const logFunction = this.getLogFunction(level);\n console.log('current level', this.level);\n logFunction(`[${level.toUpperCase()}]`, message, ...args);\n }\n }\n\n private getLogFunction(level: LogLevel): (message?: any, ...optionalParams: any[]) => void {\n switch (level) {\n case 'error':\n return console.error;\n case 'warn':\n return console.warn;\n case 'info':\n return console.info;\n default:\n return () => {}; // No-op for 'silent'\n }\n }\n\n info(message: string, ...args: any[]) {\n this.log('info', message, ...args);\n }\n\n warn(message: string, ...args: any[]) {\n this.log('warn', message, ...args);\n }\n\n error(message: string, ...args: any[]) {\n this.log('error', message, ...args);\n }\n}\n\n// Create the logger instance\nconst logger = new SimpleLogger();\n\n// Function to set the log level\nexport function setLogLevel(level: LogLevel) {\n logger.setLevel(level);\n}\n\n// Export the logger instance and the setLogLevel function\nexport default {\n logger,\n setLogLevel\n};\n","import { OnError } from './types'\nimport { TimeoutError } from './errors'\nimport loggerModule from './logger'\nconst logger = loggerModule.logger\n\n/**\n * Escapes special characters in a string for use in a regular expression\n * @param string - The input string to escape\n * @returns The input string with special regex characters escaped\n */\nexport function escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Replaces all occurrences of a substring in a string\n * @param str - The original string\n * @param find - The substring to find\n * @param replace - The string to replace the found substrings with\n * @returns A new string with all occurrences of 'find' replaced by 'replace'\n */\nexport function replaceAll(str: string, find: string, replace: string): string {\n if (find === '') return str;\n return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);\n}\n\n/**\n * Schedules a task to end an interval after a specified timeout\n * @param sessionId - The ID of the current session\n * @param intervals - A Map containing the intervals\n * @param onFailureCallback - Callback function to be called on failure\n * @param timeout - Timeout in milliseconds (default: 10 minutes)\n */\nexport function scheduleIntervalEndingTask(\n sessionId: string,\n intervals: Map<string, NodeJS.Timer>,\n onFailureCallback: OnError,\n timeout: number = 1000 * 60 * 10\n): void {\n setTimeout(() => {\n if (intervals.has(sessionId)) {\n const message = 'Interval ended without receiving proofs'\n onFailureCallback(new TimeoutError(message))\n logger.info(message)\n clearInterval(intervals.get(sessionId) as NodeJS.Timeout)\n intervals.delete(sessionId)\n }\n }, timeout)\n}\n","// Base URL for the backend API\nexport let BACKEND_BASE_URL = \"https://api.reclaimprotocol.org\";\n\nexport function setBackendBaseUrl(url: string) {\n BACKEND_BASE_URL = url;\n}\n\n// Constant values used throughout the application\nexport const constants = {\n // Default callback URL for Reclaim protocol\n get DEFAULT_RECLAIM_CALLBACK_URL() {\n return `${BACKEND_BASE_URL}/api/sdk/callback?callbackId=`;\n },\n\n // Default status URL for Reclaim sessions\n get DEFAULT_RECLAIM_STATUS_URL() {\n return `${BACKEND_BASE_URL}/api/sdk/session/`;\n },\n\n // URL for sharing Reclaim templates\n RECLAIM_SHARE_URL: 'https://share.reclaimprotocol.org/verifier/?template=',\n\n // Chrome extension URL for Reclaim Protocol\n CHROME_EXTENSION_URL: 'https://chromewebstore.google.com/detail/reclaim-extension/oafieibbbcepkmenknelhmgaoahamdeh',\n\n // QR Code API base URL\n QR_CODE_API_URL: 'https://api.qrserver.com/v1/create-qr-code/'\n};\n","import { ethers } from \"ethers\";\nimport { InavlidParametersError, InvalidParamError, InvalidSignatureError } from \"./errors\";\nimport canonicalize from 'canonicalize'\nimport { Context } from \"./interfaces\";\nimport loggerModule from './logger';\nimport { ProofRequestOptions, ModalOptions } from \"./types\";\nconst logger = loggerModule.logger;\n\n/**\n * Validates function parameters based on specified criteria\n * @param params - An array of objects containing input, paramName, and optional isString flag\n * @param functionName - The name of the function being validated\n * @throws InvalidParamError if any parameter fails validation\n */\nexport function validateFunctionParams(params: { input: any, paramName: string, isString?: boolean }[], functionName: string): void {\n params.forEach(({ input, paramName, isString }) => {\n if (input == null) {\n logger.info(`Validation failed: ${paramName} in ${functionName} is null or undefined`);\n throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`);\n }\n if (isString && typeof input !== 'string') {\n logger.info(`Validation failed: ${paramName} in ${functionName} is not a string`);\n throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`);\n }\n if (isString && input.trim() === '') {\n logger.info(`Validation failed: ${paramName} in ${functionName} is an empty string`);\n throw new InvalidParamError(`${paramName} passed to ${functionName} must not be an empty string.`);\n }\n });\n}\n\n\n// validate the parameters\n/** \n * Validates the parameters object\n * @param parameters - The parameters object to validate\n * @throws InavlidParametersError if the parameters object is not valid\n */\nexport function validateParameters(parameters: { [key: string]: string }): void {\n try {\n // check if the parameters is an object of key value pairs of string and string\n if (typeof parameters !== 'object' || parameters === null) {\n logger.info(`Parameters validation failed: Provided parameters is not an object`);\n throw new InavlidParametersError(`The provided parameters is not an object`);\n }\n // check each key and value in the parameters object\n for (const [key, value] of Object.entries(parameters)) {\n if (typeof key !== 'string' || typeof value !== 'string') {\n logger.info(`Parameters validation failed: Provided parameters is not an object of key value pairs of string and string`);\n throw new InavlidParametersError(`The provided parameters is not an object of key value pairs of string and string`);\n }\n }\n } catch (e) {\n logger.info(`Parameters validation failed: ${(e as Error).message}`);\n throw new InavlidParametersError(`Invalid parameters passed to validateParameters.`, e as Error);\n }\n}\n\n\n/**\n* Validates a URL string\n* @param url - The URL to validate\n* @param functionName - The name of the function calling this validation\n* @throws InvalidParamError if the URL is invalid or empty\n*/\nexport function validateURL(url: string, functionName: string): void {\n try {\n new URL(url);\n } catch (e) {\n logger.info(`URL validation failed for ${url} in ${functionName}: ${(e as Error).message}`);\n throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e as Error);\n }\n}\n\n/**\n* Validates a signature against the provided application ID\n* @param providerId - The ID of the provider\n* @param signature - The signature to validate\n* @param applicationId - The expected application ID\n* @param timestamp - The timestamp of the signature\n* @throws InvalidSignatureError if the signature is invalid or doesn't match the application ID\n*/\nexport function validateSignature(providerId: string, signature: string, applicationId: string, timestamp: string): void {\n try {\n logger.info(`Starting signature validation for providerId: ${providerId}, applicationId: ${applicationId}, timestamp: ${timestamp}`);\n\n const message = canonicalize({ providerId, timestamp });\n if (!message) {\n logger.info('Failed to canonicalize message for signature validation');\n throw new Error('Failed to canonicalize message');\n }\n const messageHash = ethers.keccak256(new TextEncoder().encode(message));\n let appId = ethers.verifyMessage(\n ethers.getBytes(messageHash),\n ethers.hexlify(signature)\n ).toLowerCase();\n\n if (ethers.getAddress(appId) !== ethers.getAddress(applicationId)) {\n logger.info(`Signature validation failed: Mismatch between derived appId (${appId}) and provided applicationId (${applicationId})`);\n throw new InvalidSignatureError(`Signature does not match the application id: ${appId}`);\n }\n\n logger.info(`Signature validated successfully for applicationId: ${applicationId}`);\n } catch (err) {\n logger.info(`Signature validation failed: ${(err as Error).message}`);\n if (err instanceof InvalidSignatureError) {\n throw err;\n }\n throw new InvalidSignatureError(`Failed to validate signature: ${(err as Error).message}`);\n }\n}\n\n\n/**\n * Validates the context object\n * @param context - The context object to validate\n * @throws InvalidParamError if the context object is not valid\n */\nexport function validateContext(context: Context): void {\n if (!context.contextAddress) {\n logger.info(`Context validation failed: Provided context address in context is not valid`);\n throw new InvalidParamError(`The provided context address in context is not valid`);\n }\n\n if (!context.contextMessage) {\n logger.info(`Context validation failed: Provided context message in context is not valid`);\n throw new InvalidParamError(`The provided context message in context is not valid`);\n }\n\n validateFunctionParams([\n { input: context.contextAddress, paramName: 'contextAddress', isString: true },\n { input: context.contextMessage, paramName: 'contextMessage', isString: true }\n ], 'validateContext');\n}\n\n/**\n * Validates the options object\n * @param options - The options object to validate\n * @throws InvalidParamError if the options object is not valid\n */\nexport function validateOptions(options: ProofRequestOptions): void {\n if (options.acceptAiProviders && typeof options.acceptAiProviders !== 'boolean') {\n logger.info(`Options validation failed: Provided acceptAiProviders in options is not valid`);\n throw new InvalidParamError(`The provided acceptAiProviders in options is not valid`);\n }\n\n if (options.log && typeof options.log !== 'boolean') {\n logger.info(`Options validation failed: Provided log in options is not valid`);\n throw new InvalidParamError(`The provided log in options is not valid`);\n }\n\n if (options.providerVersion && typeof options.providerVersion !== 'string') {\n logger.info(`Options validation failed: Provided providerVersion in options is not valid`);\n throw new InvalidParamError(`The provided providerVersion in options is not valid`);\n }\n}\n\n/**\n * Validates the modalOptions object\n * @param modalOptions - The modalOptions object to validate\n * @param functionName - The name of the function calling this validation\n * @param paramPrefix - Optional prefix for parameter names (e.g., 'modalOptions.')\n * @throws InvalidParamError if the modalOptions object is not valid\n */\nexport function validateModalOptions(modalOptions: ModalOptions, functionName: string, paramPrefix: string = ''): void {\n if (modalOptions.title !== undefined) {\n validateFunctionParams([\n { input: modalOptions.title, paramName: `${paramPrefix}title`, isString: true }\n ], functionName);\n }\n\n if (modalOptions.description !== undefined) {\n validateFunctionParams([\n { input: modalOptions.description, paramName: `${paramPrefix}description`, isString: true }\n ], functionName);\n }\n\n if (modalOptions.extensionUrl !== undefined) {\n validateURL(modalOptions.extensionUrl, functionName);\n validateFunctionParams([\n { input: modalOptions.extensionUrl, paramName: `${paramPrefix}extensionUrl`, isString: true }\n ], functionName);\n }\n\n if (modalOptions.darkTheme !== undefined) {\n if (typeof modalOptions.darkTheme !== 'boolean') {\n throw new InvalidParamError(`${paramPrefix}darkTheme prop must be a boolean`);\n }\n validateFunctionParams([\n { input: modalOptions.darkTheme, paramName: `${paramPrefix}darkTheme` }\n ], functionName);\n }\n\n if (modalOptions.modalPopupTimer !== undefined) {\n if (typeof modalOptions.modalPopupTimer !== 'number' || modalOptions.modalPopupTimer <= 0 || !Number.isInteger(modalOptions.modalPopupTimer)) {\n throw new InvalidParamError(`${paramPrefix}modalPopupTimer prop must be a valid time in minutes`);\n }\n validateFunctionParams([\n { input: modalOptions.modalPopupTimer, paramName: `${paramPrefix}modalPopupTimer` }\n ], functionName);\n }\n\n if (modalOptions.showExtensionInstallButton !== undefined) {\n if (typeof modalOptions.showExtensionInstallButton !== 'boolean') {\n throw new InvalidParamError(`${paramPrefix}showExtensionInstallButton prop must be a boolean`);\n }\n validateFunctionParams([\n { input: modalOptions.showExtensionInstallButton, paramName: `${paramPrefix}showExtensionInstallButton` }\n ], functionName);\n }\n}\n\n\n\n","import {\n InitSessionError,\n UpdateSessionError,\n StatusUrlError\n} from \"./errors\";\nimport { InitSessionResponse, SessionStatus, StatusUrlResponse } from \"./types\";\nimport { validateFunctionParams } from \"./validationUtils\";\nimport { BACKEND_BASE_URL, constants } from './constants';\nimport loggerModule from './logger';\nconst logger = loggerModule.logger;\n\n/**\n * Initializes a session with the provided parameters\n * @param providerId - The ID of the provider\n * @param appId - The ID of the application\n * @param timestamp - The timestamp of the request\n * @param signature - The signature for authentication\n * @returns A promise that resolves to an InitSessionResponse\n * @throws InitSessionError if the session initialization fails\n */\nexport async function initSession(\n providerId: string,\n appId: string,\n timestamp: string,\n signature: string,\n versionNumber?: string\n): Promise<InitSessionResponse> {\n logger.info(`Initializing session for providerId: ${providerId}, appId: ${appId}`);\n try {\n const response = await fetch(`${BACKEND_BASE_URL}/api/sdk/init/session/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ providerId, appId, timestamp, signature, versionNumber })\n });\n\n const res = await response.json();\n\n if (!response.ok) {\n logger.info(`Session initialization failed: ${res.message || 'Unknown error'}`);\n throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`);\n }\n\n return res as InitSessionResponse;\n } catch (err) {\n logger.info(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`, err);\n throw err;\n }\n}\n\n/**\n * Updates the status of an existing session\n * @param sessionId - The ID of the session to update\n * @param status - The new status of the session\n * @returns A promise that resolves to the update response\n * @throws UpdateSessionError if the session update fails\n */\nexport async function updateSession(sessionId: string, status: SessionStatus) {\n logger.info(`Updating session status for sessionId: ${sessionId}, new status: ${status}`);\n validateFunctionParams(\n [{ input: sessionId, paramName: 'sessionId', isString: true }],\n 'updateSession'\n );\n\n try {\n const response = await fetch(`${BACKEND_BASE_URL}/api/sdk/update/session/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ sessionId, status })\n });\n\n const res = await response.json();\n\n if (!response.ok) {\n const errorMessage = `Error updating session with sessionId: ${sessionId}. Status Code: ${response.status}`;\n logger.info(errorMessage, res);\n throw new UpdateSessionError(errorMessage);\n }\n\n logger.info(`Session status updated successfully for sessionId: ${sessionId}`);\n return res;\n } catch (err) {\n const errorMessage = `Failed to update session with sessionId: ${sessionId}`;\n logger.info(errorMessage, err);\n throw new UpdateSessionError(`Error updating session with sessionId: ${sessionId}`);\n }\n}\n\n/**\n * Fetches the status URL for a given session ID\n * @param sessionId - The ID of the session to fetch the status URL for\n * @returns A promise that resolves to a StatusUrlResponse\n * @throws StatusUrlError if the status URL fetch fails\n */\nexport async function fetchStatusUrl(sessionId: string): Promise<StatusUrlResponse> {\n validateFunctionParams(\n [{ input: sessionId, paramName: 'sessionId', isString: true }],\n 'fetchStatusUrl'\n );\n\n try {\n const response = await fetch(`${constants.DEFAULT_RECLAIM_STATUS_URL}${sessionId}`, {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n });\n\n const res = await response.json();\n\n if (!response.ok) {\n const errorMessage = `Error fetching status URL for sessionId: ${sessionId}. Status Code: ${response.status}`;\n logger.info(errorMessage, res);\n throw new StatusUrlError(errorMessage);\n }\n\n return res as StatusUrlResponse;\n } catch (err) {\n const errorMessage = `Failed to fetch status URL for sessionId: ${sessionId}`;\n logger.info(errorMessage, err);\n throw new StatusUrlError(`Error fetching status URL for sessionId: ${sessionId}`);\n }\n}\n\n\n","import { ethers } from \"ethers\";\nimport { WitnessData } from \"./interfaces\";\nimport { SignedClaim, TemplateData } from \"./types\";\nimport { createSignDataForClaim, fetchWitnessListForClaim } from \"../witness\";\nimport { BACKEND_BASE_URL, constants } from \"./constants\";\nimport { replaceAll } from \"./helper\";\nimport { validateURL } from \"./validationUtils\";\nimport { makeBeacon } from \"../smart-contract\";\nimport { ProofNotVerifiedError } from \"./errors\";\nimport loggerModule from './logger';\nconst logger = loggerModule.logger;\n\n\n/**\n * Retrieves a shortened URL for the given URL\n * @param url - The URL to be shortened\n * @returns A promise that resolves to the shortened URL, or the original URL if shortening fails\n */\nexport async function getShortenedUrl(url: string): Promise<string> {\n logger.info(`Attempting to shorten URL: ${url}`);\n try {\n validateURL(url, 'getShortenedUrl')\n const response = await fetch(`${BACKEND_BASE_URL}/api/sdk/shortener`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ fullUrl: url })\n })\n const res = await response.json()\n if (!response.ok) {\n logger.info(`Failed to shorten URL: ${url}, Response: ${JSON.stringify(res)}`);\n return url;\n }\n const shortenedVerificationUrl = res.result.shortUrl\n return shortenedVerificationUrl\n } catch (err) {\n logger.info(`Error shortening URL: ${url}, Error: ${err}`);\n return url\n }\n}\n\n/**\n * Creates a link with embedded template data\n * @param templateData - The data to be embedded in the link\n * @param sharePagePath - The path to the share page (optional)\n * @returns A promise that resolves to the created link (shortened if possible)\n */\nexport async function createLinkWithTemplateData(templateData: TemplateData, sharePagePath?: string): Promise<string> {\n let template = encodeURIComponent(JSON.stringify(templateData))\n template = replaceAll(template, '(', '%28')\n template = replaceAll(template, ')', '%29')\n const fullLink = sharePagePath ? `${sharePagePath}/?template=${template}` : `${constants.RECLAIM_SHARE_URL}${template}`\n try {\n const shortenedLink = await getShortenedUrl(fullLink)\n return shortenedLink;\n } catch (err) {\n logger.info(`Error creating link for sessionId: ${templateData.sessionId}, Error: ${err}`);\n return fullLink;\n }\n}\n\n/**\n * Retrieves the list of witnesses for a given claim\n * @param epoch - The epoch number\n * @param identifier - The claim identifier\n * @param timestampS - The timestamp in seconds\n * @returns A promise that resolves to an array of witness addresses\n * @throws Error if no beacon is available\n */\nexport async function getWitnessesForClaim(\n epoch: number,\n identifier: string,\n timestampS: number\n): Promise<string[]> {\n const beacon = makeBeacon()\n if (!beacon) {\n logger.info('No beacon available for getting witnesses');\n throw new Error('No beacon available');\n }\n const state = await beacon.getState(epoch)\n const witnessList = fetchWitnessListForClaim(state, identifier, timestampS)\n const witnesses = witnessList.map((w: WitnessData) => w.id.toLowerCase())\n return witnesses;\n}\n\n/**\n * Recovers the signers' addresses from a signed claim\n * @param claim - The signed claim object\n * @param signatures - The signatures associated with the claim\n * @returns An array of recovered signer addresses\n */\nexport function recoverSignersOfSignedClaim({\n claim,\n signatures\n}: SignedClaim): string[] {\n const dataStr = createSignDataForClaim({ ...claim })\n const signers = signatures.map(signature =>\n ethers.verifyMessage(dataStr, ethers.hexlify(signature)).toLowerCase()\n )\n return signers;\n}\n\n/**\n * Asserts that a signed claim is valid by checking if all expected witnesses have signed\n * @param claim - The signed claim to validate\n * @param expectedWitnessAddresses - An array of expected witness addresses\n * @throws ProofNotVerifiedError if any expected witness signature is missing\n */\nexport function assertValidSignedClaim(\n claim: SignedClaim,\n expectedWitnessAddresses: string[]\n): void {\n const witnessAddresses = recoverSignersOfSignedClaim(claim)\n const witnessesNotSeen = new Set(expectedWitnessAddresses)\n for (const witness of witnessAddresses) {\n if (witnessesNotSeen.has(witness)) {\n witnessesNotSeen.delete(witness)\n }\n }\n\n if (witnessesNotSeen.size > 0) {\n const missingWitnesses = Array.from(witnessesNotSeen).join(', ');\n logger.info(`Claim validation failed. Missing signatures from: ${missingWitnesses}`);\n throw new ProofNotVerifiedError(\n `Missing signatures from ${missingWitnesses}`\n )\n }\n}","/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n\nimport { Contract } from 'ethers';\n\nconst _abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'address',\n name: 'previousAdmin',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'address',\n name: 'newAdmin',\n type: 'address',\n },\n ],\n name: 'AdminChanged',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'beacon',\n type: 'address',\n },\n ],\n name: 'BeaconUpgraded',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n components: [\n {\n internalType: 'uint32',\n name: 'id',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampStart',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampEnd',\n type: 'uint32',\n },\n {\n components: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n internalType: 'struct Reclaim.Witness[]',\n name: 'witnesses',\n type: 'tuple[]',\n },\n {\n internalType: 'uint8',\n name: 'minimumWitnessesForClaimCreation',\n type: 'uint8',\n },\n ],\n indexed: false,\n internalType: 'struct Reclaim.Epoch',\n name: 'epoch',\n type: 'tuple',\n },\n ],\n name: 'EpochAdded',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'uint8',\n name: 'version',\n type: 'uint8',\n },\n ],\n name: 'Initialized',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'previousOwner',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'newOwner',\n type: 'address',\n },\n ],\n name: 'OwnershipTransferred',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'implementation',\n type: 'address',\n },\n ],\n name: 'Upgraded',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'witnessAddress',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n name: 'addAsWitness',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'addNewEpoch',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint32',\n name: 'epochNum',\n type: 'uint32',\n },\n {\n components: [\n {\n internalType: 'string',\n name: 'provider',\n type: 'string',\n },\n {\n internalType: 'string',\n name: 'parameters',\n type: 'string',\n },\n {\n internalType: 'string',\n name: 'context',\n type: 'string',\n },\n ],\n internalType: 'struct Claims.ClaimInfo',\n name: 'claimInfo',\n type: 'tuple',\n },\n {\n components: [\n {\n internalType: 'bytes32',\n name: 'identifier',\n type: 'bytes32',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n {\n internalType: 'uint32',\n name: 'timestampS',\n type: 'uint32',\n },\n {\n internalType: 'uint256',\n name: 'epoch',\n type: 'uint256',\n },\n ],\n internalType: 'struct Claims.CompleteClaimData',\n name: 'claimData',\n type: 'tuple',\n },\n {\n internalType: 'bytes[]',\n name: 'signatures',\n type: 'bytes[]',\n },\n ],\n name: 'assertValidEpochAndSignedClaim',\n outputs: [],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'currentEpoch',\n outputs: [\n {\n internalType: 'uint32',\n name: '',\n type: 'uint32',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'epochDurationS',\n outputs: [\n {\n internalType: 'uint32',\n name: '',\n type: 'uint32',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'epochs',\n outputs: [\n {\n internalType: 'uint32',\n name: 'id',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampStart',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampEnd',\n type: 'uint32',\n },\n {\n internalType: 'uint8',\n name: 'minimumWitnessesForClaimCreation',\n type: 'uint8',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint32',\n name: 'epoch',\n type: 'uint32',\n },\n ],\n name: 'fetchEpoch',\n outputs: [\n {\n components: [\n {\n internalType: 'uint32',\n name: 'id',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampStart',\n type: 'uint32',\n },\n {\n internalType: 'uint32',\n name: 'timestampEnd',\n type: 'uint32',\n },\n {\n components: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n internalType: 'struct Reclaim.Witness[]',\n name: 'witnesses',\n type: 'tuple[]',\n },\n {\n internalType: 'uint8',\n name: 'minimumWitnessesForClaimCreation',\n type: 'uint8',\n },\n ],\n internalType: 'struct Reclaim.Epoch',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint32',\n name: 'epoch',\n type: 'uint32',\n },\n {\n internalType: 'bytes32',\n name: 'identifier',\n type: 'bytes32',\n },\n {\n internalType: 'uint32',\n name: 'timestampS',\n type: 'uint32',\n },\n ],\n name: 'fetchWitnessesForClaim',\n outputs: [\n {\n components: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n internalType: 'struct Reclaim.Witness[]',\n name: '',\n type: 'tuple[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'initialize',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'minimumWitnessesForClaimCreation',\n outputs: [\n {\n internalType: 'uint8',\n name: '',\n type: 'uint8',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'owner',\n outputs: [\n {\n internalType: 'address',\n name: '',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'proxiableUUID',\n outputs: [\n {\n internalType: 'bytes32',\n name: '',\n type: 'bytes32',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'witnessAddress',\n type: 'address',\n },\n ],\n name: 'removeAsWitness',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'renounceOwnership',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'newOwner',\n type: 'address',\n },\n ],\n name: 'transferOwnership',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'isWhitelisted',\n type: 'bool',\n },\n ],\n name: 'updateWitnessWhitelist',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'newImplementation',\n type: 'address',\n },\n ],\n name: 'upgradeTo',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'newImplementation',\n type: 'address',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'upgradeToAndCall',\n outputs: [],\n stateMutability: 'payable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'witnesses',\n outputs: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n {\n internalType: 'string',\n name: 'host',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const;\n\nexport class Reclaim__factory {\n static readonly abi = _abi;\n\n static connect(address: string, signerOrProvider: any): Contract {\n return new Contract(address, _abi, signerOrProvider);\n }\n}\n","{\n \"0x1a4\": {\n \"chainName\": \"opt-goerli\",\n \"address\": \"0xF93F605142Fb1Efad7Aa58253dDffF67775b4520\",\n \"rpcUrl\": \"https://opt-goerli.g.alchemy.com/v2/rksDkSUXd2dyk2ANy_zzODknx_AAokui\"\n },\n \"0xaa37dc\": {\n \"chainName\": \"opt-sepolia\",\n \"address\": \"0x6D0f81BDA11995f25921aAd5B43359630E65Ca96\",\n \"rpcUrl\": \"https://opt-sepolia.g.alchemy.com/v2/aO1-SfG4oFRLyAiLREqzyAUu0HTCwHgs\"\n}\n\n}\n","import type { Beacon, BeaconState } from './utils/interfaces';\nimport { Reclaim__factory as ReclaimFactory } from './contract-types';\nimport CONTRACTS_CONFIG from './contract-types/config.json';\nimport { Contract, ethers } from 'ethers';\n\nconst DEFAULT_CHAIN_ID = 11155420;\n\nexport function makeBeacon(chainId?: number): Beacon | undefined {\n chainId = chainId || DEFAULT_CHAIN_ID;\n const contract = getContract(chainId);\n if (contract) {\n return makeBeaconCacheable({\n async getState(epochId: number | undefined): Promise<BeaconState> {\n //@ts-ignore\n const epoch = await contract.fetchEpoch(epochId || 0);\n if (!epoch.id) {\n throw new Error(`Invalid epoch ID: ${epochId}`);\n }\n\n return {\n epoch: epoch.id,\n witnesses: epoch.witnesses.map((w: any) => ({\n id: w.addr.toLowerCase(),\n url: w.host,\n })),\n witnessesRequiredForClaim: epoch.minimumWitnessesForClaimCreation,\n nextEpochTimestampS: epoch.timestampEnd,\n };\n },\n });\n } else {\n return undefined;\n }\n}\n\nexport function makeBeaconCacheable(beacon: Beacon): Beacon {\n const cache: { [epochId: number]: Promise<BeaconState> } = {};\n\n return {\n ...beacon,\n async getState(epochId: number | undefined): Promise<BeaconState> {\n if (!epochId) {\n // TODO: add cache here\n const state = await beacon.getState();\n return state;\n }\n\n const key = epochId;\n\n if (!cache[key]) {\n cache[key] = beacon.getState(epochId);\n }\n\n return cache[key] as unknown as BeaconState;\n },\n };\n}\n\nconst existingContractsMap: { [chain: string]: Contract } = {};\n\nfunction getContract(chainId: number): Contract {\n const chainKey = `0x${chainId.toString(16)}`;\n if (!existingContractsMap[chainKey]) {\n const contractData =\n CONTRACTS_CONFIG[chainKey as keyof typeof CONTRACTS_CONFIG];\n if (!contractData) {\n throw new Error(`Unsupported chain: \"${chainKey}\"`);\n }\n\n const rpcProvider = new ethers.JsonRpcProvider(contractData.rpcUrl);\n existingContractsMap[chainKey] = ReclaimFactory.connect(\n contractData.address,\n rpcProvider\n );\n }\n\n return existingContractsMap[chainKey] as Contract;\n}\n","import loggerModule from './logger';\nimport { ModalOptions } from './types';\nimport { constants } from './constants';\nconst logger = loggerModule.logger;\n\nexport class QRCodeModal {\n private modalId: string;\n private options: ModalOptions;\n private autoCloseTimer?: NodeJS.Timeout;\n private countdownTimer?: NodeJS.Timeout;\n private countdownSeconds: number = 60;\n\n constructor(options: ModalOptions = {}) {\n this.modalId = 'reclaim-qr-modal';\n this.options = {\n title: 'Verify with Reclaim',\n description: 'Scan the QR code with your mobile device to complete verification',\n extensionUrl: constants.CHROME_EXTENSION_URL,\n darkTheme: false,\n modalPopupTimer: 1, // default to 1 minute\n showExtensionInstallButton: false, // default to false\n ...options\n };\n }\n\n async show(requestUrl: string): Promise<void> {\n try {\n // Remove existing modal if present\n this.close();\n\n // Create modal HTML\n const modalHTML = this.createModalHTML();\n\n // Add modal to DOM\n document.body.insertAdjacentHTML('beforeend', modalHTML);\n\n // Generate QR code\n await this.generateQRCode(requestUrl, 'reclaim-qr-code');\n\n // Add event listeners\n this.addEventListeners();\n\n // Start auto-close timer\n this.startAutoCloseTimer();\n\n } catch (error) {\n logger.info('Error showing QR code modal:', error);\n throw error;\n }\n }\n\n close(): void {\n // Clear timers\n if (this.autoCloseTimer) {\n clearTimeout(this.autoCloseTimer);\n this.autoCloseTimer = undefined;\n }\n if (this.countdownTimer) {\n clearInterval(this.countdownTimer);\n this.countdownTimer = undefined;\n }\n\n const modal = document.getElementById(this.modalId);\n if (modal) {\n modal.remove();\n }\n if (this.options.onClose) {\n this.options.onClose();\n }\n }\n\n private getThemeStyles() {\n const isDark = this.options.darkTheme;\n\n return {\n modalBackground: isDark ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.5)',\n cardBackground: isDark ? '#1f2937' : 'white',\n titleColor: isDark ? '#f9fafb' : '#1f2937',\n textColor: isDark ? '#d1d5db' : '#6b7280',\n qrBackground: isDark ? '#374151' : '#f9fafb',\n tipBackground: isDark ? '#1e40af' : '#f0f9ff',\n tipBorder: isDark ? '#1e40af' : '#e0f2fe',\n tipTextColor: isDark ? '#dbeafe' : '#0369a1',\n buttonBackground: isDark ? '#374151' : '#f3f4f6',\n buttonColor: isDark ? '#f9fafb' : '#374151',\n buttonHoverBackground: isDark ? '#4b5563' : '#e5e7eb',\n countdownColor: isDark ? '#6b7280' : '#9ca3af',\n progressBackground: isDark ? '#4b5563' : '#e5e7eb',\n progressGradient: isDark\n ? 'linear-gradient(90deg, #3b82f6 0%, #2563eb 50%, #1d4ed8 100%)'\n : 'linear-gradient(90deg, #2563eb 0%, #1d4ed8 50%, #1e40af 100%)',\n linkColor: isDark ? '#60a5fa' : '#2563eb',\n extensionButtonBackground: isDark ? '#1e40af' : '#2563eb',\n extensionButtonHover: isDark ? '#1d4ed8' : '#1d4ed8'\n };\n }\n\n private createModalHTML(): string {\n const styles = this.getThemeStyles();\n\n return `\n <div id=\"${this.modalId}\" style=\"\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: ${styles.modalBackground};\n display: flex;\n justify-content: center;\n align-items: center;\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n \">\n <div style=\"\n background: ${styles.cardBackground};\n border-radius: 12px;\n padding: 32px;\n max-width: 400px;\n width: 90%;\n text-align: center;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n position: relative;\n \">\n <button id=\"reclaim-close-modal\" style=\"\n position: absolute;\n top: 16px;\n right: 16px;\n background: none;\n border: none;\n cursor: pointer;\n padding: 4px;\n border-radius: 6px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background-color 0.2s;\n width: 32px;\n height: 32px;\n \"\n onmouseover=\"this.style.backgroundColor='${styles.buttonHoverBackground}'\"\n onmouseout=\"this.style.backgroundColor='transparent'\"\n title=\"Close modal\">\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M12 4L4 12M4 4L12 12\" stroke=\"${styles.buttonColor}\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </svg>\n </button>\n \n <h2 style=\"\n margin: 0 0 16px 0;\n font-size: 24px;\n font-weight: 600;\n color: ${styles.titleColor};\n \">${this.options.title}</h2>\n \n <p style=\"\n margin: 0 0 24px 0;\n color: ${styles.textColor};\n font-size: 14px;\n line-height: 1.5;\n \">${this.options.description}</p>\n \n <div id=\"reclaim-qr-code\" style=\"\n margin: 0 auto 24px auto;\n background: ${styles.qrBackground};\n border-radius: 8px;\n display: inline-block;\n \"></div>\n \n ${this.options.showExtensionInstallButton ? `\n <div style=\"\n margin-bottom: 24px;\n padding: 16px;\n background: ${styles.tipBackground};\n border: 1px solid ${styles.tipBorder};\n border-radius: 8px;\n \">\n <p style=\"\n margin: 0 0 12px 0;\n font-size: 14px;\n color: ${styles.tipTextColor};\n font-weight: 500;\n \">💡 For a better experience</p>\n <p style=\"\n margin: 0 0 12px 0;\n font-size: 13px;\n color: ${styles.tipTextColor};\n line-height: 1.4;\n \">Install our browser extension for seamless verification without QR codes</p>\n <a href=\"${this.options.extensionUrl}\" \n target=\"_blank\" \n style=\"\n display: inline-block;\n background: ${styles.extensionButtonBackground};\n color: white;\n text-decoration: none;\n padding: 8px 16px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n transition: background-color 0.2s;\n \"\n onmouseover=\"this.style.backgroundColor='${styles.extensionButtonHover}'\"\n onmouseout=\"this.style.backgroundColor='${styles.extensionButtonBackground}'\">\n Install Extension\n </a>\n </div>` : ''}\n \n <div style=\"margin-top: 16px;\">\n <div id=\"reclaim-countdown\" style=\"\n font-size: 12px;\n color: ${styles.countdownColor};\n font-weight: 400;\n margin-bottom: 8px;\n \">Auto-close in 1:00</div>\n \n <div style=\"\n width: 100%;\n height: 4px;\n background-color: ${styles.progressBackground};\n border-radius: 2px;\n overflow: hidden;\n \">\n <div id=\"reclaim-progress-bar\" style=\"\n width: 100%;\n height: 100%;\n background: ${styles.progressGradient};\n border-radius: 2px;\n transition: width 1s linear;\n \"></div>\n </div>\n </div>\n </div>\n </div>\n `\n }\n\n private async generateQRCode(text: string, containerId: string): Promise<void> {\n try {\n // Simple QR code generation using a public API\n // In production, you might want to use a proper QR code library\n const qrCodeUrl = `${constants.QR_CODE_API_URL}?size=200x200&data=${encodeURIComponent(text)}`;\n\n const container = document.getElementById(containerId);\n const styles = this.getThemeStyles();\n\n if (container) {\n container.innerHTML = `\n <img src=\"${qrCodeUrl}\" \n alt=\"QR Code for Reclaim verification\" \n style=\"width: 200px; height: 200px; border-radius: 4px;\"\n onerror=\"this.style.display='none'; this.nextElementSibling.style.display='block';\">\n <div style=\"display: none; padding: 20px; color: ${styles.textColor}; font-size: 14px;\">\n QR code could not be loaded.<br>\n <a href=\"${text}\" target=\"_blank\" style=\"color: ${styles.linkColor}; text-decoration: underline;\">\n Click here to open verification link\n </a>\n </div>\n `;\n }\n } catch (error) {\n logger.info('Error generating QR code:', error);\n // Fallback to text link\n const container = document.getElementById(containerId);\n const styles = this.getThemeStyles();\n\n if (container) {\n container.innerHTML = `\n <div style=\"padding: 20px; color: ${styles.textColor}; font-size: 14px;\">\n <a href=\"${text}\" target=\"_blank\" style=\"color: ${styles.linkColor}; text-decoration: underline;\">\n Click here to open verification link\n </a>\n </div>\n `;\n }\n }\n }\n\n private addEventListeners(): void {\n const closeButton = document.getElementById('reclaim-close-modal');\n const modal = document.getElementById(this.modalId);\n\n const closeModal = () => {\n this.close();\n };\n\n if (closeButton) {\n closeButton.addEventListener('click', closeModal);\n }\n\n // Close on backdrop click\n if (modal) {\n modal.addEventListener('click', (e) => {\n if (e.target === modal) {\n closeModal();\n }\n });\n }\n\n // Close on escape key\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n closeModal();\n document.removeEventListener('keydown', handleEscape);\n }\n };\n document.addEventListener('keydown', handleEscape);\n }\n\n private startAutoCloseTimer(): void {\n this.countdownSeconds = (this.options.modalPopupTimer || 1) * 60; // default to 1 minute\n\n // Update countdown display immediately\n this.updateCountdownDisplay();\n\n // Start countdown timer (updates every second)\n this.countdownTimer = setInterval(() => {\n this.countdownSeconds--;\n this.updateCountdownDisplay();\n\n if (this.countdownSeconds <= 0) {\n this.close();\n }\n }, 1000);\n\n // Set auto-close timer for the number of minutes specified in the options in milliseconds\n const autoCloseMs = (this.options.modalPopupTimer || 1) * 60 * 1000;\n this.autoCloseTimer = setTimeout(() => {\n this.close();\n }, autoCloseMs);\n }\n\n private updateCountdownDisplay(): void {\n const countdownElement = document.getElementById('reclaim-countdown');\n const progressBar = document.getElementById('reclaim-progress-bar');\n\n if (countdownElement) {\n const minutes = Math.floor(this.countdownSeconds / 60);\n const seconds = this.countdownSeconds % 60;\n const timeString = `${minutes}:${seconds.toString().padStart(2, '0')}`;\n countdownElement.textContent = `Auto-close in ${timeString}`;\n }\n\n if (progressBar) {\n // Calculate progress percentage (reverse: starts at 100%, goes to 0%)\n const totalSeconds = (this.options.modalPopupTimer || 1) * 60;\n const progressPercentage = (this.countdownSeconds / totalSeconds) * 100;\n progressBar.style.width = `${progressPercentage}%`;\n }\n }\n}","import { DeviceType } from \"./types\";\n\nconst navigatorDefined = typeof navigator !== 'undefined';\nconst windowDefined = typeof window !== 'undefined';\n\nconst userAgent = navigatorDefined ? navigator.userAgent.toLowerCase() : '';\nconst userAgentData = navigatorDefined ? (navigator as Navigator & {\n userAgentData?: {\n platform: string;\n brands?: { brand: string; version: string }[];\n }\n}).userAgentData : undefined;\n\n// Cache for device detection results\nlet cachedDeviceType: DeviceType.DESKTOP | DeviceType.MOBILE | null = null;\nlet cachedMobileType: DeviceType.ANDROID | DeviceType.IOS | null = null;\n\n/**\n * Safe wrapper for window.matchMedia\n */\nfunction safeMatchMedia(query: string): boolean {\n try {\n return window.matchMedia?.(query)?.matches || false;\n } catch {\n return false;\n }\n}\n\n/**\n * Safe wrapper for CSS.supports\n */\nfunction safeCSSSupports(property: string, value: string): boolean {\n try {\n return CSS?.supports?.(property, value) || false;\n } catch {\n return false;\n }\n}\n\n/**\n * Safe wrapper for document.querySelector\n */\nfunction safeQuerySelector(selector: string): boolean {\n try {\n return document?.querySelector?.(selector) !== null;\n } catch {\n return false;\n }\n}\n\n/**\n * Highly accurate device type detection - returns only 'desktop' or 'mobile'\n * Uses multiple detection methods and scoring system for maximum accuracy\n * @returns {DeviceType.DESKTOP | DeviceType.MOBILE} The detected device type\n */\nexport function getDeviceType(): DeviceType.DESKTOP | DeviceType.MOBILE {\n // Return cached result if available\n if (cachedDeviceType !== null) {\n return cachedDeviceType;\n }\n\n // Early return for server-side rendering - assume desktop\n if (!navigatorDefined || !windowDefined) {\n return DeviceType.DESKTOP;\n }\n\n let mobileScore = 0;\n const CONFIDENCE_THRESHOLD = 3; // Need at least 3 points to be considered mobile\n \n // ====== Device Characteristics ======\n \n // Screen dimensions\n const screenWidth = window.innerWidth || window.screen?.width || 0;\n const screenHeight = window.innerHeight || window.screen?.height || 0;\n const hasSmallScreen = screenWidth <= 480 || screenHeight <= 480;\n const hasLargeScreen = screenWidth > 1024 && screenHeight > 768;\n \n // Touch capabilities\n const hasTouch = 'ontouchstart' in window || \n (navigatorDefined && navigator.maxTouchPoints > 0);\n const hasPreciseMouse = safeMatchMedia('(pointer: fine)');\n const canHover = safeMatchMedia('(hover: hover)');\n const hasMouseAndTouch = hasTouch && hasPreciseMouse; // Touchscreen laptop\n \n // Windows touch laptop detection (used for exceptions)\n const isWindowsTouchLaptop = /Windows/i.test(userAgent) && \n hasPreciseMouse && \n hasTouch;\n \n // ====== Mobile Indicators (Add Points) ======\n \n // Touch without mouse = likely mobile (+2 points)\n // Touch with mouse = touchscreen laptop (+1 point)\n if (hasTouch && !hasMouseAndTouch) {\n mobileScore += 2;\n } else if (hasMouseAndTouch) {\n mobileScore += 1;\n }\n \n // Small screen is mobile indicator (+2 points)\n // Exception: Windows touch laptops with precise mouse should not be penalized for small screens\n if (hasSmallScreen && !isWindowsTouchLaptop) {\n mobileScore += 2;\n }\n \n // Mobile user agent is strong indicator (+3 points)\n const hasMobileUserAgent = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(userAgent);\n if (hasMobileUserAgent) {\n mobileScore += 3;\n }\n \n // Mobile APIs only count if combined with other mobile signs (+2 points)\n // Exception: Desktop Safari and Windows touch laptops have mobile APIs but should not be considered mobile\n const hasMobileAPIs = 'orientation' in window || \n 'DeviceMotionEvent' in window ||\n 'DeviceOrientationEvent' in window;\n const isDesktopSafari = /Safari/i.test(userAgent) && \n !/Mobile/i.test(userAgent) && \n /Mac|Intel/i.test(userAgent);\n if (hasMobileAPIs && (hasSmallScreen || hasMobileUserAgent) && !isDesktopSafari && !isWindowsTouchLaptop) {\n mobileScore += 2;\n }\n \n // High DPI with small screen = mobile (+1 point)\n const hasHighDPI = window.devicePixelRatio > 1.5;\n if (hasHighDPI && hasSmallScreen) {\n mobileScore += 1;\n }\n \n // Viewport meta tag with small screen = mobile optimized (+1 point)\n const hasViewportMeta = safeQuerySelector('meta[name=\"viewport\"]');\n if (hasViewportMeta && hasSmallScreen) {\n mobileScore += 1;\n }\n \n // iPad Pro special case: Mac user agent with touch (+2 points)\n const isPadProInDesktopMode = userAgent.includes('macintosh') && hasTouch;\n if (isPadProInDesktopMode) {\n mobileScore += 2;\n }\n \n // ====== Desktop Indicators (Subtract Points) ======\n \n // Large screen with mouse = desktop (-3 points)\n if (hasLargeScreen && hasPreciseMouse) {\n mobileScore -= 3;\n } \n // Large screen without touch = desktop (-2 points)\n else if (hasLargeScreen && !hasTouch) {\n mobileScore -= 2;\n }\n \n // Can hover with precise pointer = has real mouse (-2 points)\n if (hasPreciseMouse && canHover) {\n mobileScore -= 2;\n }\n \n // Windows user agent = strong desktop indicator (-3 points)\n const isWindowsDesktop = /Windows/i.test(userAgent) && !hasMobileUserAgent;\n if (isWindowsDesktop) {\n mobileScore -= 3;\n }\n\n // Cache and return the result\n cachedDeviceType = mobileScore >= CONFIDENCE_THRESHOLD ? DeviceType.MOBILE : DeviceType.DESKTOP;\n return cachedDeviceType;\n}\n\n/**\n * Highly accurate mobile device type detection - returns only 'android' or 'ios'\n * Should only be called when getDeviceType() returns 'mobile'\n * @returns {DeviceType.ANDROID | DeviceType.IOS} The detected mobile device type\n */\nexport function getMobileDeviceType(): DeviceType.ANDROID | DeviceType.IOS {\n // Return cached result if available\n if (cachedMobileType !== null) {\n return cachedMobileType;\n }\n\n // Early return for server-side rendering - default to Android\n if (!navigatorDefined || !windowDefined) {\n return DeviceType.ANDROID;\n }\n\n const ua = navigator.userAgent;\n \n // ====== iOS Detection ======\n \n // Direct iOS device detection\n const hasIOSDeviceName = /iPad|iPhone|iPod/i.test(ua);\n if (hasIOSDeviceName) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // iPad Pro detection (reports as Mac but has touch)\n const isMacWithTouch = /Macintosh|MacIntel/i.test(ua) && 'ontouchstart' in window;\n const isMacOSWithTouch = userAgentData?.platform === 'macOS' && 'ontouchstart' in window;\n if (isMacWithTouch || isMacOSWithTouch) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // iOS-specific APIs\n const hasIOSPermissionAPI = typeof (window as any).DeviceMotionEvent?.requestPermission === 'function';\n const hasIOSTouchCallout = safeCSSSupports('-webkit-touch-callout', 'none');\n if (hasIOSPermissionAPI || hasIOSTouchCallout) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // Safari without Chrome (iOS WebKit) - but not desktop Safari\n const isIOSWebKit = /WebKit/i.test(ua) && \n !/Chrome|CriOS|Android/i.test(ua) && \n !/Macintosh|MacIntel/i.test(ua);\n if (isIOSWebKit) {\n cachedMobileType = DeviceType.IOS;\n return cachedMobileType;\n }\n \n // ====== Android Detection ======\n \n // Direct Android detection\n const hasAndroidKeyword = /Android/i.test(ua);\n if (hasAndroidKeyword) {\n cachedMobileType = DeviceType.ANDROID;\n return cachedMobileType;\n }\n \n // Mobile Chrome (usually Android)\n const isChromeOnMobile = (window as any).chrome && /Mobile/i.test(ua);\n if (isChromeOnMobile) {\n cachedMobileType = DeviceType.ANDROID;\n return cachedMobileType;\n }\n \n // Default fallback - Android is more common globally\n cachedMobileType = DeviceType.ANDROID;\n return cachedMobileType;\n}\n\n/**\n * Convenience method to check if current device is mobile\n * @returns {boolean} True if device is mobile\n */\nexport function isMobileDevice(): boolean {\n return getDeviceType() === DeviceType.MOBILE;\n}\n\n/**\n * Convenience method to check if current device is desktop\n * @returns {boolean} True if device is desktop\n */\nexport function isDesktopDevice(): boolean {\n return getDeviceType() === DeviceType.DESKTOP;\n}\n\n/**\n * Clear cached device detection results (useful for testing)\n */\nexport function clearDeviceCache(): void {\n cachedDeviceType = null;\n cachedMobileType = null;\n}\n\n// Export safe wrappers for testing\nexport { safeMatchMedia, safeCSSSupports, safeQuerySelector };"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iBAAAA,UAAAC,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,OAAS;AAAA,QACP;AAAA,MACF;AAAA,MACA,MAAQ;AAAA,QACN,OAAS;AAAA,UACP;AAAA,QACF;AAAA,QACA,WAAa;AAAA,QACb,WAAa;AAAA,QACb,OAAS;AAAA,MACX;AAAA,MACA,SAAW;AAAA,QACT,OAAS;AAAA,QACT,SAAW;AAAA,QACX,MAAQ;AAAA,QACR,cAAc;AAAA,QACd,iBAAiB;AAAA,QACjB,YAAc;AAAA,MAChB;AAAA,MACA,YAAc;AAAA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A,gBAAI,kBAAkB,QAAQ,wDAC1B,kBAAkB,QAAQ,4DAA+C;AACzE,kBAAI,WAAW;AACX,0BAAU,yDAAyD;AAAA,cACvE;AACA,mBAAK,cAAc;AACnB,yBAAK,UAAL,mBAAY;AAAA,YAChB;AAAA,UACJ;AAAA,QACJ,SAAS,GAAG;AACR,cAAI,SAAS;AACT,oBAAQ,CAAU;AAAA,UACtB;AACA,eAAK,cAAc;AACnB,qBAAK,UAAL,mBAAY;AAAA,QAChB;AAAA,MACJ,IAAG,4BAA4B;AAE/B,WAAK,UAAU,IAAI,KAAK,WAAW,QAAQ;AAC3C,iCAA2B,KAAK,WAAW,KAAK,WAAW,OAAO;AAAA,IACtE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,aAAmB;AACf,QAAI,KAAK,OAAO;AACZ,WAAK,MAAM,MAAM;AACjB,MAAAA,QAAO,KAAK,sBAAsB;AAAA,IACtC;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,uBAAgC;AAC5B,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["exports","module","canonicalize","ClaimCreationType","DeviceType","import_ethers","import_canonicalize","logger","import_ethers","import_canonicalize","logger","canonicalize","logger","import_ethers","import_ethers","import_ethers","logger","logger","logger","proof","canonicalize","sdkVersion"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reclaimprotocol/js-sdk",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.7.0",
|
|
4
4
|
"description": "Designed to request proofs from the Reclaim protocol and manage the flow of claims and witness interactions.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -95,4 +95,4 @@
|
|
|
95
95
|
"overrides": {
|
|
96
96
|
"@conventional-changelog/git-client": "^2.0.0"
|
|
97
97
|
}
|
|
98
|
-
}
|
|
98
|
+
}
|