@provex/extension-react 1.0.16 → 1.2.3

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.
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var viem = require('viem');
5
+ var time = require('@provex/utils/time');
6
+ var payment = require('@provex/utils/payment');
7
+ require('@provex/utils/conversionRates');
8
+ var jsxRuntime = require('react/jsx-runtime');
9
+
10
+ // src/ZKTLSContext.tsx
11
+ viem.parseAbiParameter("((string provider, string parameters, string context) claimInfo, ((bytes32 identifier, address owner, uint32 timestampS, uint32 epoch) claim, bytes[] signatures) signedClaim, bool isAppclipProof)");
12
+ var useZKTLS = () => {
13
+ const [isInitialized, setIsInitialized] = react.useState(false);
14
+ react.useEffect(() => {
15
+ const setup = () => {
16
+ setIsInitialized(true);
17
+ };
18
+ const eventName = "peer#initialized";
19
+ if (typeof window.peer !== "undefined") {
20
+ setup();
21
+ } else {
22
+ window.addEventListener(eventName, setup);
23
+ return () => {
24
+ window.removeEventListener(eventName, setup);
25
+ };
26
+ }
27
+ }, []);
28
+ return react.useMemo(() => {
29
+ const fetchProofById = async (proofId) => {
30
+ const proof = await window.peer.fetchProofById(proofId);
31
+ if (proof && proof.notaryRequest) return proof.notaryRequest;
32
+ const proofs = await window.peer.fetchProofs();
33
+ const proofFromList = proofs.notaryRequests.find((p) => p.id === proofId);
34
+ if (proofFromList) return proofFromList;
35
+ return null;
36
+ };
37
+ const waitForProof = async (proofId, onCurrent) => {
38
+ let notaryRequest = null;
39
+ do {
40
+ notaryRequest = await fetchProofById(proofId);
41
+ onCurrent?.(notaryRequest);
42
+ await time.sleep(1e3);
43
+ } while (!notaryRequest || !notaryRequest.status || notaryRequest.status === "pending");
44
+ if (notaryRequest.status === "failed" || notaryRequest.status === "expired" || notaryRequest.status === "cancelled" || notaryRequest.status === "error") {
45
+ throw new Error(`Proof generation failed: ${notaryRequest.status}`);
46
+ }
47
+ return notaryRequest;
48
+ };
49
+ const generateProof = async (inputs) => {
50
+ return await window.peer.generateProof({
51
+ proofIndex: 0,
52
+ ...inputs,
53
+ intentHash: BigInt(inputs.intentHash).toString()
54
+ });
55
+ };
56
+ return {
57
+ /** check if the PeerAuth extension is initialized */
58
+ isInitialized,
59
+ /** request a connection to the PeerAuth extension */
60
+ requestConnection: async () => {
61
+ if (!window.peer) return false;
62
+ return window.peer.requestConnection();
63
+ },
64
+ /**
65
+ * check the connection status of the PeerAuth extension
66
+ * @returns the connection status
67
+ */
68
+ checkConnectionStatus: async () => {
69
+ return await window.peer.checkConnectionStatus();
70
+ },
71
+ /** get the version of the PeerAuth extension */
72
+ getVersion: async () => {
73
+ return await window.peer?.getVersion();
74
+ },
75
+ /** authenticate with the PeerAuth extension */
76
+ authenticate: async (inputs) => {
77
+ let resolve;
78
+ const promise = new Promise((resolver) => {
79
+ resolve = resolver;
80
+ });
81
+ const unsub = window.peer.onMetadataMessage((data) => {
82
+ if (`transfer_${data.platform}` === inputs.actionType) {
83
+ resolve(data);
84
+ }
85
+ });
86
+ await window.peer.authenticate(inputs);
87
+ return await promise.then((data) => {
88
+ unsub();
89
+ return data;
90
+ });
91
+ },
92
+ /** generate a proof */
93
+ generateProof,
94
+ /** wait for a proof to be generated */
95
+ waitForProof,
96
+ /** generate a proof series */
97
+ generateProofSeries: async (inputs, { progress: progressCallback } = {}) => {
98
+ const { platform, provider, intentHash, originalIndex } = inputs;
99
+ const args = {
100
+ platform: provider,
101
+ originalIndex,
102
+ intentHash
103
+ };
104
+ const isChase = platform === payment.extensionPlatforms.CHASE;
105
+ const isZelle = provider === payment.providers.ZELLE;
106
+ const expectedTotal = isZelle && isChase ? 2 : 1;
107
+ progressCallback?.({ progress: 0 /* Generating */, step: 0, id: null, total: expectedTotal });
108
+ const genProofA = await generateProof({ ...args, proofIndex: 0 });
109
+ progressCallback?.({ progress: 1 /* Polling */, step: 0, id: genProofA.proofId, total: expectedTotal });
110
+ const proofA = await waitForProof(genProofA.proofId);
111
+ if (!isChase || !isZelle) {
112
+ progressCallback?.({ progress: 2 /* Complete */, step: null, id: null, total: expectedTotal });
113
+ return [proofA];
114
+ }
115
+ progressCallback?.({ progress: 0 /* Generating */, step: 1, id: null, total: expectedTotal });
116
+ const genProofB = await generateProof({ ...args, proofIndex: 1 });
117
+ progressCallback?.({ progress: 1 /* Polling */, step: 1, id: genProofB.proofId, total: expectedTotal });
118
+ const proofB = await waitForProof(genProofB.proofId);
119
+ progressCallback?.({ progress: 2 /* Complete */, step: null, id: null, total: expectedTotal });
120
+ return [proofA, proofB];
121
+ },
122
+ /** subscribe to metadata messages */
123
+ onMetadataMessage: (fn) => {
124
+ return window.peer.onMetadataMessage(fn);
125
+ },
126
+ /** fetch a proof by its id */
127
+ fetchProofById,
128
+ /** fetch generated proofs */
129
+ fetchGeneratedProofs: async (genProofResponses) => {
130
+ return await Promise.all(genProofResponses.map((r) => fetchProofById(r.proofId)));
131
+ },
132
+ /** fetch all proofs */
133
+ fetchProofs: async () => {
134
+ return await window.peer.fetchProofs();
135
+ },
136
+ /** open the PeerAuth sidebar */
137
+ openSidebar: async (route) => {
138
+ return await window.peer.openSidebar(route);
139
+ }
140
+ };
141
+ }, [isInitialized]);
142
+ };
143
+ var ZKTLSContext = react.createContext(void 0);
144
+ function useZKTLSContext() {
145
+ const context = react.useContext(ZKTLSContext);
146
+ if (context === void 0) {
147
+ throw new Error("useZKTLSContext must be used within a ZKTLSProvider");
148
+ }
149
+ return context;
150
+ }
151
+ function ZKTLSProvider({ children }) {
152
+ const zktlsHook = useZKTLS();
153
+ return /* @__PURE__ */ jsxRuntime.jsx(ZKTLSContext.Provider, { value: zktlsHook, children });
154
+ }
155
+
156
+ exports.ZKTLSContext = ZKTLSContext;
157
+ exports.ZKTLSProvider = ZKTLSProvider;
158
+ exports.useZKTLSContext = useZKTLSContext;
159
+ //# sourceMappingURL=ZKTLSContext.cjs.map
160
+ //# sourceMappingURL=ZKTLSContext.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/useZKTLS.ts","../src/ZKTLSContext.tsx"],"names":["parseAbiParameter","useState","useEffect","useMemo","sleep","extensionPlatforms","providers","createContext","useContext"],"mappings":";;;;;;;;;;AAuN8BA,uBAAkB,qMAAqM;AAuE9O,IAAM,WAAW,MAAM;AAC5B,EAAA,MAAM,CAAC,aAAA,EAAe,gBAAgB,CAAA,GAAIC,eAAS,KAAK,CAAA;AACxD,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,MAAM,QAAQ,MAAM;AAClB,MAAA,gBAAA,CAAiB,IAAI,CAAA;AAAA,IACvB,CAAA;AACA,IAAA,MAAM,SAAA,GAAY,kBAAA;AAClB,IAAA,IAAI,OAAO,MAAA,CAAO,IAAA,KAAS,WAAA,EAAa;AAEtC,MAAA,KAAA,EAAM;AAAA,IACR,CAAA,MAAO;AACL,MAAA,MAAA,CAAO,gBAAA,CAAiB,WAAW,KAAK,CAAA;AACxC,MAAA,OAAO,MAAM;AACX,QAAA,MAAA,CAAO,mBAAA,CAAoB,WAAW,KAAK,CAAA;AAAA,MAC7C,CAAA;AAAA,IACF;AAAA,EACF,CAAA,EAAG,EAAE,CAAA;AACL,EAAA,OAAOC,cAAQ,MAAM;AAEnB,IAAA,MAAM,cAAA,GAAiB,OAAO,OAAA,KAAmD;AAC/E,MAAA,MAAM,KAAA,GAAQ,MAAM,MAAA,CAAO,IAAA,CAAM,eAAe,OAAO,CAAA;AACvD,MAAA,IAAI,KAAA,IAAS,KAAA,CAAM,aAAA,EAAe,OAAO,KAAA,CAAM,aAAA;AAC/C,MAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,IAAA,CAAM,WAAA,EAAY;AAC9C,MAAA,MAAM,aAAA,GAAgB,OAAO,cAAA,CAAe,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,OAAO,OAAO,CAAA;AACxE,MAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,MAAA,OAAO,IAAA;AAAA,IACT,CAAA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file":"ZKTLSContext.cjs","sourcesContent":["/**\n * @fileoverview React hook and utilities for PeerAuth browser extension integration.\n *\n * The PeerAuth extension (formerly ZK-TLS) provides secure proof generation\n * for off-chain payment verification. This module provides:\n *\n * 1. Type definitions for extension API (window.peer)\n * 2. useZKTLS hook for React components\n * 3. Utility functions for transaction matching and proof encoding\n *\n * @remarks\n * The extension exposes `window.peer` (or deprecated `window.zktls`) for:\n * - Requesting connection (OAuth-like flow)\n * - Authenticating with payment providers\n * - Generating notarized proofs\n * - Fetching transaction metadata\n *\n * @see {@link ZKTLSContext} for the React context provider\n */\n\nimport { useEffect, useMemo, useState } from \"react\"\nimport { encodeAbiParameters, encodePacked, parseAbiParameter, parseUnits, type Hex } from \"viem\"\nimport { sleep } from \"@provex/utils/time\"\nimport type { IntentStruct } from \"@provex/utils/intent\"\nimport type { TokenInfo } from \"@provex/utils/tokens\"\nimport { extensionPlatforms, providers, subProviderConfigs, type ActionType, type PlatformKey, type ProviderKey, type SubProviderKey } from \"@provex/utils/payment\"\nimport { convertTokenInputToCurrency } from \"@provex/utils/conversionRates\"\n\ndeclare global {\n interface ZKTLS {\n requestConnection(): Promise<boolean>\n checkConnectionStatus(): Promise<Status>\n getVersion(): Promise<string>\n authenticate(inputs: AuthenticationInputs): Promise<void>\n generateProof(inputs: GenerateProofInputs): Promise<GenerateProofResponse>\n fetchProofById(proofId: string): Promise<ProofResponse>\n fetchProofs(): Promise<FetchProofsResponse>\n openSidebar(route: string): Promise<void>\n onMetadataMessage(fn: (data: MetadataMessageResponse) => void): () => void\n }\n interface Window {\n /** @deprecated Use window.peer instead */\n zktls: ZKTLS | undefined\n /** PeerAuth extension API (replaces window.zktls) */\n peer: ZKTLS | undefined\n }\n}\n\n/** the status of the PeerAuth extension */\nexport type Status = 'connected' | 'disconnected' | 'pending'\n\n/** the individual metadata message sent by the PeerAuth extension */\nexport interface MetadataMessage {\n amount: number\n /** Currency code (e.g., 'USD', 'EUR') */\n currency?: string\n /**\n * Date of the transaction.\n * Can be a string in YYYYMMDD format, a number (YYYYMMDD or timestamp), or Date object.\n * The actual type depends on the extension implementation.\n */\n date: string | number | Date\n hidden: boolean\n originalIndex: number\n paymentId: number\n recipient: string\n}\n\n/** the response from the PeerAuth extension when a metadata message is received */\nexport interface MetadataMessageResponse {\n expiresAt: number\n platform: ProviderKey\n requestId: string\n metadata: MetadataMessage[]\n}\n\n/** the response from the PeerAuth extension when fetching proofs */\nexport interface FetchProofsResponse {\n notaryRequests: NotaryRequest[]\n}\n\n/** the inputs for the generateProof function */\nexport type GenerateProofInputsAbstracted = {\n platform: PlatformKey\n provider: ProviderKey\n intentHash: Hex\n originalIndex: number\n}\n\n/** the inputs for the generateProof function */\nexport type GenerateProofInputs = {\n platform: ProviderKey\n originalIndex: number\n proofIndex?: number\n intentHash: string\n}\n\n/**\n * inputs for the generate proof function that requires the intent hash\n * as hex to ensure it can be converted to a bigint string accurately\n */\nexport type HexIntentGenerateProofInputs = Exclude<GenerateProofInputs, 'intentHash'> & { intentHash: Hex }\n\n/** the response from the PeerAuth extension when generating a proof */\nexport type GenerateProofResponse = {\n proofId: string\n platform: ProviderKey\n}\n\n/** the inputs for the authenticate function */\nexport type AuthenticationInputs = {\n actionType: ActionType\n platform: PlatformKey\n}\n\n/** the response from the PeerAuth extension when fetching a proof */\nexport interface Proof {\n claimInfo: ClaimInfo\n signedClaim: SignedClaim\n isAppclipProof: boolean\n status: string\n}\n\n/** the response from the PeerAuth extension when fetching a proof */\nexport interface NotarizedProof {\n claim: {\n context: string\n epoch: number\n identifier: Hex\n owner: Hex\n parameters: string\n provider: string\n timestampS: number\n },\n signatures: {\n attestorAddress: Hex\n claimSignature: Record<number, number>\n resultSignature: Record<number, number>\n },\n}\n\n/** the claim info for a proof */\nexport interface ClaimInfo {\n provider: string\n parameters: string\n context: string\n}\n\n/** the complete claim data for a proof */\nexport interface CompleteClaimData {\n identifier: Hex\n owner: Hex\n timestampS: number\n epoch: number\n}\n\n/** the signed claim for a proof */\nexport interface SignedClaim {\n claim: CompleteClaimData\n signatures: Hex[]\n}\n\n/** the reclaim proof for a proof */\nexport type ReclaimProof = {\n claimInfo: ClaimInfo\n signedClaim: SignedClaim\n isAppclipProof: boolean\n}\n\n/** the notary request for a proof */\nexport interface NotaryRequest {\n metadata: (string | number)[]\n actionType: ActionType\n id: string\n status: string\n timestamp: number\n proof: NotarizedProof\n}\n\n/** the response from the PeerAuth extension when fetching a proof */\nexport interface ProofResponse {\n notaryRequest: NotaryRequest\n}\n\nexport const extensionUrl = 'https://chromewebstore.google.com/detail/ijpgccednehjpeclfcllnjjcmiohdjih'\n\n/** convert a byte array to a hex string */\nexport const byteArrayToHexString = (byteArray: number[]): Hex => {\n return `0x${byteArray\n .map(byte => byte.toString(16).padStart(2, '0'))\n .join('')}`\n}\n\n/** parse a proof object from the PeerAuth extension */\nexport const parseExtensionProof = (proofObject: NotarizedProof) => {\n return {\n claimInfo: {\n provider: proofObject.claim.provider,\n parameters: proofObject.claim.parameters,\n context: proofObject.claim.context\n },\n signedClaim: {\n claim: {\n identifier: proofObject.claim.identifier as Hex,\n owner: proofObject.claim.owner as Hex,\n timestampS: proofObject.claim.timestampS,\n epoch: proofObject.claim.epoch\n },\n signatures: [byteArrayToHexString(Object.values(proofObject.signatures.claimSignature))]\n },\n isAppclipProof: false\n } as ReclaimProof\n}\n\n/** the abi encoding for a proof */\nexport const PROOF_ENCODING = parseAbiParameter(\"((string provider, string parameters, string context) claimInfo, ((bytes32 identifier, address owner, uint32 timestampS, uint32 epoch) claim, bytes[] signatures) signedClaim, bool isAppclipProof)\")\n\n/** encode a single proof as a bytes array */\nexport function encodeProofAsBytes(proof: ReclaimProof): Hex {\n return encodeAbiParameters([PROOF_ENCODING], [proof])\n}\n\n/** encode two proofs to be passed to the underlying sub-provider */\nexport const encodeTwoProofs = (proof1: ReclaimProof, proof2: ReclaimProof) => {\n return encodeAbiParameters([PROOF_ENCODING, PROOF_ENCODING], [proof1, proof2])\n}\n\n/** a high level function to encode a proof for a given provider and sub-provider */\nexport const encodeProof = ({ extensionProofs, subProvider, provider }: {\n extensionProofs: NotarizedProof[],\n subProvider: PlatformKey | null,\n provider: ProviderKey\n}) => {\n const reclaimProofs = extensionProofs.map((p) => parseExtensionProof(p))\n if (provider === 'zelle') {\n // move this to check the blockchain for the payment method\n const paymentMethod = subProviderConfigs![provider]![subProvider as SubProviderKey]!.paymentMethod\n const twoEncoded = reclaimProofs.length === 2\n ? encodeTwoProofs(reclaimProofs[0]!, reclaimProofs[1]!)\n : encodeProofAsBytes(reclaimProofs[0]!)\n // select between various possible sub-providers\n const withPaymentMethod = encodeProofWithPaymentMethod({\n paymentMethod,\n proof: twoEncoded,\n })\n return withPaymentMethod\n }\n const [reclaimProof] = reclaimProofs\n return encodeProofAsBytes(reclaimProof!)\n}\n\n/**\n * wrap a proof with a payment method and proof\n * this allows us to use a single verifier as an entry point for multiple underlying sub-providers\n */\nexport const encodeProofWithPaymentMethod = ({\n proof,\n paymentMethod\n}: {\n proof: Hex,\n paymentMethod: number\n}): Hex => {\n return encodePacked(['uint8', 'bytes'], [paymentMethod, proof])\n}\n\n/** the progress of a proof series */\nexport enum SeriesProgress {\n Generating,\n Polling,\n Complete,\n}\n\nexport type ProgressInfo = {\n progress: SeriesProgress\n total: number\n step: number | null\n id: string | null\n}\n\n/** the mutations for the generate proof series function */\nexport type GenerateProofSeriesMutations = {\n progress?: ({ progress, step, id }: ProgressInfo) => void\n setOwnerName?: (name: string) => void\n}\n\n/** React hook to interact with the PeerAuth extension */\nexport const useZKTLS = () => {\n const [isInitialized, setIsInitialized] = useState(false)\n useEffect(() => {\n const setup = () => {\n setIsInitialized(true)\n }\n const eventName = 'peer#initialized'\n if (typeof window.peer !== 'undefined') {\n // api is available\n setup()\n } else {\n window.addEventListener(eventName, setup)\n return () => {\n window.removeEventListener(eventName, setup)\n }\n }\n }, [])\n return useMemo(() => {\n /** fetch a proof by its id */\n const fetchProofById = async (proofId: string): Promise<NotaryRequest | null> => {\n const proof = await window.peer!.fetchProofById(proofId)\n if (proof && proof.notaryRequest) return proof.notaryRequest\n const proofs = await window.peer!.fetchProofs()\n const proofFromList = proofs.notaryRequests.find((p) => p.id === proofId)\n if (proofFromList) return proofFromList\n return null\n }\n /** wait for a proof to be generated */\n const waitForProof = async (proofId: string, onCurrent?: (notaryRequest: NotaryRequest | null) => void) => {\n let notaryRequest: NotaryRequest | null = null\n do {\n notaryRequest = await fetchProofById(proofId)\n onCurrent?.(notaryRequest)\n await sleep(1_000)\n } while (!notaryRequest || !notaryRequest.status || notaryRequest.status === 'pending')\n if (notaryRequest.status === 'failed' || notaryRequest.status === 'expired' || notaryRequest.status === 'cancelled' || notaryRequest.status === 'error') {\n throw new Error(`Proof generation failed: ${notaryRequest.status}`)\n }\n return notaryRequest\n }\n /** generate a proof */\n const generateProof = async (inputs: HexIntentGenerateProofInputs): Promise<GenerateProofResponse> => {\n return await window.peer!.generateProof({\n proofIndex: 0,\n ...inputs,\n intentHash: BigInt(inputs.intentHash).toString(),\n })\n }\n return {\n /** check if the PeerAuth extension is initialized */\n isInitialized,\n /** request a connection to the PeerAuth extension */\n requestConnection: async () => {\n if (!window.peer) return false\n return window.peer!.requestConnection()\n },\n /**\n * check the connection status of the PeerAuth extension\n * @returns the connection status\n */\n checkConnectionStatus: async () => {\n return await window.peer!.checkConnectionStatus()\n },\n /** get the version of the PeerAuth extension */\n getVersion: async () => {\n return await window.peer?.getVersion()\n },\n /** authenticate with the PeerAuth extension */\n authenticate: async (inputs: AuthenticationInputs) => {\n // Create promise first to avoid race condition where message arrives before resolver is assigned\n let resolve: (value: MetadataMessageResponse) => void\n const promise = new Promise<MetadataMessageResponse>((resolver) => {\n resolve = resolver\n })\n\n // Now set up the listener - resolve is guaranteed to be the real resolver\n const unsub = window.peer!.onMetadataMessage((data) => {\n if (`transfer_${data.platform}` === inputs.actionType) {\n resolve(data)\n }\n })\n\n await window.peer!.authenticate(inputs)\n\n return await promise.then((data) => {\n unsub()\n return data\n })\n },\n /** generate a proof */\n generateProof,\n /** wait for a proof to be generated */\n waitForProof,\n /** generate a proof series */\n generateProofSeries: async (\n inputs: GenerateProofInputsAbstracted,\n { progress: progressCallback }: GenerateProofSeriesMutations = {},\n ): Promise<NotaryRequest[]> => {\n const { platform, provider, intentHash, originalIndex } = inputs\n const args = {\n platform: provider,\n originalIndex,\n intentHash,\n } as const\n // Chase requires 2 proofs (account verification + transaction)\n // Platform is the bank name (e.g., 'chase') from extensionPlatform config\n const isChase = platform === extensionPlatforms.CHASE\n const isZelle = provider === providers.ZELLE\n const expectedTotal = isZelle && isChase ? 2 : 1\n progressCallback?.({ progress: SeriesProgress.Generating, step: 0, id: null, total: expectedTotal })\n const genProofA = await generateProof({ ...args, proofIndex: 0 })\n progressCallback?.({ progress: SeriesProgress.Polling, step: 0, id: genProofA.proofId, total: expectedTotal })\n const proofA = await waitForProof(genProofA.proofId)\n if (!isChase || !isZelle) {\n progressCallback?.({ progress: SeriesProgress.Complete, step: null, id: null, total: expectedTotal })\n return [proofA]\n }\n progressCallback?.({ progress: SeriesProgress.Generating, step: 1, id: null, total: expectedTotal })\n const genProofB = await generateProof({ ...args, proofIndex: 1 })\n progressCallback?.({ progress: SeriesProgress.Polling, step: 1, id: genProofB.proofId, total: expectedTotal })\n const proofB = await waitForProof(genProofB.proofId)\n progressCallback?.({ progress: SeriesProgress.Complete, step: null, id: null, total: expectedTotal })\n return [proofA, proofB]\n },\n /** subscribe to metadata messages */\n onMetadataMessage: (fn: (data: any) => void) => {\n return window.peer!.onMetadataMessage(fn)\n },\n /** fetch a proof by its id */\n fetchProofById,\n /** fetch generated proofs */\n fetchGeneratedProofs: async (genProofResponses: GenerateProofResponse[]) => {\n return await Promise.all(genProofResponses.map((r) => fetchProofById(r.proofId)))\n },\n /** fetch all proofs */\n fetchProofs: async () => {\n return await window.peer!.fetchProofs()\n },\n /** open the PeerAuth sidebar */\n openSidebar: async (route: string) => {\n return await window.peer!.openSidebar(route)\n },\n }\n }, [isInitialized])\n}\n\n/**\n * Find the metadata message that matches the intent by amount.\n * Returns the first (most recent) transaction in the metadata array that matches the expected amount.\n *\n * Simplified matching: just find transactions with the correct amount.\n * The user can manually select if multiple matches exist.\n */\nexport const findMetadataMessage = ({ metadata, intent, token, centIsInt = false }: {\n metadata: MetadataMessage[],\n intent: IntentStruct,\n token: TokenInfo,\n /** @deprecated No longer used - kept for API compatibility */\n recipient?: string,\n centIsInt?: boolean,\n}): MetadataMessage | null => {\n const currencyAmount = convertTokenInputToCurrency({\n token,\n amountOutInt: intent.amount,\n rate: intent.conversionRate,\n })\n /**\n * Normalize an amount from the extension into a bigint in token base units.\n *\n * The extension sends amounts in different formats per provider:\n * - Venmo: `\"- $1.00\"` (formatted dollar string)\n * - Others: `100` (integer cents) or `1.00` (decimal dollars)\n *\n * We detect the format by checking for currency symbols or decimal points\n * in the raw value. If present, the value is already in dollars and we\n * skip the centIsInt division.\n */\n const normalizeAmount = (amount: number | string): bigint => {\n const raw = String(amount)\n const isFormattedDollars = /[^0-9\\-]/.test(raw) && raw.includes('.')\n const cleaned = raw.replace(/[^0-9.]/g, '')\n let value = parseUnits(cleaned, token.decimals)\n if (centIsInt && !isFormattedDollars) {\n value = value / 100n\n }\n return value\n }\n\n // Skip auto-match when manual selection is forced (dev/testing)\n if (typeof window !== 'undefined' && (window as unknown as Record<string, unknown>).__FORCE_MANUAL_TX_SELECT__) {\n return null\n }\n\n // Find the first transaction that matches the amount (first in array = most recent)\n // Note: We ignore the hidden flag - matching is purely by amount\n const match = metadata.find((m) => {\n const converted = normalizeAmount(m.amount)\n return converted === currencyAmount || converted === (currencyAmount * -1n)\n })\n\n if (!match) {\n return null\n }\n\n return match\n}\n","/**\n * @fileoverview React context for PeerAuth extension state.\n *\n * Provides global access to the useZKTLS hook state throughout the\n * component tree, avoiding prop drilling for extension status.\n *\n * @see {@link useZKTLS} for the underlying hook\n */\n\nimport { createContext, useContext, type ReactNode } from 'react'\nimport { useZKTLS } from './useZKTLS'\n\n/**\n * Context type derived from useZKTLS hook return value.\n */\ntype ZKTLSContextType = ReturnType<typeof useZKTLS>\n\nexport const ZKTLSContext = createContext<ZKTLSContextType | undefined>(undefined)\n\ninterface ZKTLSProviderProps {\n children: ReactNode\n}\n\n/**\n * Hook to consume the ZKTLS context.\n * Must be used within a ZKTLSProvider.\n *\n * @throws Error if used outside of ZKTLSProvider\n */\nexport function useZKTLSContext() {\n const context = useContext(ZKTLSContext)\n if (context === undefined) {\n throw new Error('useZKTLSContext must be used within a ZKTLSProvider')\n }\n return context\n}\n\nexport function ZKTLSProvider({ children }: ZKTLSProviderProps) {\n const zktlsHook = useZKTLS()\n\n return (\n <ZKTLSContext.Provider value={zktlsHook}>\n {children}\n </ZKTLSContext.Provider>\n )\n}\n"]}
@@ -0,0 +1,51 @@
1
+ import { Status, AuthenticationInputs, MetadataMessageResponse, HexIntentGenerateProofInputs, GenerateProofResponse, NotaryRequest, GenerateProofInputsAbstracted, GenerateProofSeriesMutations, FetchProofsResponse } from './useZKTLS.cjs';
2
+ import * as react_jsx_runtime from 'react/jsx-runtime';
3
+ import * as react from 'react';
4
+ import { ReactNode } from 'react';
5
+ import 'viem';
6
+ import '@provex/utils/intent';
7
+ import '@provex/utils/tokens';
8
+ import '@provex/utils/payment';
9
+
10
+ declare const ZKTLSContext: react.Context<{
11
+ isInitialized: boolean;
12
+ requestConnection: () => Promise<boolean>;
13
+ checkConnectionStatus: () => Promise<Status>;
14
+ getVersion: () => Promise<string | undefined>;
15
+ authenticate: (inputs: AuthenticationInputs) => Promise<MetadataMessageResponse>;
16
+ generateProof: (inputs: HexIntentGenerateProofInputs) => Promise<GenerateProofResponse>;
17
+ waitForProof: (proofId: string, onCurrent?: (notaryRequest: NotaryRequest | null) => void) => Promise<NotaryRequest>;
18
+ generateProofSeries: (inputs: GenerateProofInputsAbstracted, { progress: progressCallback }?: GenerateProofSeriesMutations) => Promise<NotaryRequest[]>;
19
+ onMetadataMessage: (fn: (data: any) => void) => () => void;
20
+ fetchProofById: (proofId: string) => Promise<NotaryRequest | null>;
21
+ fetchGeneratedProofs: (genProofResponses: GenerateProofResponse[]) => Promise<(NotaryRequest | null)[]>;
22
+ fetchProofs: () => Promise<FetchProofsResponse>;
23
+ openSidebar: (route: string) => Promise<void>;
24
+ } | undefined>;
25
+ interface ZKTLSProviderProps {
26
+ children: ReactNode;
27
+ }
28
+ /**
29
+ * Hook to consume the ZKTLS context.
30
+ * Must be used within a ZKTLSProvider.
31
+ *
32
+ * @throws Error if used outside of ZKTLSProvider
33
+ */
34
+ declare function useZKTLSContext(): {
35
+ isInitialized: boolean;
36
+ requestConnection: () => Promise<boolean>;
37
+ checkConnectionStatus: () => Promise<Status>;
38
+ getVersion: () => Promise<string | undefined>;
39
+ authenticate: (inputs: AuthenticationInputs) => Promise<MetadataMessageResponse>;
40
+ generateProof: (inputs: HexIntentGenerateProofInputs) => Promise<GenerateProofResponse>;
41
+ waitForProof: (proofId: string, onCurrent?: (notaryRequest: NotaryRequest | null) => void) => Promise<NotaryRequest>;
42
+ generateProofSeries: (inputs: GenerateProofInputsAbstracted, { progress: progressCallback }?: GenerateProofSeriesMutations) => Promise<NotaryRequest[]>;
43
+ onMetadataMessage: (fn: (data: any) => void) => () => void;
44
+ fetchProofById: (proofId: string) => Promise<NotaryRequest | null>;
45
+ fetchGeneratedProofs: (genProofResponses: GenerateProofResponse[]) => Promise<(NotaryRequest | null)[]>;
46
+ fetchProofs: () => Promise<FetchProofsResponse>;
47
+ openSidebar: (route: string) => Promise<void>;
48
+ };
49
+ declare function ZKTLSProvider({ children }: ZKTLSProviderProps): react_jsx_runtime.JSX.Element;
50
+
51
+ export { ZKTLSContext, ZKTLSProvider, useZKTLSContext };
@@ -0,0 +1,51 @@
1
+ import { Status, AuthenticationInputs, MetadataMessageResponse, HexIntentGenerateProofInputs, GenerateProofResponse, NotaryRequest, GenerateProofInputsAbstracted, GenerateProofSeriesMutations, FetchProofsResponse } from './useZKTLS.js';
2
+ import * as react_jsx_runtime from 'react/jsx-runtime';
3
+ import * as react from 'react';
4
+ import { ReactNode } from 'react';
5
+ import 'viem';
6
+ import '@provex/utils/intent';
7
+ import '@provex/utils/tokens';
8
+ import '@provex/utils/payment';
9
+
10
+ declare const ZKTLSContext: react.Context<{
11
+ isInitialized: boolean;
12
+ requestConnection: () => Promise<boolean>;
13
+ checkConnectionStatus: () => Promise<Status>;
14
+ getVersion: () => Promise<string | undefined>;
15
+ authenticate: (inputs: AuthenticationInputs) => Promise<MetadataMessageResponse>;
16
+ generateProof: (inputs: HexIntentGenerateProofInputs) => Promise<GenerateProofResponse>;
17
+ waitForProof: (proofId: string, onCurrent?: (notaryRequest: NotaryRequest | null) => void) => Promise<NotaryRequest>;
18
+ generateProofSeries: (inputs: GenerateProofInputsAbstracted, { progress: progressCallback }?: GenerateProofSeriesMutations) => Promise<NotaryRequest[]>;
19
+ onMetadataMessage: (fn: (data: any) => void) => () => void;
20
+ fetchProofById: (proofId: string) => Promise<NotaryRequest | null>;
21
+ fetchGeneratedProofs: (genProofResponses: GenerateProofResponse[]) => Promise<(NotaryRequest | null)[]>;
22
+ fetchProofs: () => Promise<FetchProofsResponse>;
23
+ openSidebar: (route: string) => Promise<void>;
24
+ } | undefined>;
25
+ interface ZKTLSProviderProps {
26
+ children: ReactNode;
27
+ }
28
+ /**
29
+ * Hook to consume the ZKTLS context.
30
+ * Must be used within a ZKTLSProvider.
31
+ *
32
+ * @throws Error if used outside of ZKTLSProvider
33
+ */
34
+ declare function useZKTLSContext(): {
35
+ isInitialized: boolean;
36
+ requestConnection: () => Promise<boolean>;
37
+ checkConnectionStatus: () => Promise<Status>;
38
+ getVersion: () => Promise<string | undefined>;
39
+ authenticate: (inputs: AuthenticationInputs) => Promise<MetadataMessageResponse>;
40
+ generateProof: (inputs: HexIntentGenerateProofInputs) => Promise<GenerateProofResponse>;
41
+ waitForProof: (proofId: string, onCurrent?: (notaryRequest: NotaryRequest | null) => void) => Promise<NotaryRequest>;
42
+ generateProofSeries: (inputs: GenerateProofInputsAbstracted, { progress: progressCallback }?: GenerateProofSeriesMutations) => Promise<NotaryRequest[]>;
43
+ onMetadataMessage: (fn: (data: any) => void) => () => void;
44
+ fetchProofById: (proofId: string) => Promise<NotaryRequest | null>;
45
+ fetchGeneratedProofs: (genProofResponses: GenerateProofResponse[]) => Promise<(NotaryRequest | null)[]>;
46
+ fetchProofs: () => Promise<FetchProofsResponse>;
47
+ openSidebar: (route: string) => Promise<void>;
48
+ };
49
+ declare function ZKTLSProvider({ children }: ZKTLSProviderProps): react_jsx_runtime.JSX.Element;
50
+
51
+ export { ZKTLSContext, ZKTLSProvider, useZKTLSContext };
@@ -0,0 +1,4 @@
1
+ export { ZKTLSContext, ZKTLSProvider, useZKTLSContext } from './chunk-MXHT5VC5.js';
2
+ import './chunk-DVOEKDW7.js';
3
+ //# sourceMappingURL=ZKTLSContext.js.map
4
+ //# sourceMappingURL=ZKTLSContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"ZKTLSContext.js"}
@@ -0,0 +1,226 @@
1
+ import { useState, useEffect, useMemo } from 'react';
2
+ import { parseAbiParameter, encodeAbiParameters, encodePacked, parseUnits } from 'viem';
3
+ import { sleep } from '@provex/utils/time';
4
+ import { subProviderConfigs, extensionPlatforms, providers } from '@provex/utils/payment';
5
+ import { convertTokenInputToCurrency } from '@provex/utils/conversionRates';
6
+
7
+ // src/useZKTLS.ts
8
+ var extensionUrl = "https://chromewebstore.google.com/detail/ijpgccednehjpeclfcllnjjcmiohdjih";
9
+ var byteArrayToHexString = (byteArray) => {
10
+ return `0x${byteArray.map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
11
+ };
12
+ var parseExtensionProof = (proofObject) => {
13
+ return {
14
+ claimInfo: {
15
+ provider: proofObject.claim.provider,
16
+ parameters: proofObject.claim.parameters,
17
+ context: proofObject.claim.context
18
+ },
19
+ signedClaim: {
20
+ claim: {
21
+ identifier: proofObject.claim.identifier,
22
+ owner: proofObject.claim.owner,
23
+ timestampS: proofObject.claim.timestampS,
24
+ epoch: proofObject.claim.epoch
25
+ },
26
+ signatures: [byteArrayToHexString(Object.values(proofObject.signatures.claimSignature))]
27
+ },
28
+ isAppclipProof: false
29
+ };
30
+ };
31
+ var PROOF_ENCODING = parseAbiParameter("((string provider, string parameters, string context) claimInfo, ((bytes32 identifier, address owner, uint32 timestampS, uint32 epoch) claim, bytes[] signatures) signedClaim, bool isAppclipProof)");
32
+ function encodeProofAsBytes(proof) {
33
+ return encodeAbiParameters([PROOF_ENCODING], [proof]);
34
+ }
35
+ var encodeTwoProofs = (proof1, proof2) => {
36
+ return encodeAbiParameters([PROOF_ENCODING, PROOF_ENCODING], [proof1, proof2]);
37
+ };
38
+ var encodeProof = ({ extensionProofs, subProvider, provider }) => {
39
+ const reclaimProofs = extensionProofs.map((p) => parseExtensionProof(p));
40
+ if (provider === "zelle") {
41
+ const paymentMethod = subProviderConfigs[provider][subProvider].paymentMethod;
42
+ const twoEncoded = reclaimProofs.length === 2 ? encodeTwoProofs(reclaimProofs[0], reclaimProofs[1]) : encodeProofAsBytes(reclaimProofs[0]);
43
+ const withPaymentMethod = encodeProofWithPaymentMethod({
44
+ paymentMethod,
45
+ proof: twoEncoded
46
+ });
47
+ return withPaymentMethod;
48
+ }
49
+ const [reclaimProof] = reclaimProofs;
50
+ return encodeProofAsBytes(reclaimProof);
51
+ };
52
+ var encodeProofWithPaymentMethod = ({
53
+ proof,
54
+ paymentMethod
55
+ }) => {
56
+ return encodePacked(["uint8", "bytes"], [paymentMethod, proof]);
57
+ };
58
+ var SeriesProgress = /* @__PURE__ */ ((SeriesProgress2) => {
59
+ SeriesProgress2[SeriesProgress2["Generating"] = 0] = "Generating";
60
+ SeriesProgress2[SeriesProgress2["Polling"] = 1] = "Polling";
61
+ SeriesProgress2[SeriesProgress2["Complete"] = 2] = "Complete";
62
+ return SeriesProgress2;
63
+ })(SeriesProgress || {});
64
+ var useZKTLS = () => {
65
+ const [isInitialized, setIsInitialized] = useState(false);
66
+ useEffect(() => {
67
+ const setup = () => {
68
+ setIsInitialized(true);
69
+ };
70
+ const eventName = "peer#initialized";
71
+ if (typeof window.peer !== "undefined") {
72
+ setup();
73
+ } else {
74
+ window.addEventListener(eventName, setup);
75
+ return () => {
76
+ window.removeEventListener(eventName, setup);
77
+ };
78
+ }
79
+ }, []);
80
+ return useMemo(() => {
81
+ const fetchProofById = async (proofId) => {
82
+ const proof = await window.peer.fetchProofById(proofId);
83
+ if (proof && proof.notaryRequest) return proof.notaryRequest;
84
+ const proofs = await window.peer.fetchProofs();
85
+ const proofFromList = proofs.notaryRequests.find((p) => p.id === proofId);
86
+ if (proofFromList) return proofFromList;
87
+ return null;
88
+ };
89
+ const waitForProof = async (proofId, onCurrent) => {
90
+ let notaryRequest = null;
91
+ do {
92
+ notaryRequest = await fetchProofById(proofId);
93
+ onCurrent?.(notaryRequest);
94
+ await sleep(1e3);
95
+ } while (!notaryRequest || !notaryRequest.status || notaryRequest.status === "pending");
96
+ if (notaryRequest.status === "failed" || notaryRequest.status === "expired" || notaryRequest.status === "cancelled" || notaryRequest.status === "error") {
97
+ throw new Error(`Proof generation failed: ${notaryRequest.status}`);
98
+ }
99
+ return notaryRequest;
100
+ };
101
+ const generateProof = async (inputs) => {
102
+ return await window.peer.generateProof({
103
+ proofIndex: 0,
104
+ ...inputs,
105
+ intentHash: BigInt(inputs.intentHash).toString()
106
+ });
107
+ };
108
+ return {
109
+ /** check if the PeerAuth extension is initialized */
110
+ isInitialized,
111
+ /** request a connection to the PeerAuth extension */
112
+ requestConnection: async () => {
113
+ if (!window.peer) return false;
114
+ return window.peer.requestConnection();
115
+ },
116
+ /**
117
+ * check the connection status of the PeerAuth extension
118
+ * @returns the connection status
119
+ */
120
+ checkConnectionStatus: async () => {
121
+ return await window.peer.checkConnectionStatus();
122
+ },
123
+ /** get the version of the PeerAuth extension */
124
+ getVersion: async () => {
125
+ return await window.peer?.getVersion();
126
+ },
127
+ /** authenticate with the PeerAuth extension */
128
+ authenticate: async (inputs) => {
129
+ let resolve;
130
+ const promise = new Promise((resolver) => {
131
+ resolve = resolver;
132
+ });
133
+ const unsub = window.peer.onMetadataMessage((data) => {
134
+ if (`transfer_${data.platform}` === inputs.actionType) {
135
+ resolve(data);
136
+ }
137
+ });
138
+ await window.peer.authenticate(inputs);
139
+ return await promise.then((data) => {
140
+ unsub();
141
+ return data;
142
+ });
143
+ },
144
+ /** generate a proof */
145
+ generateProof,
146
+ /** wait for a proof to be generated */
147
+ waitForProof,
148
+ /** generate a proof series */
149
+ generateProofSeries: async (inputs, { progress: progressCallback } = {}) => {
150
+ const { platform, provider, intentHash, originalIndex } = inputs;
151
+ const args = {
152
+ platform: provider,
153
+ originalIndex,
154
+ intentHash
155
+ };
156
+ const isChase = platform === extensionPlatforms.CHASE;
157
+ const isZelle = provider === providers.ZELLE;
158
+ const expectedTotal = isZelle && isChase ? 2 : 1;
159
+ progressCallback?.({ progress: 0 /* Generating */, step: 0, id: null, total: expectedTotal });
160
+ const genProofA = await generateProof({ ...args, proofIndex: 0 });
161
+ progressCallback?.({ progress: 1 /* Polling */, step: 0, id: genProofA.proofId, total: expectedTotal });
162
+ const proofA = await waitForProof(genProofA.proofId);
163
+ if (!isChase || !isZelle) {
164
+ progressCallback?.({ progress: 2 /* Complete */, step: null, id: null, total: expectedTotal });
165
+ return [proofA];
166
+ }
167
+ progressCallback?.({ progress: 0 /* Generating */, step: 1, id: null, total: expectedTotal });
168
+ const genProofB = await generateProof({ ...args, proofIndex: 1 });
169
+ progressCallback?.({ progress: 1 /* Polling */, step: 1, id: genProofB.proofId, total: expectedTotal });
170
+ const proofB = await waitForProof(genProofB.proofId);
171
+ progressCallback?.({ progress: 2 /* Complete */, step: null, id: null, total: expectedTotal });
172
+ return [proofA, proofB];
173
+ },
174
+ /** subscribe to metadata messages */
175
+ onMetadataMessage: (fn) => {
176
+ return window.peer.onMetadataMessage(fn);
177
+ },
178
+ /** fetch a proof by its id */
179
+ fetchProofById,
180
+ /** fetch generated proofs */
181
+ fetchGeneratedProofs: async (genProofResponses) => {
182
+ return await Promise.all(genProofResponses.map((r) => fetchProofById(r.proofId)));
183
+ },
184
+ /** fetch all proofs */
185
+ fetchProofs: async () => {
186
+ return await window.peer.fetchProofs();
187
+ },
188
+ /** open the PeerAuth sidebar */
189
+ openSidebar: async (route) => {
190
+ return await window.peer.openSidebar(route);
191
+ }
192
+ };
193
+ }, [isInitialized]);
194
+ };
195
+ var findMetadataMessage = ({ metadata, intent, token, centIsInt = false }) => {
196
+ const currencyAmount = convertTokenInputToCurrency({
197
+ token,
198
+ amountOutInt: intent.amount,
199
+ rate: intent.conversionRate
200
+ });
201
+ const normalizeAmount = (amount) => {
202
+ const raw = String(amount);
203
+ const isFormattedDollars = /[^0-9\-]/.test(raw) && raw.includes(".");
204
+ const cleaned = raw.replace(/[^0-9.]/g, "");
205
+ let value = parseUnits(cleaned, token.decimals);
206
+ if (centIsInt && !isFormattedDollars) {
207
+ value = value / 100n;
208
+ }
209
+ return value;
210
+ };
211
+ if (typeof window !== "undefined" && window.__FORCE_MANUAL_TX_SELECT__) {
212
+ return null;
213
+ }
214
+ const match = metadata.find((m) => {
215
+ const converted = normalizeAmount(m.amount);
216
+ return converted === currencyAmount || converted === currencyAmount * -1n;
217
+ });
218
+ if (!match) {
219
+ return null;
220
+ }
221
+ return match;
222
+ };
223
+
224
+ export { PROOF_ENCODING, SeriesProgress, byteArrayToHexString, encodeProof, encodeProofAsBytes, encodeProofWithPaymentMethod, encodeTwoProofs, extensionUrl, findMetadataMessage, parseExtensionProof, useZKTLS };
225
+ //# sourceMappingURL=chunk-DVOEKDW7.js.map
226
+ //# sourceMappingURL=chunk-DVOEKDW7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/useZKTLS.ts"],"names":["SeriesProgress"],"mappings":";;;;;;;AAwLO,IAAM,YAAA,GAAe;AAGrB,IAAM,oBAAA,GAAuB,CAAC,SAAA,KAA6B;AAChE,EAAA,OAAO,CAAA,E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AAAA,IAClB;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AAGA,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAgB,MAAA,CAA8C,0BAAA,EAA4B;AAC9G,IAAA,OAAO,IAAA;AAAA,EACT;AAIA,EAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAM;AACjC,IAAA,MAAM,SAAA,GAAY,eAAA,CAAgB,CAAA,CAAE,MAAM,CAAA;AAC1C,IAAA,OAAO,SAAA,KAAc,cAAA,IAAkB,SAAA,KAAe,cAAA,GAAiB,CAAC,EAAA;AAAA,EAC1E,CAAC,CAAA;AAED,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT","file":"chunk-DVOEKDW7.js","sourcesContent":["/**\n * @fileoverview React hook and utilities for PeerAuth browser extension integration.\n *\n * The PeerAuth extension (formerly ZK-TLS) provides secure proof generation\n * for off-chain payment verification. This module provides:\n *\n * 1. Type definitions for extension API (window.peer)\n * 2. useZKTLS hook for React components\n * 3. Utility functions for transaction matching and proof encoding\n *\n * @remarks\n * The extension exposes `window.peer` (or deprecated `window.zktls`) for:\n * - Requesting connection (OAuth-like flow)\n * - Authenticating with payment providers\n * - Generating notarized proofs\n * - Fetching transaction metadata\n *\n * @see {@link ZKTLSContext} for the React context provider\n */\n\nimport { useEffect, useMemo, useState } from \"react\"\nimport { encodeAbiParameters, encodePacked, parseAbiParameter, parseUnits, type Hex } from \"viem\"\nimport { sleep } from \"@provex/utils/time\"\nimport type { IntentStruct } from \"@provex/utils/intent\"\nimport type { TokenInfo } from \"@provex/utils/tokens\"\nimport { extensionPlatforms, providers, subProviderConfigs, type ActionType, type PlatformKey, type ProviderKey, type SubProviderKey } from \"@provex/utils/payment\"\nimport { convertTokenInputToCurrency } from \"@provex/utils/conversionRates\"\n\ndeclare global {\n interface ZKTLS {\n requestConnection(): Promise<boolean>\n checkConnectionStatus(): Promise<Status>\n getVersion(): Promise<string>\n authenticate(inputs: AuthenticationInputs): Promise<void>\n generateProof(inputs: GenerateProofInputs): Promise<GenerateProofResponse>\n fetchProofById(proofId: string): Promise<ProofResponse>\n fetchProofs(): Promise<FetchProofsResponse>\n openSidebar(route: string): Promise<void>\n onMetadataMessage(fn: (data: MetadataMessageResponse) => void): () => void\n }\n interface Window {\n /** @deprecated Use window.peer instead */\n zktls: ZKTLS | undefined\n /** PeerAuth extension API (replaces window.zktls) */\n peer: ZKTLS | undefined\n }\n}\n\n/** the status of the PeerAuth extension */\nexport type Status = 'connected' | 'disconnected' | 'pending'\n\n/** the individual metadata message sent by the PeerAuth extension */\nexport interface MetadataMessage {\n amount: number\n /** Currency code (e.g., 'USD', 'EUR') */\n currency?: string\n /**\n * Date of the transaction.\n * Can be a string in YYYYMMDD format, a number (YYYYMMDD or timestamp), or Date object.\n * The actual type depends on the extension implementation.\n */\n date: string | number | Date\n hidden: boolean\n originalIndex: number\n paymentId: number\n recipient: string\n}\n\n/** the response from the PeerAuth extension when a metadata message is received */\nexport interface MetadataMessageResponse {\n expiresAt: number\n platform: ProviderKey\n requestId: string\n metadata: MetadataMessage[]\n}\n\n/** the response from the PeerAuth extension when fetching proofs */\nexport interface FetchProofsResponse {\n notaryRequests: NotaryRequest[]\n}\n\n/** the inputs for the generateProof function */\nexport type GenerateProofInputsAbstracted = {\n platform: PlatformKey\n provider: ProviderKey\n intentHash: Hex\n originalIndex: number\n}\n\n/** the inputs for the generateProof function */\nexport type GenerateProofInputs = {\n platform: ProviderKey\n originalIndex: number\n proofIndex?: number\n intentHash: string\n}\n\n/**\n * inputs for the generate proof function that requires the intent hash\n * as hex to ensure it can be converted to a bigint string accurately\n */\nexport type HexIntentGenerateProofInputs = Exclude<GenerateProofInputs, 'intentHash'> & { intentHash: Hex }\n\n/** the response from the PeerAuth extension when generating a proof */\nexport type GenerateProofResponse = {\n proofId: string\n platform: ProviderKey\n}\n\n/** the inputs for the authenticate function */\nexport type AuthenticationInputs = {\n actionType: ActionType\n platform: PlatformKey\n}\n\n/** the response from the PeerAuth extension when fetching a proof */\nexport interface Proof {\n claimInfo: ClaimInfo\n signedClaim: SignedClaim\n isAppclipProof: boolean\n status: string\n}\n\n/** the response from the PeerAuth extension when fetching a proof */\nexport interface NotarizedProof {\n claim: {\n context: string\n epoch: number\n identifier: Hex\n owner: Hex\n parameters: string\n provider: string\n timestampS: number\n },\n signatures: {\n attestorAddress: Hex\n claimSignature: Record<number, number>\n resultSignature: Record<number, number>\n },\n}\n\n/** the claim info for a proof */\nexport interface ClaimInfo {\n provider: string\n parameters: string\n context: string\n}\n\n/** the complete claim data for a proof */\nexport interface CompleteClaimData {\n identifier: Hex\n owner: Hex\n timestampS: number\n epoch: number\n}\n\n/** the signed claim for a proof */\nexport interface SignedClaim {\n claim: CompleteClaimData\n signatures: Hex[]\n}\n\n/** the reclaim proof for a proof */\nexport type ReclaimProof = {\n claimInfo: ClaimInfo\n signedClaim: SignedClaim\n isAppclipProof: boolean\n}\n\n/** the notary request for a proof */\nexport interface NotaryRequest {\n metadata: (string | number)[]\n actionType: ActionType\n id: string\n status: string\n timestamp: number\n proof: NotarizedProof\n}\n\n/** the response from the PeerAuth extension when fetching a proof */\nexport interface ProofResponse {\n notaryRequest: NotaryRequest\n}\n\nexport const extensionUrl = 'https://chromewebstore.google.com/detail/ijpgccednehjpeclfcllnjjcmiohdjih'\n\n/** convert a byte array to a hex string */\nexport const byteArrayToHexString = (byteArray: number[]): Hex => {\n return `0x${byteArray\n .map(byte => byte.toString(16).padStart(2, '0'))\n .join('')}`\n}\n\n/** parse a proof object from the PeerAuth extension */\nexport const parseExtensionProof = (proofObject: NotarizedProof) => {\n return {\n claimInfo: {\n provider: proofObject.claim.provider,\n parameters: proofObject.claim.parameters,\n context: proofObject.claim.context\n },\n signedClaim: {\n claim: {\n identifier: proofObject.claim.identifier as Hex,\n owner: proofObject.claim.owner as Hex,\n timestampS: proofObject.claim.timestampS,\n epoch: proofObject.claim.epoch\n },\n signatures: [byteArrayToHexString(Object.values(proofObject.signatures.claimSignature))]\n },\n isAppclipProof: false\n } as ReclaimProof\n}\n\n/** the abi encoding for a proof */\nexport const PROOF_ENCODING = parseAbiParameter(\"((string provider, string parameters, string context) claimInfo, ((bytes32 identifier, address owner, uint32 timestampS, uint32 epoch) claim, bytes[] signatures) signedClaim, bool isAppclipProof)\")\n\n/** encode a single proof as a bytes array */\nexport function encodeProofAsBytes(proof: ReclaimProof): Hex {\n return encodeAbiParameters([PROOF_ENCODING], [proof])\n}\n\n/** encode two proofs to be passed to the underlying sub-provider */\nexport const encodeTwoProofs = (proof1: ReclaimProof, proof2: ReclaimProof) => {\n return encodeAbiParameters([PROOF_ENCODING, PROOF_ENCODING], [proof1, proof2])\n}\n\n/** a high level function to encode a proof for a given provider and sub-provider */\nexport const encodeProof = ({ extensionProofs, subProvider, provider }: {\n extensionProofs: NotarizedProof[],\n subProvider: PlatformKey | null,\n provider: ProviderKey\n}) => {\n const reclaimProofs = extensionProofs.map((p) => parseExtensionProof(p))\n if (provider === 'zelle') {\n // move this to check the blockchain for the payment method\n const paymentMethod = subProviderConfigs![provider]![subProvider as SubProviderKey]!.paymentMethod\n const twoEncoded = reclaimProofs.length === 2\n ? encodeTwoProofs(reclaimProofs[0]!, reclaimProofs[1]!)\n : encodeProofAsBytes(reclaimProofs[0]!)\n // select between various possible sub-providers\n const withPaymentMethod = encodeProofWithPaymentMethod({\n paymentMethod,\n proof: twoEncoded,\n })\n return withPaymentMethod\n }\n const [reclaimProof] = reclaimProofs\n return encodeProofAsBytes(reclaimProof!)\n}\n\n/**\n * wrap a proof with a payment method and proof\n * this allows us to use a single verifier as an entry point for multiple underlying sub-providers\n */\nexport const encodeProofWithPaymentMethod = ({\n proof,\n paymentMethod\n}: {\n proof: Hex,\n paymentMethod: number\n}): Hex => {\n return encodePacked(['uint8', 'bytes'], [paymentMethod, proof])\n}\n\n/** the progress of a proof series */\nexport enum SeriesProgress {\n Generating,\n Polling,\n Complete,\n}\n\nexport type ProgressInfo = {\n progress: SeriesProgress\n total: number\n step: number | null\n id: string | null\n}\n\n/** the mutations for the generate proof series function */\nexport type GenerateProofSeriesMutations = {\n progress?: ({ progress, step, id }: ProgressInfo) => void\n setOwnerName?: (name: string) => void\n}\n\n/** React hook to interact with the PeerAuth extension */\nexport const useZKTLS = () => {\n const [isInitialized, setIsInitialized] = useState(false)\n useEffect(() => {\n const setup = () => {\n setIsInitialized(true)\n }\n const eventName = 'peer#initialized'\n if (typeof window.peer !== 'undefined') {\n // api is available\n setup()\n } else {\n window.addEventListener(eventName, setup)\n return () => {\n window.removeEventListener(eventName, setup)\n }\n }\n }, [])\n return useMemo(() => {\n /** fetch a proof by its id */\n const fetchProofById = async (proofId: string): Promise<NotaryRequest | null> => {\n const proof = await window.peer!.fetchProofById(proofId)\n if (proof && proof.notaryRequest) return proof.notaryRequest\n const proofs = await window.peer!.fetchProofs()\n const proofFromList = proofs.notaryRequests.find((p) => p.id === proofId)\n if (proofFromList) return proofFromList\n return null\n }\n /** wait for a proof to be generated */\n const waitForProof = async (proofId: string, onCurrent?: (notaryRequest: NotaryRequest | null) => void) => {\n let notaryRequest: NotaryRequest | null = null\n do {\n notaryRequest = await fetchProofById(proofId)\n onCurrent?.(notaryRequest)\n await sleep(1_000)\n } while (!notaryRequest || !notaryRequest.status || notaryRequest.status === 'pending')\n if (notaryRequest.status === 'failed' || notaryRequest.status === 'expired' || notaryRequest.status === 'cancelled' || notaryRequest.status === 'error') {\n throw new Error(`Proof generation failed: ${notaryRequest.status}`)\n }\n return notaryRequest\n }\n /** generate a proof */\n const generateProof = async (inputs: HexIntentGenerateProofInputs): Promise<GenerateProofResponse> => {\n return await window.peer!.generateProof({\n proofIndex: 0,\n ...inputs,\n intentHash: BigInt(inputs.intentHash).toString(),\n })\n }\n return {\n /** check if the PeerAuth extension is initialized */\n isInitialized,\n /** request a connection to the PeerAuth extension */\n requestConnection: async () => {\n if (!window.peer) return false\n return window.peer!.requestConnection()\n },\n /**\n * check the connection status of the PeerAuth extension\n * @returns the connection status\n */\n checkConnectionStatus: async () => {\n return await window.peer!.checkConnectionStatus()\n },\n /** get the version of the PeerAuth extension */\n getVersion: async () => {\n return await window.peer?.getVersion()\n },\n /** authenticate with the PeerAuth extension */\n authenticate: async (inputs: AuthenticationInputs) => {\n // Create promise first to avoid race condition where message arrives before resolver is assigned\n let resolve: (value: MetadataMessageResponse) => void\n const promise = new Promise<MetadataMessageResponse>((resolver) => {\n resolve = resolver\n })\n\n // Now set up the listener - resolve is guaranteed to be the real resolver\n const unsub = window.peer!.onMetadataMessage((data) => {\n if (`transfer_${data.platform}` === inputs.actionType) {\n resolve(data)\n }\n })\n\n await window.peer!.authenticate(inputs)\n\n return await promise.then((data) => {\n unsub()\n return data\n })\n },\n /** generate a proof */\n generateProof,\n /** wait for a proof to be generated */\n waitForProof,\n /** generate a proof series */\n generateProofSeries: async (\n inputs: GenerateProofInputsAbstracted,\n { progress: progressCallback }: GenerateProofSeriesMutations = {},\n ): Promise<NotaryRequest[]> => {\n const { platform, provider, intentHash, originalIndex } = inputs\n const args = {\n platform: provider,\n originalIndex,\n intentHash,\n } as const\n // Chase requires 2 proofs (account verification + transaction)\n // Platform is the bank name (e.g., 'chase') from extensionPlatform config\n const isChase = platform === extensionPlatforms.CHASE\n const isZelle = provider === providers.ZELLE\n const expectedTotal = isZelle && isChase ? 2 : 1\n progressCallback?.({ progress: SeriesProgress.Generating, step: 0, id: null, total: expectedTotal })\n const genProofA = await generateProof({ ...args, proofIndex: 0 })\n progressCallback?.({ progress: SeriesProgress.Polling, step: 0, id: genProofA.proofId, total: expectedTotal })\n const proofA = await waitForProof(genProofA.proofId)\n if (!isChase || !isZelle) {\n progressCallback?.({ progress: SeriesProgress.Complete, step: null, id: null, total: expectedTotal })\n return [proofA]\n }\n progressCallback?.({ progress: SeriesProgress.Generating, step: 1, id: null, total: expectedTotal })\n const genProofB = await generateProof({ ...args, proofIndex: 1 })\n progressCallback?.({ progress: SeriesProgress.Polling, step: 1, id: genProofB.proofId, total: expectedTotal })\n const proofB = await waitForProof(genProofB.proofId)\n progressCallback?.({ progress: SeriesProgress.Complete, step: null, id: null, total: expectedTotal })\n return [proofA, proofB]\n },\n /** subscribe to metadata messages */\n onMetadataMessage: (fn: (data: any) => void) => {\n return window.peer!.onMetadataMessage(fn)\n },\n /** fetch a proof by its id */\n fetchProofById,\n /** fetch generated proofs */\n fetchGeneratedProofs: async (genProofResponses: GenerateProofResponse[]) => {\n return await Promise.all(genProofResponses.map((r) => fetchProofById(r.proofId)))\n },\n /** fetch all proofs */\n fetchProofs: async () => {\n return await window.peer!.fetchProofs()\n },\n /** open the PeerAuth sidebar */\n openSidebar: async (route: string) => {\n return await window.peer!.openSidebar(route)\n },\n }\n }, [isInitialized])\n}\n\n/**\n * Find the metadata message that matches the intent by amount.\n * Returns the first (most recent) transaction in the metadata array that matches the expected amount.\n *\n * Simplified matching: just find transactions with the correct amount.\n * The user can manually select if multiple matches exist.\n */\nexport const findMetadataMessage = ({ metadata, intent, token, centIsInt = false }: {\n metadata: MetadataMessage[],\n intent: IntentStruct,\n token: TokenInfo,\n /** @deprecated No longer used - kept for API compatibility */\n recipient?: string,\n centIsInt?: boolean,\n}): MetadataMessage | null => {\n const currencyAmount = convertTokenInputToCurrency({\n token,\n amountOutInt: intent.amount,\n rate: intent.conversionRate,\n })\n /**\n * Normalize an amount from the extension into a bigint in token base units.\n *\n * The extension sends amounts in different formats per provider:\n * - Venmo: `\"- $1.00\"` (formatted dollar string)\n * - Others: `100` (integer cents) or `1.00` (decimal dollars)\n *\n * We detect the format by checking for currency symbols or decimal points\n * in the raw value. If present, the value is already in dollars and we\n * skip the centIsInt division.\n */\n const normalizeAmount = (amount: number | string): bigint => {\n const raw = String(amount)\n const isFormattedDollars = /[^0-9\\-]/.test(raw) && raw.includes('.')\n const cleaned = raw.replace(/[^0-9.]/g, '')\n let value = parseUnits(cleaned, token.decimals)\n if (centIsInt && !isFormattedDollars) {\n value = value / 100n\n }\n return value\n }\n\n // Skip auto-match when manual selection is forced (dev/testing)\n if (typeof window !== 'undefined' && (window as unknown as Record<string, unknown>).__FORCE_MANUAL_TX_SELECT__) {\n return null\n }\n\n // Find the first transaction that matches the amount (first in array = most recent)\n // Note: We ignore the hidden flag - matching is purely by amount\n const match = metadata.find((m) => {\n const converted = normalizeAmount(m.amount)\n return converted === currencyAmount || converted === (currencyAmount * -1n)\n })\n\n if (!match) {\n return null\n }\n\n return match\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import { useZKTLS } from './chunk-DVOEKDW7.js';
2
+ import { createContext, useContext } from 'react';
3
+ import { jsx } from 'react/jsx-runtime';
4
+
5
+ var ZKTLSContext = createContext(void 0);
6
+ function useZKTLSContext() {
7
+ const context = useContext(ZKTLSContext);
8
+ if (context === void 0) {
9
+ throw new Error("useZKTLSContext must be used within a ZKTLSProvider");
10
+ }
11
+ return context;
12
+ }
13
+ function ZKTLSProvider({ children }) {
14
+ const zktlsHook = useZKTLS();
15
+ return /* @__PURE__ */ jsx(ZKTLSContext.Provider, { value: zktlsHook, children });
16
+ }
17
+
18
+ export { ZKTLSContext, ZKTLSProvider, useZKTLSContext };
19
+ //# sourceMappingURL=chunk-MXHT5VC5.js.map
20
+ //# sourceMappingURL=chunk-MXHT5VC5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ZKTLSContext.tsx"],"names":[],"mappings":";;;;AAiBO,IAAM,YAAA,GAAe,cAA4C,MAAS;AAY1E,SAAS,eAAA,GAAkB;AAChC,EAAA,MAAM,OAAA,GAAU,WAAW,YAAY,CAAA;AACvC,EAAA,IAAI,YAAY,MAAA,EAAW;AACzB,IAAA,MAAM,IAAI,MAAM,qDAAqD,CAAA;AAAA,EACvE;AACA,EAAA,OAAO,OAAA;AACT;AAEO,SAAS,aAAA,CAAc,EAAE,QAAA,EAAS,EAAuB;AAC9D,EAAA,MAAM,YAAY,QAAA,EAAS;AAE3B,EAAA,2BACG,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,WAC3B,QAAA,EACH,CAAA;AAEJ","file":"chunk-MXHT5VC5.js","sourcesContent":["/**\n * @fileoverview React context for PeerAuth extension state.\n *\n * Provides global access to the useZKTLS hook state throughout the\n * component tree, avoiding prop drilling for extension status.\n *\n * @see {@link useZKTLS} for the underlying hook\n */\n\nimport { createContext, useContext, type ReactNode } from 'react'\nimport { useZKTLS } from './useZKTLS'\n\n/**\n * Context type derived from useZKTLS hook return value.\n */\ntype ZKTLSContextType = ReturnType<typeof useZKTLS>\n\nexport const ZKTLSContext = createContext<ZKTLSContextType | undefined>(undefined)\n\ninterface ZKTLSProviderProps {\n children: ReactNode\n}\n\n/**\n * Hook to consume the ZKTLS context.\n * Must be used within a ZKTLSProvider.\n *\n * @throws Error if used outside of ZKTLSProvider\n */\nexport function useZKTLSContext() {\n const context = useContext(ZKTLSContext)\n if (context === undefined) {\n throw new Error('useZKTLSContext must be used within a ZKTLSProvider')\n }\n return context\n}\n\nexport function ZKTLSProvider({ children }: ZKTLSProviderProps) {\n const zktlsHook = useZKTLS()\n\n return (\n <ZKTLSContext.Provider value={zktlsHook}>\n {children}\n </ZKTLSContext.Provider>\n )\n}\n"]}