@use-glyph/sdk-react 2.1.9 → 2.1.11

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 CHANGED
@@ -5,3 +5,10 @@ See it in action 🚀: [https://demo.useglyph.io](https://demo.useglyph.io)
5
5
  Dashboard ⚙️: [https://useglyph.io/](https://useglyph.io/)
6
6
 
7
7
  Documentation 📝: [https://docs.useglyph.io/](https://docs.useglyph.io/)
8
+
9
+ ## Diagnostics
10
+
11
+ SDK debug and informational logs are disabled by default. Warnings and errors remain visible.
12
+ Import `setGlyphDebugLogging` from `@use-glyph/sdk-react` and call it with `true` for temporary diagnostics.
13
+ Call it with `false` to disable diagnostics again. Third-party wallet logging is separate.
14
+ Authentication logs never contain signatures, tokens, nonces, or raw provider errors.
@@ -1,71 +1,69 @@
1
1
  import { jsx as J } from "react/jsx-runtime";
2
- import { useState as g, useEffect as m, useCallback as a } from "react";
2
+ import { useState as u, useEffect as h, useCallback as s } from "react";
3
3
  import { useAccount as R, useDisconnect as q, useSignMessage as z, useSignTypedData as H, useSendTransaction as Q, useAccountEffect as V } from "wagmi";
4
4
  import { c as X, W as A, b as Z, a as U } from "./index.js";
5
- const T = "__glyph-widget-token__", I = "__glyph-widget-nonce__", s = X("EIP1193Strategy"), re = ({
5
+ const T = "__glyph-widget-token__", I = "__glyph-widget-nonce__", a = X("EIP1193Strategy"), re = ({
6
6
  children: x,
7
7
  glyphUrl: c,
8
8
  onLogin: M,
9
9
  onLogout: P,
10
- askForSignature: p = !0
10
+ askForSignature: m = !0
11
11
  }) => {
12
- const [j, i] = g(!1), [L, f] = g(null), { address: t, isConnected: n, chainId: _ } = R(), { disconnectAsync: v } = q(), { signMessageAsync: y } = z(), { signTypedDataAsync: k } = H(), { sendTransactionAsync: C } = Q();
13
- s.log({ address: t, isConnected: n });
14
- const [l, w] = g(() => {
12
+ const [j, i] = u(!1), [L, f] = u(null), { address: t, isConnected: n, chainId: _ } = R(), { disconnectAsync: v } = q(), { signMessageAsync: y } = z(), { signTypedDataAsync: k } = H(), { sendTransactionAsync: C } = Q(), [l, p] = u(() => {
15
13
  if (typeof window > "u")
16
14
  return null;
17
15
  try {
18
16
  return localStorage.getItem(T);
19
- } catch (e) {
20
- return s.warn("Error reading session token", e), null;
17
+ } catch {
18
+ return a.warn("Error reading session token"), null;
21
19
  }
22
- }), [u, O] = g(null), [o, E] = g(() => {
20
+ }), [g, O] = u(null), [o, w] = u(() => {
23
21
  if (typeof window > "u")
24
22
  return null;
25
23
  try {
26
24
  return localStorage.getItem(I);
27
- } catch (e) {
28
- return s.warn("Error reading session nonce", e), null;
25
+ } catch {
26
+ return a.warn("Error reading session nonce"), null;
29
27
  }
30
28
  });
31
- m(() => {
29
+ h(() => {
32
30
  try {
33
31
  !l || !o ? (localStorage.removeItem(T), localStorage.removeItem(I)) : (localStorage.setItem(T, l), localStorage.setItem(I, o));
34
- } catch (e) {
35
- s.error("Error saving session token", e);
32
+ } catch {
33
+ a.error("Error saving session token");
36
34
  }
37
35
  }, [o, l]);
38
- const b = a(
36
+ const b = s(
39
37
  async (e) => {
40
38
  try {
41
39
  return await fetch(
42
40
  `${c || A}/api/widget/auth/message/${e}`
43
41
  ).then((d) => d.json());
44
- } catch (r) {
45
- throw s.error("Can't fetch message to sign", r), new Error("Failed to fetch the message to sign.");
42
+ } catch {
43
+ throw a.error("Can't fetch message to sign"), new Error("Failed to fetch the message to sign.");
46
44
  }
47
45
  },
48
46
  [c]
49
- ), D = a(
47
+ ), D = s(
50
48
  async (e, r, d) => {
51
49
  try {
52
50
  return await fetch(`${c || A}/api/widget/auth/verify/${e}`, {
53
51
  method: "POST",
54
52
  body: JSON.stringify({ signature: r, nonce: d })
55
53
  }).then((B) => B.json());
56
- } catch (h) {
57
- throw s.error("Can't verify signature", h), new Error("Signature verification failed.");
54
+ } catch {
55
+ throw a.error("Can't verify signature"), new Error("Signature verification failed.");
58
56
  }
59
57
  },
60
58
  [c]
61
59
  );
62
- m(() => {
60
+ h(() => {
63
61
  !t || !n || o || (i(!0), b(t).then(({ message: e, nonce: r }) => {
64
- O(e), E(r), i(!1);
62
+ O(e), w(r), i(!1);
65
63
  }).finally(() => {
66
64
  i(!1);
67
65
  }));
68
- }, [t, n, b, o]), m(() => {
66
+ }, [t, n, b, o]), h(() => {
69
67
  if (!l || !o) return;
70
68
  const e = Z(c || A, async () => l, {
71
69
  "x-evm-address": t,
@@ -73,64 +71,62 @@ const T = "__glyph-widget-token__", I = "__glyph-widget-nonce__", s = X("EIP1193
73
71
  });
74
72
  f(() => e);
75
73
  }, [l, t, c, o]);
76
- const $ = a(async () => {
74
+ const $ = s(async () => {
77
75
  await v();
78
- }, [v]), S = a(async () => {
79
- if (s.log("authenticate"), !t) {
80
- s.error("no wallet connected.");
76
+ }, [v]), E = s(async () => {
77
+ if (a.log("authenticate"), !t) {
78
+ a.error("no wallet connected.");
81
79
  return;
82
80
  }
83
81
  try {
84
- if (!t || !n || !u || !o) {
82
+ if (!t || !n || !g || !o) {
85
83
  f(null), i(!1);
86
84
  return;
87
85
  }
88
86
  i(!0);
89
- const e = await y({ account: t, message: u });
90
- console.log(o, u, e);
91
- const r = (await D(t, e, o))?.token;
92
- w(r);
87
+ const e = await y({ account: t, message: g }), r = (await D(t, e, o))?.token;
88
+ p(r);
93
89
  } catch (e) {
94
- s.error("Authentication failed", e), e?.message?.toLowerCase?.().includes?.("user rejected") || await alert(
90
+ a.error("Authentication failed"), e?.message?.toLowerCase?.().includes?.("user rejected") || await alert(
95
91
  "Authentication failed - your browser could be blocking the popups. Allow popups or try to manually click sign in."
96
- ), f(null), w(null), E(null);
92
+ ), f(null), p(null), w(null);
97
93
  } finally {
98
94
  i(!1), M?.();
99
95
  }
100
- }, [t, n, u, o, y, D]), F = a(async () => {
101
- E(null), w(null), i(!1), f(null), P?.();
102
- }, []), K = a(
96
+ }, [t, n, g, o, y, D]), F = s(async () => {
97
+ w(null), p(null), i(!1), f(null), P?.();
98
+ }, []), K = s(
103
99
  async ({ message: e }) => {
104
100
  if (!t || !n)
105
101
  throw new Error("Wallet not connected");
106
102
  return y({ account: t, message: e });
107
103
  },
108
104
  [t, n, y]
109
- ), G = a(
105
+ ), G = s(
110
106
  async ({ data: e }) => {
111
107
  if (!t || !n)
112
108
  throw new Error("Wallet not connected");
113
- const r = e.types, d = e.primaryType, h = e.message;
114
- return k({ types: r, primaryType: d, message: h });
109
+ const r = e.types, d = e.primaryType, S = e.message;
110
+ return k({ types: r, primaryType: d, message: S });
115
111
  },
116
112
  [t, n, k]
117
- ), Y = a(
113
+ ), Y = s(
118
114
  async ({ transaction: e }) => {
119
115
  if (!t || !n) throw new Error("Wallet not connected");
120
116
  return C({ ...e, chainId: e.chainId || _ });
121
117
  },
122
118
  [t, n, C, _]
123
- ), [N, W] = g(!1);
119
+ ), [N, W] = u(!1);
124
120
  return V({
125
121
  onConnect: () => {
126
- p && W(!0);
122
+ m && W(!0);
127
123
  },
128
124
  onDisconnect: () => {
129
125
  F();
130
126
  }
131
- }), m(() => {
132
- p && n && t && N && o && u && (S(), W(!1));
133
- }, [n, t, S, N, o, u, p]), /* @__PURE__ */ J(
127
+ }), h(() => {
128
+ m && n && t && N && o && g && (E(), W(!1));
129
+ }, [n, t, E, N, o, g, m]), /* @__PURE__ */ J(
134
130
  U.Provider,
135
131
  {
136
132
  value: {
@@ -139,7 +135,7 @@ const T = "__glyph-widget-token__", I = "__glyph-widget-nonce__", s = X("EIP1193
139
135
  glyphUrl: c,
140
136
  // Pass as string to avoid type error (we are passing fallback value in useGlyph hook at a common place)
141
137
  hideWidget: !n || !t,
142
- login: S,
138
+ login: E,
143
139
  logout: $,
144
140
  // on disconnect, logoutSideEffect is called and clears states
145
141
  signMessage: K,
@@ -1 +1 @@
1
- {"version":3,"file":"EIP1193Strategy.js","sources":["../src/context/strategies/EIP1193Strategy.tsx"],"sourcesContent":["import { SignTypedDataParams, UnsignedTransactionRequest } from \"@privy-io/react-auth\";\nimport react, { useCallback, useEffect, useState } from \"react\";\nimport {\n useAccount,\n useAccountEffect,\n useDisconnect,\n useSendTransaction,\n useSignMessage,\n useSignTypedData,\n} from \"wagmi\";\nimport { WIDGET_API_BASE_URL } from \"../../lib/constants\";\nimport { createLogger } from \"../../lib/utils\";\nimport { BaseGlyphProviderOptionsWithSignature } from \"../../types\";\nimport { GlyphApiFetch, GlyphContext, createApiFetch } from \"../GlyphContext\";\n\ntype GlyphSigningMsgResponse = { message: string; nonce: string };\ntype GlyphSignatureVerifyResponse = { token: string };\n\nconst TOKEN_KEY = \"__glyph-widget-token__\";\nconst NONCE_KEY = \"__glyph-widget-nonce__\";\nconst logger = createLogger(\"EIP1193Strategy\");\n\nconst EIP1193Strategy: react.FC<BaseGlyphProviderOptionsWithSignature> = ({\n children,\n glyphUrl,\n onLogin,\n onLogout,\n askForSignature = true\n}) => {\n const [loading, setLoading] = useState(false);\n const [apiFetch, setApiFetch] = useState<GlyphApiFetch | null>(null);\n const { address, isConnected, chainId } = useAccount(); // detect wallet connection\n const { disconnectAsync } = useDisconnect(); // disconnect the wallet\n const { signMessageAsync } = useSignMessage(); // signing messages with the wallet\n const { signTypedDataAsync } = useSignTypedData(); // signing typed data with the wallet\n const { sendTransactionAsync } = useSendTransaction(); // sending transactions with the wallet\n\n logger.log({ address, isConnected });\n\n // Fetch authentication token from session storage\n const [token, setToken] = useState<string | null>(() => {\n if (typeof window === \"undefined\") {\n return null;\n }\n try {\n return localStorage.getItem(TOKEN_KEY);\n } catch (error) {\n logger.warn(\"Error reading session token\", error);\n return null;\n }\n });\n\n const [message, setMessage] = useState<string | null>(null);\n\n // fetch nonce from session storage\n const [sessNonce, setSessNonce] = useState<string | null>(() => {\n if (typeof window === \"undefined\") {\n return null;\n }\n try {\n return localStorage.getItem(NONCE_KEY);\n } catch (error) {\n logger.warn(\"Error reading session nonce\", error);\n return null;\n }\n });\n\n // Keep token and nonce updated in session storage\n useEffect(() => {\n try {\n if (!token || !sessNonce) {\n localStorage.removeItem(TOKEN_KEY);\n localStorage.removeItem(NONCE_KEY);\n } else {\n localStorage.setItem(TOKEN_KEY, token!);\n localStorage.setItem(NONCE_KEY, sessNonce!);\n }\n } catch (error) {\n logger.error(\"Error saving session token\", error);\n }\n }, [sessNonce, token]);\n\n const fetchMessageToSign = useCallback(\n async (address: string): Promise<GlyphSigningMsgResponse> => {\n try {\n const payload = (await fetch(\n `${glyphUrl || WIDGET_API_BASE_URL}/api/widget/auth/message/${address}`\n ).then((resp) => resp.json())) as GlyphSigningMsgResponse;\n\n return payload;\n } catch (error) {\n logger.error(\"Can't fetch message to sign\", error);\n throw new Error(\"Failed to fetch the message to sign.\");\n }\n },\n [glyphUrl]\n );\n\n const verifySignature = useCallback(\n async (address: string, signature: string, nonce: string): Promise<GlyphSignatureVerifyResponse> => {\n try {\n const payload = await fetch(`${glyphUrl || WIDGET_API_BASE_URL}/api/widget/auth/verify/${address}`, {\n method: \"POST\",\n body: JSON.stringify({ signature, nonce })\n }).then((resp) => resp.json());\n return payload as unknown as GlyphSignatureVerifyResponse;\n } catch (error) {\n logger.error(\"Can't verify signature\", error);\n throw new Error(\"Signature verification failed.\");\n }\n },\n [glyphUrl]\n );\n\n useEffect(() => {\n if (!address || !isConnected) return;\n if (sessNonce) return;\n\n setLoading(true);\n fetchMessageToSign(address)\n .then(({ message, nonce }) => {\n setMessage(message);\n setSessNonce(nonce);\n setLoading(false);\n })\n .finally(() => {\n setLoading(false);\n });\n }, [address, isConnected, fetchMessageToSign, sessNonce]);\n\n useEffect(() => {\n if (!token || !sessNonce) return;\n\n const glyphApiFetch = createApiFetch(glyphUrl || WIDGET_API_BASE_URL, async () => token, {\n \"x-evm-address\": address!,\n \"x-glyph-nonce\": sessNonce!\n });\n setApiFetch(() => glyphApiFetch);\n }, [token, address, glyphUrl, sessNonce]);\n\n const disconnect = useCallback(async () => {\n await disconnectAsync();\n }, [disconnectAsync]);\n\n const authenticate = useCallback(async () => {\n logger.log(\"authenticate\");\n if (!address) {\n logger.error(\"no wallet connected.\");\n return;\n }\n\n try {\n if (!address || !isConnected || !message || !sessNonce) {\n setApiFetch(null);\n setLoading(false);\n return;\n }\n\n // Sign a message with the wallet to authenticate\n setLoading(true);\n\n const userSignature = await signMessageAsync({ account: address, message: message });\n console.log(sessNonce, message, userSignature);\n\n const token = (await verifySignature(address, userSignature, sessNonce))?.token;\n\n setToken(token);\n } catch (error) {\n logger.error(\"Authentication failed\", error);\n if (!(error as Error)?.message?.toLowerCase?.().includes?.(\"user rejected\")) {\n await alert(\n \"Authentication failed - your browser could be blocking the popups. Allow popups or try to manually click sign in.\"\n );\n }\n setApiFetch(null);\n setToken(null);\n setSessNonce(null);\n } finally {\n setLoading(false);\n onLogin?.();\n }\n }, [address, isConnected, message, sessNonce, signMessageAsync, verifySignature]);\n\n const logoutSideEffect = useCallback(async () => {\n setSessNonce(null);\n setToken(null);\n setLoading(false);\n setApiFetch(null);\n onLogout?.();\n }, []);\n\n const signMessage = useCallback(\n async ({ message }: { message: string }) => {\n if (!address || !isConnected) {\n throw new Error(\"Wallet not connected\");\n }\n return signMessageAsync({ account: address, message });\n },\n [address, isConnected, signMessageAsync]\n );\n\n const signTypedData = useCallback(\n async ({ data }: { data: SignTypedDataParams }) => {\n if (!address || !isConnected) {\n throw new Error(\"Wallet not connected\");\n }\n const types = data.types;\n const primaryType = data.primaryType as string;\n const message = data.message;\n return signTypedDataAsync({ types, primaryType, message });\n },\n [address, isConnected, signTypedDataAsync]\n );\n\n const sendTransaction = useCallback(\n async ({ transaction }: { transaction: UnsignedTransactionRequest }) => {\n if (!address || !isConnected) throw new Error(\"Wallet not connected\");\n\n return sendTransactionAsync({ ...transaction, chainId: transaction.chainId || chainId } as any);\n },\n [address, isConnected, sendTransactionAsync, chainId]\n );\n\n const [tryAuthenticate, setTryAuthenticate] = useState<boolean>(false);\n // Perform graceful logout when the wallet is disconnected from anywhere within the app\n useAccountEffect({\n onConnect: () => {\n if (askForSignature) {\n // Perform initial authentication when the wallet is connected\n setTryAuthenticate(true);\n }\n },\n onDisconnect: () => {\n logoutSideEffect();\n }\n });\n useEffect(() => {\n if (askForSignature && isConnected && address && tryAuthenticate && sessNonce && message) {\n // Initial authentication\n authenticate();\n setTryAuthenticate(false);\n }\n }, [isConnected, address, authenticate, tryAuthenticate, sessNonce, message, askForSignature]);\n\n return (\n <GlyphContext.Provider\n value={{\n ready: !loading && !!sessNonce,\n authenticated: isConnected && !!address && token !== null,\n glyphUrl: glyphUrl as string, // Pass as string to avoid type error (we are passing fallback value in useGlyph hook at a common place)\n hideWidget: !isConnected || !address,\n login: authenticate,\n logout: disconnect, // on disconnect, logoutSideEffect is called and clears states\n signMessage,\n signTypedData,\n sendTransaction,\n apiFetch: apiFetch!\n }}\n children={children}\n />\n );\n};\n\nexport default EIP1193Strategy;\n"],"names":["TOKEN_KEY","NONCE_KEY","logger","createLogger","EIP1193Strategy","children","glyphUrl","onLogin","onLogout","askForSignature","loading","setLoading","useState","apiFetch","setApiFetch","address","isConnected","chainId","useAccount","disconnectAsync","useDisconnect","signMessageAsync","useSignMessage","signTypedDataAsync","useSignTypedData","sendTransactionAsync","useSendTransaction","token","setToken","error","message","setMessage","sessNonce","setSessNonce","useEffect","fetchMessageToSign","useCallback","WIDGET_API_BASE_URL","resp","verifySignature","signature","nonce","glyphApiFetch","createApiFetch","disconnect","authenticate","userSignature","logoutSideEffect","signMessage","signTypedData","data","types","primaryType","sendTransaction","transaction","tryAuthenticate","setTryAuthenticate","useAccountEffect","jsx","GlyphContext"],"mappings":";;;;AAkBA,MAAMA,IAAY,0BACZC,IAAY,0BACZC,IAASC,EAAa,iBAAiB,GAEvCC,KAAmE,CAAC;AAAA,EACtE,UAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AAAA,EACA,UAAAC;AAAA,EACA,iBAAAC,IAAkB;AACtB,MAAM;AACF,QAAM,CAACC,GAASC,CAAU,IAAIC,EAAS,EAAK,GACtC,CAACC,GAAUC,CAAW,IAAIF,EAA+B,IAAI,GAC7D,EAAE,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KAAW,CAAC,CAACsB;AAAA,QACrB,eAAehB,KAAe,CAAC,CAACD,KAAWY,MAAU;AAAA,QACrD,UAAArB;AAAA;AAAA,QACA,YAAY,CAACU,KAAe,CAACD;AAAA,QAC7B,OAAO8B;AAAA,QACP,QAAQD;AAAA;AAAA,QACR,aAAAI;AAAA,QACA,eAAAC;AAAA,QACA,iBAAAI;AAAA,QACA,UAAAxC;AAAA,MAAA;AAAA,MAEJ,UAAAR;AAAA,IAAA;AAAA,EAAA;AAGZ;"}
1
+ {"version":3,"file":"EIP1193Strategy.js","sources":["../src/context/strategies/EIP1193Strategy.tsx"],"sourcesContent":["import { SignTypedDataParams, UnsignedTransactionRequest } from \"@privy-io/react-auth\";\nimport react, { useCallback, useEffect, useState } from \"react\";\nimport {\n useAccount,\n useAccountEffect,\n useDisconnect,\n useSendTransaction,\n useSignMessage,\n useSignTypedData,\n} from \"wagmi\";\nimport { WIDGET_API_BASE_URL } from \"../../lib/constants\";\nimport { createLogger } from \"../../lib/utils\";\nimport { BaseGlyphProviderOptionsWithSignature } from \"../../types\";\nimport { GlyphApiFetch, GlyphContext, createApiFetch } from \"../GlyphContext\";\n\ntype GlyphSigningMsgResponse = { message: string; nonce: string };\ntype GlyphSignatureVerifyResponse = { token: string };\n\nconst TOKEN_KEY = \"__glyph-widget-token__\";\nconst NONCE_KEY = \"__glyph-widget-nonce__\";\nconst logger = createLogger(\"EIP1193Strategy\");\n\nconst EIP1193Strategy: react.FC<BaseGlyphProviderOptionsWithSignature> = ({\n children,\n glyphUrl,\n onLogin,\n onLogout,\n askForSignature = true\n}) => {\n const [loading, setLoading] = useState(false);\n const [apiFetch, setApiFetch] = useState<GlyphApiFetch | null>(null);\n const { address, isConnected, chainId } = useAccount(); // detect wallet connection\n const { disconnectAsync } = useDisconnect(); // disconnect the wallet\n const { signMessageAsync } = useSignMessage(); // signing messages with the wallet\n const { signTypedDataAsync } = useSignTypedData(); // signing typed data with the wallet\n const { sendTransactionAsync } = useSendTransaction(); // sending transactions with the wallet\n\n // Fetch authentication token from session storage\n const [token, setToken] = useState<string | null>(() => {\n if (typeof window === \"undefined\") {\n return null;\n }\n try {\n return localStorage.getItem(TOKEN_KEY);\n } catch (error) {\n logger.warn(\"Error reading session token\");\n return null;\n }\n });\n\n const [message, setMessage] = useState<string | null>(null);\n\n // fetch nonce from session storage\n const [sessNonce, setSessNonce] = useState<string | null>(() => {\n if (typeof window === \"undefined\") {\n return null;\n }\n try {\n return localStorage.getItem(NONCE_KEY);\n } catch (error) {\n logger.warn(\"Error reading session nonce\");\n return null;\n }\n });\n\n // Keep token and nonce updated in session storage\n useEffect(() => {\n try {\n if (!token || !sessNonce) {\n localStorage.removeItem(TOKEN_KEY);\n localStorage.removeItem(NONCE_KEY);\n } else {\n localStorage.setItem(TOKEN_KEY, token!);\n localStorage.setItem(NONCE_KEY, sessNonce!);\n }\n } catch (error) {\n logger.error(\"Error saving session token\");\n }\n }, [sessNonce, token]);\n\n const fetchMessageToSign = useCallback(\n async (address: string): Promise<GlyphSigningMsgResponse> => {\n try {\n const payload = (await fetch(\n `${glyphUrl || WIDGET_API_BASE_URL}/api/widget/auth/message/${address}`\n ).then((resp) => resp.json())) as GlyphSigningMsgResponse;\n\n return payload;\n } catch (error) {\n logger.error(\"Can't fetch message to sign\");\n throw new Error(\"Failed to fetch the message to sign.\");\n }\n },\n [glyphUrl]\n );\n\n const verifySignature = useCallback(\n async (address: string, signature: string, nonce: string): Promise<GlyphSignatureVerifyResponse> => {\n try {\n const payload = await fetch(`${glyphUrl || WIDGET_API_BASE_URL}/api/widget/auth/verify/${address}`, {\n method: \"POST\",\n body: JSON.stringify({ signature, nonce })\n }).then((resp) => resp.json());\n return payload as unknown as GlyphSignatureVerifyResponse;\n } catch (error) {\n logger.error(\"Can't verify signature\");\n throw new Error(\"Signature verification failed.\");\n }\n },\n [glyphUrl]\n );\n\n useEffect(() => {\n if (!address || !isConnected) return;\n if (sessNonce) return;\n\n setLoading(true);\n fetchMessageToSign(address)\n .then(({ message, nonce }) => {\n setMessage(message);\n setSessNonce(nonce);\n setLoading(false);\n })\n .finally(() => {\n setLoading(false);\n });\n }, [address, isConnected, fetchMessageToSign, sessNonce]);\n\n useEffect(() => {\n if (!token || !sessNonce) return;\n\n const glyphApiFetch = createApiFetch(glyphUrl || WIDGET_API_BASE_URL, async () => token, {\n \"x-evm-address\": address!,\n \"x-glyph-nonce\": sessNonce!\n });\n setApiFetch(() => glyphApiFetch);\n }, [token, address, glyphUrl, sessNonce]);\n\n const disconnect = useCallback(async () => {\n await disconnectAsync();\n }, [disconnectAsync]);\n\n const authenticate = useCallback(async () => {\n logger.log(\"authenticate\");\n if (!address) {\n logger.error(\"no wallet connected.\");\n return;\n }\n\n try {\n if (!address || !isConnected || !message || !sessNonce) {\n setApiFetch(null);\n setLoading(false);\n return;\n }\n\n // Sign a message with the wallet to authenticate\n setLoading(true);\n\n const userSignature = await signMessageAsync({ account: address, message: message });\n\n const token = (await verifySignature(address, userSignature, sessNonce))?.token;\n\n setToken(token);\n } catch (error) {\n logger.error(\"Authentication failed\");\n if (!(error as Error)?.message?.toLowerCase?.().includes?.(\"user rejected\")) {\n await alert(\n \"Authentication failed - your browser could be blocking the popups. Allow popups or try to manually click sign in.\"\n );\n }\n setApiFetch(null);\n setToken(null);\n setSessNonce(null);\n } finally {\n setLoading(false);\n onLogin?.();\n }\n }, [address, isConnected, message, sessNonce, signMessageAsync, verifySignature]);\n\n const logoutSideEffect = useCallback(async () => {\n setSessNonce(null);\n setToken(null);\n setLoading(false);\n setApiFetch(null);\n onLogout?.();\n }, []);\n\n const signMessage = useCallback(\n async ({ message }: { message: string }) => {\n if (!address || !isConnected) {\n throw new Error(\"Wallet not connected\");\n }\n return signMessageAsync({ account: address, message });\n },\n [address, isConnected, signMessageAsync]\n );\n\n const signTypedData = useCallback(\n async ({ data }: { data: SignTypedDataParams }) => {\n if (!address || !isConnected) {\n throw new Error(\"Wallet not connected\");\n }\n const types = data.types;\n const primaryType = data.primaryType as string;\n const message = data.message;\n return signTypedDataAsync({ types, primaryType, message });\n },\n [address, isConnected, signTypedDataAsync]\n );\n\n const sendTransaction = useCallback(\n async ({ transaction }: { transaction: UnsignedTransactionRequest }) => {\n if (!address || !isConnected) throw new Error(\"Wallet not connected\");\n\n return sendTransactionAsync({ ...transaction, chainId: transaction.chainId || chainId } as any);\n },\n [address, isConnected, sendTransactionAsync, chainId]\n );\n\n const [tryAuthenticate, setTryAuthenticate] = useState<boolean>(false);\n // Perform graceful logout when the wallet is disconnected from anywhere within the app\n useAccountEffect({\n onConnect: () => {\n if (askForSignature) {\n // Perform initial authentication when the wallet is connected\n setTryAuthenticate(true);\n }\n },\n onDisconnect: () => {\n logoutSideEffect();\n }\n });\n useEffect(() => {\n if (askForSignature && isConnected && address && tryAuthenticate && sessNonce && message) {\n // Initial authentication\n authenticate();\n setTryAuthenticate(false);\n }\n }, [isConnected, address, authenticate, tryAuthenticate, sessNonce, message, askForSignature]);\n\n return (\n <GlyphContext.Provider\n value={{\n ready: !loading && !!sessNonce,\n authenticated: isConnected && !!address && token !== null,\n glyphUrl: glyphUrl as string, // Pass as string to avoid type error (we are passing fallback value in useGlyph hook at a common place)\n hideWidget: !isConnected || !address,\n login: authenticate,\n logout: disconnect, // on disconnect, logoutSideEffect is called and clears states\n signMessage,\n signTypedData,\n sendTransaction,\n apiFetch: apiFetch!\n }}\n children={children}\n />\n );\n};\n\nexport default EIP1193Strategy;\n"],"names":["TOKEN_KEY","NONCE_KEY","logger","createLogger","EIP1193Strategy","children","glyphUrl","onLogin","onLogout","askForSignature","loading","setLoading","useState","apiFetch","setApiFetch","address","isConnected","chainId","useAccount","disconnectAsync","useDisconnect","signMessageAsync","useSignMessage","signTypedDataAsync","useSignTypedData","sendTransactionAsync","useSendTransaction","token","setToken","message","setMessage","sessNonce","setSessNonce","useEffect","fetchMessageToSign","useCallback","WIDGET_API_BASE_URL","resp","verifySignature","signature","nonce","glyphApiFetch","createApiFetch","disconnect","authenticate","userSignature","error","logoutSideEffect","signMessage","signTypedData","data","types","primaryType","sendTransaction","transaction","tryAuthenticate","setTryAuthenticate","useAccountEffect","jsx","GlyphContext"],"mappings":";;;;AAkBA,MAAMA,IAAY,0BACZC,IAAY,0BACZC,IAASC,EAAa,iBAAiB,GAEvCC,KAAmE,CAAC;AAAA,EACtE,UAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AAAA,EACA,UAAAC;AAAA,EACA,iBAAAC,IAAkB;AACtB,MAAM;AACF,QAAM,CAACC,GAASC,CAAU,IAAIC,EAAS,EAAK,GACtC,CAACC,GAAUC,CAAW,IAAIF,EAA+B,IAAI,GAC7D,EAAE,SAAAG,GAAS,aAAAC,GAAa,SAAAC,EAAA,IAAYC,EAAA,GACpC,EAAE,iBAAAC,EAAA,IAAoBC,EAAA,GACtB,EAAE,kBAAAC,EAAA,IAAqBC,EAAA,GACvB,EAAE,oBAAAC,EAAA,IAAuBC,EAAA,GACzB,EAAE,sBAAAC,EAAA,IAAyBC,EAAA,GAG3B,CAACC,GAAOC,CAAQ,IAAIhB,EAAwB,MAAM;AACpD,QAAI,OAAO,SAAW;AAClB,aAAO;AAEX,QAAI;AACA,aAAO,aAAa,QAAQZ,CAAS;AAAA,IACzC,QAAgB;AACZ,aAAAE,EAAO,KAAK,6BAA6B,GAClC;AAAA,IACX;AAAA,EACJ,CAAC,GAEK,CAAC2B,GAASC,CAAU,IAAIlB,EAAwB,IAAI,GAGpD,CAACmB,GAAWC,CAAY,IAAIpB,EAAwB,MAAM;AAC5D,QAAI,OAAO,SAAW;AAClB,aAAO;AAEX,QAAI;AACA,aAAO,aAAa,QAAQX,CAAS;AAAA,IACzC,QAAgB;AACZ,aAAAC,EAAO,KAAK,6BAA6B,GAClC;AAAA,IACX;AAAA,EACJ,CAAC;AAGD,EAAA+B,EAAU,MAAM;AACZ,QAAI;AACA,MAAI,CAACN,KAAS,CAACI,KACX,aAAa,WAAW/B,CAAS,GACjC,aAAa,WAAWC,CAAS,MAEjC,aAA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AaF,MAE7Ee,EAAA,GACAY,EAAmB,EAAK;AAAA,EAEhC,GAAG,CAACxC,GAAaD,GAAS6B,GAAcW,GAAiBxB,GAAWF,GAASpB,CAAe,CAAC,GAGzF,gBAAAiD;AAAA,IAACC,EAAa;AAAA,IAAb;AAAA,MACG,OAAO;AAAA,QACH,OAAO,CAACjD,KAAW,CAAC,CAACqB;AAAA,QACrB,eAAef,KAAe,CAAC,CAACD,KAAWY,MAAU;AAAA,QACrD,UAAArB;AAAA;AAAA,QACA,YAAY,CAACU,KAAe,CAACD;AAAA,QAC7B,OAAO6B;AAAA,QACP,QAAQD;AAAA;AAAA,QACR,aAAAK;AAAA,QACA,eAAAC;AAAA,QACA,iBAAAI;AAAA,QACA,UAAAxC;AAAA,MAAA;AAAA,MAEJ,UAAAR;AAAA,IAAA;AAAA,EAAA;AAGZ;"}
@@ -1,121 +1,117 @@
1
- import { jsx as q } from "react/jsx-runtime";
2
- import { usePrivy as z, useCrossAppAccounts as J } from "@privy-io/react-auth";
3
- import { memo as K, useState as l, useEffect as O, useCallback as i } from "react";
4
- import { useChainId as Q } from "wagmi";
5
- import { c as X, i as Z, S as W, G as x, a as $, b as ss, W as es } from "./index.js";
6
- const t = X("PrivyStrategy"), ts = ({
7
- children: L,
1
+ import { jsx as j } from "react/jsx-runtime";
2
+ import { usePrivy as B, useCrossAppAccounts as q } from "@privy-io/react-auth";
3
+ import { memo as z, useState as d, useEffect as J, useCallback as o } from "react";
4
+ import { useChainId as K } from "wagmi";
5
+ import { i as O, c as Q, S as W, G as b, a as X, b as Z, W as $ } from "./index.js";
6
+ const a = Q("PrivyStrategy"), ss = ({
7
+ children: M,
8
8
  glyphUrl: p,
9
9
  onLogin: m,
10
10
  onLogout: v,
11
- useStagingTenant: u
11
+ useStagingTenant: l
12
12
  }) => {
13
- const [F, y] = l(!0), [N, g] = l(null), [a, R] = l(null), [r, V] = l(!1), w = Q(), {
14
- ready: o,
15
- authenticated: d,
16
- user: c,
13
+ const [k, u] = d(!0), [x, y] = d(null), [t, L] = d(null), [r, F] = d(!1), w = K(), {
14
+ ready: c,
15
+ authenticated: g,
16
+ user: i,
17
17
  getAccessToken: P,
18
18
  login: _,
19
19
  logout: h,
20
20
  signMessage: T,
21
- signTypedData: b,
22
- sendTransaction: E
23
- } = z(), {
24
- signMessage: G,
25
21
  signTypedData: I,
26
22
  sendTransaction: S
27
- } = J();
28
- t.debug(o, d, !!c), O(() => {
29
- if (!o) {
30
- g(null), y(!0);
23
+ } = B(), {
24
+ signMessage: D,
25
+ signTypedData: E,
26
+ sendTransaction: G
27
+ } = q();
28
+ J(() => {
29
+ if (!c) {
30
+ y(null), u(!0);
31
31
  return;
32
32
  }
33
- if (!d || !c) {
34
- g(null), y(!1);
33
+ if (!g || !i) {
34
+ y(null), u(!1);
35
35
  return;
36
36
  }
37
37
  let s;
38
- const n = c.linkedAccounts?.find(
38
+ const n = i.linkedAccounts?.find(
39
39
  (e) => e.type === "wallet" && e.chainType === "ethereum" && e.walletClientType === "privy"
40
- ), D = n && Z(n.address);
41
- D && t.debug("Privy (main) EVM embedded wallet", n.address), t.debug("finding cross-app accounts...");
42
- const k = c.linkedAccounts?.filter?.((e) => e.type === "cross_app") || [], C = k.filter(
43
- (e) => e.providerApp?.id !== (u ? W : x)
44
- );
45
- t.debug("linked accounts - non-Glyph", { accounts: C });
46
- const f = C.map((e) => e.embeddedWallets[0].address);
47
- f.length > 0 && (s = f[0], t.log("using cross_app (non-Glyph) account"), f.length > 1 && t.warn("too many cross_app accounts"));
48
- const M = k.filter(
49
- (e) => e.providerApp?.id === (u ? W : x)
50
- );
51
- t.debug("linked accounts - Glyph", { accounts: M });
52
- const A = M.map((e) => e.embeddedWallets[0].address);
53
- A.length > 0 && (s = A[0], t.log("using cross_app (Glyph) account"), A.length > 1 && t.warn("too many cross_app accounts")), s ? (V(!0), t.log("using cross_app account", s)) : D && (s = n.address, t.log("using Privy (main) EVM embedded wallet", s)), R(s ?? null), (async () => {
40
+ ), H = n && O(n.address);
41
+ a.debug("finding cross-app accounts...");
42
+ const C = i.linkedAccounts?.filter?.((e) => e.type === "cross_app") || [], f = C.filter(
43
+ (e) => e.providerApp?.id !== (l ? W : b)
44
+ ).map((e) => e.embeddedWallets[0].address);
45
+ f.length > 0 && (s = f[0], a.log("using cross_app (non-Glyph) account"), f.length > 1 && a.warn("too many cross_app accounts"));
46
+ const A = C.filter(
47
+ (e) => e.providerApp?.id === (l ? W : b)
48
+ ).map((e) => e.embeddedWallets[0].address);
49
+ A.length > 0 && (s = A[0], a.log("using cross_app (Glyph) account"), A.length > 1 && a.warn("too many cross_app accounts")), s ? (F(!0), a.log("using cross_app account")) : H && (s = n.address, a.log("using Privy (main) EVM embedded wallet")), L(s ?? null), (async () => {
54
50
  if (!s) {
55
- t.error("user has no wallet");
51
+ a.error("user has no wallet");
56
52
  return;
57
53
  }
58
- const e = ss(
59
- p || es,
54
+ const e = Z(
55
+ p || $,
60
56
  async () => await P(),
61
57
  { "x-evm-address": s }
62
58
  );
63
- g(() => e), y(!1);
59
+ y(() => e), u(!1);
64
60
  })();
65
61
  }, [
66
62
  p,
67
- d,
68
- o,
63
+ g,
69
64
  c,
70
- u,
65
+ i,
66
+ l,
71
67
  r,
72
- a,
68
+ t,
73
69
  P,
74
70
  h
75
71
  ]);
76
- const Y = i(async () => {
72
+ const N = o(async () => {
77
73
  await _(), m?.();
78
- }, [m, _]), U = i(async () => {
74
+ }, [m, _]), R = o(async () => {
79
75
  h(), v?.();
80
- }, [v, h]), H = i(
76
+ }, [v, h]), Y = o(
81
77
  async ({ message: s }) => {
82
- if (!a) throw new Error("No wallet address found");
83
- return r ? G(s, { address: a }) : (await T({ message: s })).signature;
78
+ if (!t) throw new Error("No wallet address found");
79
+ return r ? D(s, { address: t }) : (await T({ message: s })).signature;
84
80
  },
85
- [a, r, G, T]
86
- ), j = i(
81
+ [t, r, D, T]
82
+ ), U = o(
87
83
  async ({ data: s }) => {
88
- if (!a) throw new Error("No wallet address found");
89
- return r ? I(s, { address: a }) : (await b(s)).signature;
84
+ if (!t) throw new Error("No wallet address found");
85
+ return r ? E(s, { address: t }) : (await I(s)).signature;
90
86
  },
91
- [a, r, I, b]
92
- ), B = i(
87
+ [t, r, E, I]
88
+ ), V = o(
93
89
  async ({ transaction: s }) => {
94
- if (!a) throw new Error("No wallet address found");
90
+ if (!t) throw new Error("No wallet address found");
95
91
  const n = { ...s, chainId: s.chainId || w };
96
- return r ? S(n, { address: a }) : (await E(n, { address: a })).hash;
92
+ return r ? G(n, { address: t }) : (await S(n, { address: t })).hash;
97
93
  },
98
- [w, r, a, S, E]
94
+ [w, r, t, G, S]
99
95
  );
100
- return /* @__PURE__ */ q(
101
- $.Provider,
96
+ return /* @__PURE__ */ j(
97
+ X.Provider,
102
98
  {
103
99
  value: {
104
- ready: o && !F,
105
- authenticated: o && d,
100
+ ready: c && !k,
101
+ authenticated: c && g,
106
102
  glyphUrl: p,
107
103
  // Pass as string to avoid type error (we are passing fallback value in useGlyph hook at a common place)
108
- login: Y,
109
- logout: U,
110
- signMessage: H,
111
- signTypedData: j,
112
- sendTransaction: B,
113
- apiFetch: N
104
+ login: N,
105
+ logout: R,
106
+ signMessage: Y,
107
+ signTypedData: U,
108
+ sendTransaction: V,
109
+ apiFetch: x
114
110
  },
115
- children: L
111
+ children: M
116
112
  }
117
113
  );
118
- }, ds = K(ts);
114
+ }, ds = z(ss);
119
115
  export {
120
116
  ds as default
121
117
  };
@@ -1 +1 @@
1
- {"version":3,"file":"PrivyStrategy.js","sources":["../src/context/strategies/PrivyStrategy.tsx"],"sourcesContent":["import {\n SignTypedDataParams,\n UnsignedTransactionRequest,\n useCrossAppAccounts,\n usePrivy,\n WalletWithMetadata\n} from \"@privy-io/react-auth\";\nimport react, { memo, useCallback, useEffect, useState } from \"react\";\nimport { useChainId } from \"wagmi\";\nimport { GLYPH_PRIVY_APP_ID, STAGING_GLYPH_PRIVY_APP_ID, WIDGET_API_BASE_URL } from \"../../lib/constants\";\nimport { createLogger, isEthereumAddress } from \"../../lib/utils\";\nimport { BaseGlyphProviderOptions } from \"../../types\";\nimport { createApiFetch, GlyphApiFetch, GlyphContext } from \"../GlyphContext\";\n\nconst logger = createLogger(\"PrivyStrategy\");\n\nconst PrivyStrategy: react.FC<BaseGlyphProviderOptions> = ({\n children,\n glyphUrl,\n onLogin,\n onLogout,\n useStagingTenant\n}) => {\n const [loading, setLoading] = useState<boolean>(true);\n const [apiFetch, setApiFetch] = useState<GlyphApiFetch | null>(null);\n const [walletAddress, setWalletAddress] = useState<string | null>(null);\n const [usesCrossapp, setUsesCrossapp] = useState<boolean>(false);\n const chainId = useChainId();\n\n const {\n ready: privyReady,\n authenticated: privyAuthenticated,\n user: privyUser,\n getAccessToken: getPrivyAccessToken,\n login: privyLogin,\n logout: privyLogout,\n signMessage: privySignMessage,\n signTypedData: privySignTypedData,\n sendTransaction: privySendTransaction\n } = usePrivy();\n\n const {\n signMessage: crossAppSignMessage,\n signTypedData: crossAppSignTypedData,\n sendTransaction: crossAppSendTransaction\n } = useCrossAppAccounts();\n\n logger.debug(privyReady, privyAuthenticated, !!privyUser);\n\n useEffect(() => {\n // If Privy is not ready, reset widget state (loading: true)\n if (!privyReady) {\n setApiFetch(null);\n setLoading(true);\n return;\n }\n\n // If user is not authenticated, reset widget state (loading: false)\n if (!privyAuthenticated || !privyUser) {\n setApiFetch(null);\n setLoading(false);\n return;\n }\n\n let address: string | undefined;\n\n const privyEvmWallet = privyUser!.linkedAccounts?.find(\n (w) => w.type === \"wallet\" && w.chainType === \"ethereum\" && w.walletClientType === \"privy\"\n ) as WalletWithMetadata | undefined;\n\n const hasPrivyEvmWallet = privyEvmWallet && isEthereumAddress(privyEvmWallet.address);\n if (hasPrivyEvmWallet) logger.debug(\"Privy (main) EVM embedded wallet\", privyEvmWallet.address);\n\n logger.debug(\"finding cross-app accounts...\");\n // Cross-app accounts are always EVM addresses\n const crossAppAccounts = privyUser!.linkedAccounts?.filter?.((account) => account.type === \"cross_app\") || [];\n\n const otherAccounts = crossAppAccounts.filter(\n (account) =>\n account.providerApp?.id !== (useStagingTenant ? STAGING_GLYPH_PRIVY_APP_ID : GLYPH_PRIVY_APP_ID)\n );\n logger.debug(\"linked accounts - non-Glyph\", { accounts: otherAccounts });\n const otherAddresses = otherAccounts.map((account) => account.embeddedWallets[0].address);\n if (otherAddresses.length > 0) {\n address = otherAddresses[0];\n logger.log(\"using cross_app (non-Glyph) account\");\n if (otherAddresses.length > 1) {\n logger.warn(\"too many cross_app accounts\");\n }\n }\n\n const glyphAccounts = crossAppAccounts.filter(\n (account) =>\n account.providerApp?.id === (useStagingTenant ? STAGING_GLYPH_PRIVY_APP_ID : GLYPH_PRIVY_APP_ID)\n );\n logger.debug(\"linked accounts - Glyph\", { accounts: glyphAccounts });\n const glyphAddresses = glyphAccounts.map((account) => account.embeddedWallets[0].address);\n if (glyphAddresses.length > 0) {\n address = glyphAddresses[0];\n logger.log(\"using cross_app (Glyph) account\");\n if (glyphAddresses.length > 1) {\n logger.warn(\"too many cross_app accounts\");\n }\n }\n\n if (address) {\n setUsesCrossapp(true);\n logger.log(\"using cross_app account\", address);\n } else if (hasPrivyEvmWallet) {\n address = privyEvmWallet.address;\n logger.log(\"using Privy (main) EVM embedded wallet\", address);\n }\n\n setWalletAddress(address ?? null);\n\n // Fetch user data from Glyph API\n const fetchUserData = async () => {\n // If no address is found, stop here\n if (!address) {\n logger.error(\"user has no wallet\");\n return;\n }\n\n const glyphApiFetch = createApiFetch(\n glyphUrl || WIDGET_API_BASE_URL,\n async () => (await getPrivyAccessToken())!,\n { \"x-evm-address\": address }\n );\n setApiFetch(() => glyphApiFetch);\n setLoading(false);\n };\n\n fetchUserData();\n }, [\n glyphUrl,\n privyAuthenticated,\n privyReady,\n privyUser,\n useStagingTenant,\n usesCrossapp,\n walletAddress,\n getPrivyAccessToken,\n privyLogout\n ]);\n\n const authenticate = useCallback(async () => {\n await privyLogin();\n onLogin?.();\n }, [onLogin, privyLogin]);\n\n const logout = useCallback(async () => {\n privyLogout();\n onLogout?.();\n }, [onLogout, privyLogout]);\n\n const signMessage = useCallback(\n async ({ message }: { message: string }) => {\n if (!walletAddress) throw new Error(\"No wallet address found\");\n\n return usesCrossapp\n ? crossAppSignMessage(message, { address: walletAddress })\n : (await privySignMessage({ message })).signature;\n },\n [walletAddress, usesCrossapp, crossAppSignMessage, privySignMessage]\n );\n\n const signTypedData = useCallback(\n async ({ data }: { data: SignTypedDataParams }) => {\n if (!walletAddress) throw new Error(\"No wallet address found\");\n return usesCrossapp\n ? crossAppSignTypedData(data, { address: walletAddress })\n : (await privySignTypedData(data)).signature;\n },\n [walletAddress, usesCrossapp, crossAppSignTypedData, privySignTypedData]\n );\n\n const sendTransaction = useCallback(\n async ({ transaction }: { transaction: UnsignedTransactionRequest }) => {\n if (!walletAddress) throw new Error(\"No wallet address found\");\n const tx = { ...transaction, chainId: transaction.chainId || chainId };\n\n return usesCrossapp\n ? crossAppSendTransaction(tx, { address: walletAddress })\n : (await privySendTransaction(tx, { address: walletAddress })).hash;\n },\n [chainId, usesCrossapp, walletAddress, crossAppSendTransaction, privySendTransaction]\n );\n\n return (\n <GlyphContext.Provider\n value={{\n ready: privyReady && !loading,\n authenticated: privyReady && privyAuthenticated,\n glyphUrl: glyphUrl as string, // Pass as string to avoid type error (we are passing fallback value in useGlyph hook at a common place)\n login: authenticate,\n logout,\n signMessage,\n signTypedData,\n sendTransaction,\n apiFetch: apiFetch!\n }}\n >\n {children}\n </GlyphContext.Provider>\n );\n};\n\nexport default memo(PrivyStrategy);\n"],"names":["logger","createLogger","PrivyStrategy","children","glyphUrl","onLogin","onLogout","useStagingTenant","loading","setLoading","useState","apiFetch","setApiFetch","walletAddress","setWalletAddress","usesCrossapp","setUsesCrossapp","chainId","useChainId","privyReady","privyAuthenticated","privyUser","getPrivyAccessToken","privyLogin","privyLogout","privySignMessage","privySignTypedData","privySendTransaction","usePrivy","crossAppSignMessage","crossAppSignTypedData","crossAppSendTransaction","useCrossAppAccounts","useEffect","address","privyEvmWallet","w","hasPrivyEvmWallet","isEthereumAddress","crossAppAccounts","account","otherAccounts","STAGING_GLYPH_PRIVY_APP_ID","GLYPH_PRIVY_APP_ID","otherAddresses","glyphAccounts","glyphAddresses","glyphApiFetch","createApiFetch","WIDGET_API_BASE_URL","authenticate","useCallback","logout","signMessage","message","signTypedData","data","sendTransaction","transaction","tx","jsx","GlyphContext","PrivyStrategy_default","memo"],"mappings":";;;;;AAcA,MAAMA,IAASC,EAAa,eAAe,GAErCC,KAAoD,CAAC;AAAA,EACvD,UAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AAAA,EACA,UAAAC;AAAA,EACA,kBAAAC;AACJ,MAAM;AACF,QAAM,CAACC,GAASC,CAAU,IAAIC,EAAkB,EAAI,GAC9C,CAACC,GAAUC,CAAW,IAAIF,EAA+B,IAAI,GAC7D,CAACG,GAAeC,CAAgB,IAAIJ,EAAwB,IAAI,GAChE,CAACK,GAAcC,CAAe,IAAIN,EAAkB,EAAK,GACzDO,IAAUC,EAAA,GAEV;AAAA,IACF,OAAOC;AAAA,IACP,eAAeC;AAAA,IACf,MAAMC;AAAA,IACN,gBAAgBC;AAAA,IAChB,OAAOC;AAAA,IACP,QAAQC;AAAA,IACR,aAAaC;AAAA,IACb,eAAeC;AAAA,IACf,iBAAiBC;AAAA,EAAA,IACjBC,EAAA,GAEE;AAAA,IACF,aAAaC;AAAA,IACb,eAAeC;AAAA,IACf,iBAAiBC;AAAA,EAAA,IACjBC,EAAA;AAEJ,EAAAhC,EAAO,MAAMmB,GAAYC,GAAoB,CAAC,CAACC,CAAS,GAExDY,EAAU,MAAM;AAEZ,QAAI,CAACd,GAAY;AACb,MAAAP,EAAY,IAAI,GAChBH,EAAW,EAAI;AACf;AAAA,IACJ;AAGA,QAAI,CAACW,KAAsB,CAACC,GAAW;AACnC,MAAAT,EAAY,IAAI,GAChBH,EAAW,EAAK;AAChB;AAAA,IACJ;AAEA,QAAIyB;AAEJ,UAAMC,IAAiBd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AAA,GAGrE+B,IAAkBN;AAAA,IACpB,OAAO,EAAE,aAAAO,EAAA,MAA+D;AACpE,UAAI,CAAC7C,EAAe,OAAM,IAAI,MAAM,yBAAyB;AAC7D,YAAM8C,IAAK,EAAE,GAAGD,GAAa,SAASA,EAAY,WAAWzC,EAAA;AAE7D,aAAOF,IACDgB,EAAwB4B,GAAI,EAAE,SAAS9C,EAAA,CAAe,KACrD,MAAMc,EAAqBgC,GAAI,EAAE,SAAS9C,EAAA,CAAe,GAAG;AAAA,IACvE;AAAA,IACA,CAACI,GAASF,GAAcF,GAAekB,GAAyBJ,CAAoB;AAAA,EAAA;AAGxF,SACI,gBAAAiC;AAAA,IAACC,EAAa;AAAA,IAAb;AAAA,MACG,OAAO;AAAA,QACH,OAAO1C,KAAc,CAACX;AAAA,QACtB,eAAeW,KAAcC;AAAA,QAC7B,UAAAhB;AAAA;AAAA,QACA,OAAO8C;AAAA,QACP,QAAAE;AAAA,QACA,aAAAC;AAAA,QACA,eAAAE;AAAA,QACA,iBAAAE;AAAA,QACA,UAAA9C;AAAA,MAAA;AAAA,MAGH,UAAAR;AAAA,IAAA;AAAA,EAAA;AAGb,GAEA2D,KAAeC,EAAK7D,EAAa;"}
1
+ {"version":3,"file":"PrivyStrategy.js","sources":["../src/context/strategies/PrivyStrategy.tsx"],"sourcesContent":["import {\n SignTypedDataParams,\n UnsignedTransactionRequest,\n useCrossAppAccounts,\n usePrivy,\n WalletWithMetadata\n} from \"@privy-io/react-auth\";\nimport react, { memo, useCallback, useEffect, useState } from \"react\";\nimport { useChainId } from \"wagmi\";\nimport { GLYPH_PRIVY_APP_ID, STAGING_GLYPH_PRIVY_APP_ID, WIDGET_API_BASE_URL } from \"../../lib/constants\";\nimport { createLogger, isEthereumAddress } from \"../../lib/utils\";\nimport { BaseGlyphProviderOptions } from \"../../types\";\nimport { createApiFetch, GlyphApiFetch, GlyphContext } from \"../GlyphContext\";\n\nconst logger = createLogger(\"PrivyStrategy\");\n\nconst PrivyStrategy: react.FC<BaseGlyphProviderOptions> = ({\n children,\n glyphUrl,\n onLogin,\n onLogout,\n useStagingTenant\n}) => {\n const [loading, setLoading] = useState<boolean>(true);\n const [apiFetch, setApiFetch] = useState<GlyphApiFetch | null>(null);\n const [walletAddress, setWalletAddress] = useState<string | null>(null);\n const [usesCrossapp, setUsesCrossapp] = useState<boolean>(false);\n const chainId = useChainId();\n\n const {\n ready: privyReady,\n authenticated: privyAuthenticated,\n user: privyUser,\n getAccessToken: getPrivyAccessToken,\n login: privyLogin,\n logout: privyLogout,\n signMessage: privySignMessage,\n signTypedData: privySignTypedData,\n sendTransaction: privySendTransaction\n } = usePrivy();\n\n const {\n signMessage: crossAppSignMessage,\n signTypedData: crossAppSignTypedData,\n sendTransaction: crossAppSendTransaction\n } = useCrossAppAccounts();\n\n\n useEffect(() => {\n // If Privy is not ready, reset widget state (loading: true)\n if (!privyReady) {\n setApiFetch(null);\n setLoading(true);\n return;\n }\n\n // If user is not authenticated, reset widget state (loading: false)\n if (!privyAuthenticated || !privyUser) {\n setApiFetch(null);\n setLoading(false);\n return;\n }\n\n let address: string | undefined;\n\n const privyEvmWallet = privyUser!.linkedAccounts?.find(\n (w) => w.type === \"wallet\" && w.chainType === \"ethereum\" && w.walletClientType === \"privy\"\n ) as WalletWithMetadata | undefined;\n\n const hasPrivyEvmWallet = privyEvmWallet && isEthereumAddress(privyEvmWallet.address);\n\n logger.debug(\"finding cross-app accounts...\");\n // Cross-app accounts are always EVM addresses\n const crossAppAccounts = privyUser!.linkedAccounts?.filter?.((account) => account.type === \"cross_app\") || [];\n\n const otherAccounts = crossAppAccounts.filter(\n (account) =>\n account.providerApp?.id !== (useStagingTenant ? STAGING_GLYPH_PRIVY_APP_ID : GLYPH_PRIVY_APP_ID)\n );\n const otherAddresses = otherAccounts.map((account) => account.embeddedWallets[0].address);\n if (otherAddresses.length > 0) {\n address = otherAddresses[0];\n logger.log(\"using cross_app (non-Glyph) account\");\n if (otherAddresses.length > 1) {\n logger.warn(\"too many cross_app accounts\");\n }\n }\n\n const glyphAccounts = crossAppAccounts.filter(\n (account) =>\n account.providerApp?.id === (useStagingTenant ? STAGING_GLYPH_PRIVY_APP_ID : GLYPH_PRIVY_APP_ID)\n );\n const glyphAddresses = glyphAccounts.map((account) => account.embeddedWallets[0].address);\n if (glyphAddresses.length > 0) {\n address = glyphAddresses[0];\n logger.log(\"using cross_app (Glyph) account\");\n if (glyphAddresses.length > 1) {\n logger.warn(\"too many cross_app accounts\");\n }\n }\n\n if (address) {\n setUsesCrossapp(true);\n logger.log(\"using cross_app account\");\n } else if (hasPrivyEvmWallet) {\n address = privyEvmWallet.address;\n logger.log(\"using Privy (main) EVM embedded wallet\");\n }\n\n setWalletAddress(address ?? null);\n\n // Fetch user data from Glyph API\n const fetchUserData = async () => {\n // If no address is found, stop here\n if (!address) {\n logger.error(\"user has no wallet\");\n return;\n }\n\n const glyphApiFetch = createApiFetch(\n glyphUrl || WIDGET_API_BASE_URL,\n async () => (await getPrivyAccessToken())!,\n { \"x-evm-address\": address }\n );\n setApiFetch(() => glyphApiFetch);\n setLoading(false);\n };\n\n fetchUserData();\n }, [\n glyphUrl,\n privyAuthenticated,\n privyReady,\n privyUser,\n useStagingTenant,\n usesCrossapp,\n walletAddress,\n getPrivyAccessToken,\n privyLogout\n ]);\n\n const authenticate = useCallback(async () => {\n await privyLogin();\n onLogin?.();\n }, [onLogin, privyLogin]);\n\n const logout = useCallback(async () => {\n privyLogout();\n onLogout?.();\n }, [onLogout, privyLogout]);\n\n const signMessage = useCallback(\n async ({ message }: { message: string }) => {\n if (!walletAddress) throw new Error(\"No wallet address found\");\n\n return usesCrossapp\n ? crossAppSignMessage(message, { address: walletAddress })\n : (await privySignMessage({ message })).signature;\n },\n [walletAddress, usesCrossapp, crossAppSignMessage, privySignMessage]\n );\n\n const signTypedData = useCallback(\n async ({ data }: { data: SignTypedDataParams }) => {\n if (!walletAddress) throw new Error(\"No wallet address found\");\n return usesCrossapp\n ? crossAppSignTypedData(data, { address: walletAddress })\n : (await privySignTypedData(data)).signature;\n },\n [walletAddress, usesCrossapp, crossAppSignTypedData, privySignTypedData]\n );\n\n const sendTransaction = useCallback(\n async ({ transaction }: { transaction: UnsignedTransactionRequest }) => {\n if (!walletAddress) throw new Error(\"No wallet address found\");\n const tx = { ...transaction, chainId: transaction.chainId || chainId };\n\n return usesCrossapp\n ? crossAppSendTransaction(tx, { address: walletAddress })\n : (await privySendTransaction(tx, { address: walletAddress })).hash;\n },\n [chainId, usesCrossapp, walletAddress, crossAppSendTransaction, privySendTransaction]\n );\n\n return (\n <GlyphContext.Provider\n value={{\n ready: privyReady && !loading,\n authenticated: privyReady && privyAuthenticated,\n glyphUrl: glyphUrl as string, // Pass as string to avoid type error (we are passing fallback value in useGlyph hook at a common place)\n login: authenticate,\n logout,\n signMessage,\n signTypedData,\n sendTransaction,\n apiFetch: apiFetch!\n }}\n >\n {children}\n </GlyphContext.Provider>\n );\n};\n\nexport default memo(PrivyStrategy);\n"],"names":["logger","createLogger","PrivyStrategy","children","glyphUrl","onLogin","onLogout","useStagingTenant","loading","setLoading","useState","apiFetch","setApiFetch","walletAddress","setWalletAddress","usesCrossapp","setUsesCrossapp","chainId","useChainId","privyReady","privyAuthenticated","privyUser","getPrivyAccessToken","privyLogin","privyLogout","privySignMessage","privySignTypedData","privySendTransaction","usePrivy","crossAppSignMessage","crossAppSignTypedData","crossAppSendTransaction","useCrossAppAccounts","useEffect","address","privyEvmWallet","w","hasPrivyEvmWallet","isEthereumAddress","crossAppAccounts","account","otherAddresses","STAGING_GLYPH_PRIVY_APP_ID","GLYPH_PRIVY_APP_ID","glyphAddresses","glyphApiFetch","createApiFetch","WIDGET_API_BASE_URL","authenticate","useCallback","logout","signMessage","message","signTypedData","data","sendTransaction","transaction","tx","jsx","GlyphContext","PrivyStrategy_default","memo"],"mappings":";;;;;AAcA,MAAMA,IAASC,EAAa,eAAe,GAErCC,KAAoD,CAAC;AAAA,EACvD,UAAAC;AAAA,EACA,UAA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E;AAAA,QACA,UAAA5C;AAAA,MAAA;AAAA,MAGH,UAAAR;AAAA,IAAA;AAAA,EAAA;AAGb,GAEAyD,KAAeC,EAAK3D,EAAa;"}
@@ -1,4 +1,4 @@
1
- import { C as e, D as l, o as t, F as n, E as i, G as o, H as y, d as G, t as p, z as h, e as P, J as r, L as _, f as u, N as g, I as C, S as I, g as c, v as A, h as L, w as N, j as T, s as v, y as H, A as D, B as Y, n as B, k as O, l as W, u as d, m as S, q as R, p as E, r as f, x as m, K as w } from "./index.js";
1
+ import { C as e, D as l, o as t, H as n, F as i, G as o, I as y, d as G, v as p, A as h, e as P, K as r, L as _, f as g, N as u, J as C, S as I, g as c, w as L, h as A, x as N, j as T, t as v, z as D, B as H, E as Y, s as B, n as O, k as W, l as d, u as S, m as R, q as E, p as f, r as m, y as w, M as F } from "./index.js";
2
2
  export {
3
3
  e as ChainSelector,
4
4
  l as DB_OFFCHAIN_TX_TYPE,
@@ -13,28 +13,29 @@ export {
13
13
  P as GlyphWidget,
14
14
  r as InjectWagmiConnector,
15
15
  _ as LoginButton,
16
- u as LogoutButton,
17
- g as NativeGlyphConnectButton,
16
+ g as LogoutButton,
17
+ u as NativeGlyphConnectButton,
18
18
  C as STAGING_GLYPH_APP_LOGIN_METHOD,
19
19
  I as STAGING_GLYPH_PRIVY_APP_ID,
20
20
  c as SignUpButton,
21
- A as StrategyType,
22
- L as Wallet,
21
+ L as StrategyType,
22
+ A as Wallet,
23
23
  N as WalletClientType,
24
24
  T as configureRelayChains,
25
25
  v as glyphConnectorDetails,
26
- H as glyphWalletConnector,
27
- D as glyphWalletRK,
26
+ D as glyphWalletConnector,
27
+ H as glyphWalletRK,
28
28
  Y as glyphWalletRKStaging,
29
- B as useActivity,
30
- O as useBalances,
31
- W as useGlyph,
32
- d as useGlyphConfigureDynamicChains,
33
- S as useGlyphFunding,
34
- R as useGlyphOwnershipCheck,
35
- E as useGlyphTokenGate,
36
- f as useGlyphView,
37
- m as useNativeGlyphConnection,
38
- w as usePrivyCrossAppProvider
29
+ B as setGlyphDebugLogging,
30
+ O as useActivity,
31
+ W as useBalances,
32
+ d as useGlyph,
33
+ S as useGlyphConfigureDynamicChains,
34
+ R as useGlyphFunding,
35
+ E as useGlyphOwnershipCheck,
36
+ f as useGlyphTokenGate,
37
+ m as useGlyphView,
38
+ w as useNativeGlyphConnection,
39
+ F as usePrivyCrossAppProvider
39
40
  };
40
41
  //# sourceMappingURL=glyph-widget.es.js.map