/
App.tsx
345 lines (313 loc) · 9.48 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { useEffect, useState } from "react";
// Import Single Factor Auth SDK for no redirect flow
import { Web3Auth } from "@web3auth/single-factor-auth";
import { CHAIN_NAMESPACES } from "@web3auth/base";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { GoogleLogin, CredentialResponse, googleLogout } from "@react-oauth/google";
// RPC libraries for blockchain calls
import RPC from "./evm.web3";
// import RPC from "./evm.ethers";
// import RPC from "./evm.viem";
import { useAuth0 } from "@auth0/auth0-react";
import "./App.css";
import Loading from "./Loading";
const verifier = "w3a-agg-google-auth0";
const clientId = "BEglQSgt4cUWcj6SKRdu5QkOXTsePmMcusG5EAoyjyOYKlVRjIF1iCNnMOTfpzCiunHRrMui8TIwQPXdkQ8Yxuk"; // get from https://dashboard.web3auth.io
const chainConfig = {
chainId: "0x1",
displayName: "Ethereum Mainnet",
chainNamespace: CHAIN_NAMESPACES.EIP155,
tickerName: "Ethereum",
ticker: "ETH",
decimals: 18,
rpcTarget: "https://rpc.ankr.com/eth",
blockExplorerUrl: "https://etherscan.io",
};
// Initialising Web3Auth Single Factor Auth SDK
const web3authSfa = new Web3Auth({
clientId, // Get your Client ID from Web3Auth Dashboard
web3AuthNetwork: "testnet", // ["cyan", "testnet"]
usePnPKey: false, // Setting this to true returns the same key as PnP Web SDK, By default, this SDK returns CoreKitKey.
});
const ethereumPrivateKeyProvider = new EthereumPrivateKeyProvider({
config: { chainConfig },
});
function App() {
const [usesSfaSDK, setUsesSfaSDK] = useState(false);
const [idToken, setIdToken] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const { getIdTokenClaims, loginWithPopup } = useAuth0();
useEffect(() => {
const init = async () => {
try {
web3authSfa.init(ethereumPrivateKeyProvider);
} catch (error) {
console.error(error);
}
};
init();
}, []);
const parseToken = (token: any) => {
try {
const base64Url = token.split(".")[1];
const base64 = base64Url.replace("-", "+").replace("_", "/");
return JSON.parse(window.atob(base64 || ""));
} catch (err) {
console.error(err);
return null;
}
};
const loginAuth0GitHub = async () => {
// trying logging in with the Single Factor Auth SDK
try {
if (!web3authSfa) {
uiConsole("Web3Auth Single Factor Auth SDK not initialized yet");
return;
}
setLoading(true);
await loginWithPopup();
const idToken = (await getIdTokenClaims())?.__raw.toString();
setIdToken(idToken!);
console.log("idToken", parseToken(idToken));
const { email } = parseToken(idToken);
const subVerifierInfoArray = [
{
verifier: "w3a-auth0-github",
idToken: idToken!,
},
];
await web3authSfa.connect({
verifier,
verifierId: email,
idToken: idToken!,
subVerifierInfoArray,
});
setUsesSfaSDK(true);
setLoading(false);
setIsLoggedIn(true);
} catch (err) {
// Single Factor Auth SDK throws an error if the user has already enabled MFA
// One can use the Web3AuthNoModal SDK to handle this case
setLoading(false);
console.error(err);
}
};
const onSuccess = async (response: CredentialResponse) => {
try {
if (!web3authSfa) {
uiConsole("Web3Auth Single Factor Auth SDK not initialized yet");
return;
}
setLoading(true);
const idToken = response.credential;
setIdToken(idToken!);
const { email } = parseToken(idToken);
console.log(email);
const subVerifierInfoArray = [
{
verifier: "w3a-google",
idToken: idToken!,
},
];
await web3authSfa.connect({
verifier,
verifierId: email,
idToken: idToken!,
subVerifierInfoArray,
});
setUsesSfaSDK(true);
setLoading(false);
setIsLoggedIn(true);
} catch (err) {
// Single Factor Auth SDK throws an error if the user has already enabled MFA
// One can use the Web3AuthNoModal SDK to handle this case
setLoading(false);
console.error(err);
}
};
const getUserInfo = async () => {
if (usesSfaSDK) {
uiConsole(
"You are directly using Single Factor Auth SDK to login the user, hence the Web3Auth <code>getUserInfo</code> function won't work for you. Get the user details directly from id token.",
parseToken(idToken)
);
return;
}
};
const logout = async () => {
if (usesSfaSDK) {
console.log(
"You are directly using Single Factor Auth SDK to login the user, hence the Web3Auth logout function won't work for you. You can logout the user directly from your login provider, or just clear the provider object."
);
web3authSfa?.logout();
googleLogout();
setIsLoggedIn(false);
return;
}
};
const getAccounts = async () => {
if (!web3authSfa.provider) {
uiConsole("No provider found");
return;
}
const rpc = new RPC(web3authSfa.provider);
const userAccount = await rpc.getAccounts();
uiConsole(userAccount);
};
const getBalance = async () => {
if (!web3authSfa.provider) {
uiConsole("No provider found");
return;
}
const rpc = new RPC(web3authSfa.provider);
const balance = await rpc.getBalance();
uiConsole(balance);
};
const signMessage = async () => {
if (!web3authSfa.provider) {
uiConsole("No provider found");
return;
}
const rpc = new RPC(web3authSfa.provider);
const result = await rpc.signMessage();
uiConsole(result);
};
const sendTransaction = async () => {
if (!web3authSfa.provider) {
uiConsole("No provider found");
return;
}
const rpc = new RPC(web3authSfa.provider);
const result = await rpc.signAndSendTransaction();
uiConsole(result);
};
function uiConsole(...args: any[]): void {
const el = document.querySelector("#console>p");
if (el) {
el.innerHTML = JSON.stringify(args || {}, null, 2);
}
}
const authenticateUser = async () => {
try {
const userCredential = await web3authSfa.authenticateUser();
uiConsole(userCredential);
} catch (err) {
uiConsole(err);
}
};
const addChain = async () => {
try {
const newChain = {
chainId: "0xaa36a7",
displayName: "Sepolia Testnet ETH",
chainNamespace: CHAIN_NAMESPACES.EIP155,
tickerName: "Sepolia Testnet ETH",
ticker: "ETH",
decimals: 18,
rpcTarget: "https://rpc.ankr.com/eth_sepolia",
blockExplorerUrl: "https://sepolia.etherscan.io",
};
await web3authSfa.addChain(newChain);
uiConsole("Chain added successfully");
} catch (err) {
uiConsole(err);
}
};
const switchChain = async () => {
try {
await web3authSfa.switchChain({ chainId: "0xaa36a7" }); // sepolia chain id
uiConsole("Chain switched successfully");
} catch (err) {
uiConsole(err);
}
};
const loginView = (
<>
<div className="flex-container">
<div>
<button onClick={getUserInfo} className="card">
Get User Info
</button>
</div>
<div>
<button onClick={() => uiConsole(parseToken(idToken))} className="card">
Get OAuth ID Token
</button>
</div>
<div>
<button onClick={authenticateUser} className="card">
Authenticate User
</button>
</div>
<div>
<button onClick={getAccounts} className="card">
Get Accounts
</button>
</div>
<div>
<button onClick={addChain} className="card">
Add Chain
</button>
</div>
<div>
<button onClick={switchChain} className="card">
Switch Chain
</button>
</div>
<div>
<button onClick={getBalance} className="card">
Get Balance
</button>
</div>
<div>
<button onClick={signMessage} className="card">
Sign Message
</button>
</div>
<div>
<button onClick={sendTransaction} className="card">
Send Transaction
</button>
</div>
<div>
<button onClick={logout} className="card">
Log Out
</button>
</div>
</div>
<div id="console" style={{ whiteSpace: "pre-line" }}>
<p style={{ whiteSpace: "pre-line" }}></p>
</div>
</>
);
const logoutView = (
<>
<button onClick={loginAuth0GitHub} className="card">
Login using <b>Github</b> [ via Auth0 ]
</button>
<GoogleLogin onSuccess={onSuccess} />
</>
);
return (
<div className="container">
<h1 className="title">
<a target="_blank" href="https://web3auth.io/docs/sdk/core-kit/sfa-web" rel="noreferrer">
Web3Auth
</a>{" "}
SFA React Auth0 GitHub Example
</h1>
{loading ? <Loading /> : <div className="grid">{isLoggedIn ? loginView : logoutView}</div>}
<footer className="footer">
<a
href="https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/single-factor-auth-web/sfa-react-agg-verifier-example "
target="_blank"
rel="noopener noreferrer"
>
Source code
</a>
</footer>
</div>
);
}
export default App;