-
Notifications
You must be signed in to change notification settings - Fork 3
/
App.tsx
538 lines (464 loc) · 15.1 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import "./cryptoSetup";
import { useEffect, useRef, useState } from "react";
import {
ActivityIndicator,
Button,
Platform,
ScrollView,
StatusBar,
Text,
TouchableOpacity,
View,
Image,
} from "react-native";
import {
AuthRequest,
exchangeCodeAsync,
AccessTokenRequestConfig,
} from "expo-auth-session";
import { EmailConflictInfo, networks } from "@0xsequence/waas";
import * as WebBrowser from "expo-web-browser";
import appleAuth, {
AppleButton,
appleAuthAndroid,
} from "@invertase/react-native-apple-authentication";
import {
sequenceWaas,
initialNetwork,
iosGoogleRedirectUri,
iosGoogleClientId,
webGoogleClientId,
} from "./waasSetup";
import CopyButton from "./components/CopyButton";
import EmailAuthView from "./components/EmailAuthView";
import { randomName } from "./utils/string";
import styles from "./styles";
import EmailConflictWarningView from "./components/EmailConflictWarningView";
const messageToSign = "Hello world";
export default function App() {
const [walletAddress, setWalletAddress] = useState<string | null>(null);
const [network, setNetwork] = useState<string>(initialNetwork);
const [isEmailAuthInProgress, setIsEmailAuthInProgress] = useState(false);
const [isSignMessageInProgress, setIsSignMessageInProgress] = useState(false);
const [sig, setSig] = useState<string | undefined>();
const [isSendTxnInProgress, setIsSendTxnInProgress] = useState(false);
const [txnHash, setTxnHash] = useState<string | undefined>();
useEffect(() => {
isSignedIn(setWalletAddress);
}, []);
const [emailConflictInfo, setEmailConflictInfo] = useState<
EmailConflictInfo | undefined
>();
const [isEmailConflictModalOpen, setIsEmailConflictModalOpen] =
useState(false);
const forceCreateFuncRef = useRef<(() => Promise<void>) | null>(null);
sequenceWaas.onEmailConflict(async (info, forceCreate) => {
forceCreateFuncRef.current = forceCreate;
setEmailConflictInfo(info);
setIsEmailConflictModalOpen(true);
});
const signMessage = async () => {
setIsSignMessageInProgress(true);
const sig = await sequenceWaas.signMessage({ message: messageToSign });
setIsSignMessageInProgress(false);
setSig(sig.data.signature);
};
const sendTxn = async () => {
setIsSendTxnInProgress(true);
const txn = await sequenceWaas.sendTransaction({
transactions: [
{
to: walletAddress,
value: 0,
},
],
});
setIsSendTxnInProgress(false);
if ("txHash" in txn.data) {
setTxnHash(txn.data.txHash);
}
};
return (
<View style={styles.container}>
<StatusBar
barStyle={Platform.OS === "ios" ? "light-content" : "dark-content"}
/>
{isEmailAuthInProgress && (
<EmailAuthView
onCancel={() => setIsEmailAuthInProgress(false)}
onSuccess={(walletAddress) => {
setIsEmailAuthInProgress(false);
setWalletAddress(walletAddress);
}}
/>
)}
{isEmailConflictModalOpen && (
<EmailConflictWarningView
info={emailConflictInfo}
onCancel={() => {
setIsEmailAuthInProgress(false);
setIsEmailConflictModalOpen(false);
setEmailConflictInfo(undefined);
forceCreateFuncRef.current = null;
}}
onConfirm={() => {
setIsEmailConflictModalOpen(false);
setEmailConflictInfo(undefined);
forceCreateFuncRef.current?.();
}}
/>
)}
{walletAddress && (
<ScrollView style={{ paddingVertical: 60, width: "100%" }}>
<View style={{ paddingBottom: 150 }}>
<View style={styles.demoItemContainer}>
<Text style={styles.demoItemTitle}>Wallet address</Text>
<Text style={styles.demoItemText}>{walletAddress}</Text>
<CopyButton stringToCopy={walletAddress} />
</View>
<View style={styles.demoItemContainer}>
<Text style={styles.demoItemTitle}>Network</Text>
<Text style={styles.demoItemText}>
{networks.nameOfNetwork(network)}
</Text>
</View>
<TouchableOpacity activeOpacity={0.8} onPress={signMessage}>
<View style={styles.demoItemContainer}>
<Text style={styles.demoItemTitle}>Sign a message</Text>
<Text style={styles.demoItemTextSecondary}>
Sign a message with your wallet.
</Text>
<Text style={styles.demoItemTextSecondary}>
Message to sign: "{messageToSign}"
</Text>
{isSignMessageInProgress && (
<View style={{ paddingVertical: 5, width: 20 }}>
<ActivityIndicator size="small" color="#fff" />
</View>
)}
</View>
</TouchableOpacity>
{sig && (
<View style={styles.demoItemContainer}>
<Text style={styles.demoItemTitleSecondary}>
Signature for "{messageToSign}":
</Text>
<ScrollView style={{ height: 140 }} nestedScrollEnabled={true}>
<Text style={styles.demoItemText}>{sig}</Text>
</ScrollView>
<CopyButton stringToCopy={sig} />
</View>
)}
<TouchableOpacity activeOpacity={0.8} onPress={sendTxn}>
<View style={styles.demoItemContainer}>
<Text style={styles.demoItemTitle}>Send a transaction</Text>
<Text style={styles.demoItemTextSecondary}>
Send a transaction with your wallet.
</Text>
{isSendTxnInProgress && (
<View style={{ paddingVertical: 5, width: 20 }}>
<ActivityIndicator size="small" color="#fff" />
</View>
)}
</View>
</TouchableOpacity>
{txnHash && (
<View style={styles.demoItemContainer}>
<Text style={styles.demoItemTitleSecondary}>
Transaction hash:
</Text>
<Text style={styles.demoItemText}>{txnHash}</Text>
<TouchableOpacity
activeOpacity={0.8}
onPress={() => {
WebBrowser.openBrowserAsync(
`https://sepolia.arbiscan.io/tx/${txnHash}`
);
}}
>
<View
style={{
alignSelf: "baseline",
backgroundColor: "#000",
padding: 4,
borderRadius: 6,
marginTop: 6,
}}
>
<Text style={styles.demoItemTextSecondary}>
View on Arbiscan
</Text>
</View>
</TouchableOpacity>
</View>
)}
<Button
title="Sign out"
onPress={async () => {
setSig(undefined);
setTxnHash(undefined);
setWalletAddress(null);
await sequenceWaas.dropSession();
}}
/>
</View>
</ScrollView>
)}
{!walletAddress && (
<>
<View
style={{
width: 150,
height: 150,
alignItems: "center",
justifyContent: "center",
}}
>
<Image
style={{
width: 300,
resizeMode: "contain",
}}
source={require("./assets/sequence-icon.png")}
/>
</View>
<View style={{ marginBottom: 50 }}>
<Text style={{ fontSize: 30, fontWeight: "bold", color: "white" }}>
Sequence WaaS Demo
</Text>
</View>
<View style={{ alignItems: "center", justifyContent: "center" }}>
<Button
title="Sign in as guest"
onPress={async () => {
const signInResult = await sequenceWaas.signIn(
{ guest: true },
randomName()
);
if (signInResult.wallet) {
setWalletAddress(signInResult.wallet);
} else {
console.error("No wallet address after guest sign in");
}
}}
/>
<View style={{ marginTop: 10 }} />
<Button
title="Sign in with Email"
onPress={() => {
setIsEmailAuthInProgress(true);
}}
/>
<View style={{ marginTop: 10 }} />
<Button
title="Sign in with Google"
onPress={async () => {
const result = await signInWithGoogle();
if (result.walletAddress) {
setWalletAddress(result.walletAddress);
}
}}
/>
<View style={{ marginTop: 10 }} />
<AppleButton
buttonStyle={AppleButton.Style.WHITE}
buttonType={AppleButton.Type.SIGN_IN}
style={{
width: 160, // You must specify a width
height: 45, // You must specify a height
}}
onPress={async () => {
if (Platform.OS === "ios") {
const result = await signInWithAppleIOS();
if (result.walletAddress) {
setWalletAddress(result.walletAddress);
}
}
if (Platform.OS === "android") {
const result = await signInWithAppleAndroid();
if (result.walletAddress) {
setWalletAddress(result.walletAddress);
}
}
}}
/>
</View>
</>
)}
</View>
);
}
// Helpers
const isSignedIn = async (
setWalletAddress: React.Dispatch<React.SetStateAction<string>>
) => {
const isSignedIn = await sequenceWaas.isSignedIn();
if (isSignedIn) {
sequenceWaas.getAddress().then((address) => {
setWalletAddress(address);
});
}
};
type GoogleUser = {
user: {
id: string;
name: string | null;
givenName: string | null;
familyName: string | null;
photo: string | null;
};
idToken: string;
};
const signInWithGoogle = async () => {
const redirectUri = `${iosGoogleRedirectUri}:/oauthredirect`;
const scopes = ["openid", "profile", "email"];
const request = new AuthRequest({
clientId: iosGoogleClientId,
scopes,
redirectUri,
usePKCE: true,
extraParams: {
audience: webGoogleClientId,
include_granted_scopes: "true",
},
});
const result = await request.promptAsync({
authorizationEndpoint: `https://accounts.google.com/o/oauth2/v2/auth`,
});
if (result.type === "cancel") {
return undefined;
}
if (result.type !== "success") {
throw new Error("Authentication failed");
}
const serverAuthCode = result.params?.code;
const configForTokenExchange: AccessTokenRequestConfig = {
code: serverAuthCode,
redirectUri,
clientId: iosGoogleClientId,
extraParams: {
code_verifier: request?.codeVerifier || "",
audience: webGoogleClientId,
},
};
const tokenResponse = await exchangeCodeAsync(configForTokenExchange, {
tokenEndpoint: "https://oauth2.googleapis.com/token",
});
const userInfo = await fetchGoogleUserInfo(tokenResponse.accessToken);
const idToken = tokenResponse.idToken;
if (!idToken) {
throw new Error("No idToken");
}
const waasSession = await authenticateWithWaas(idToken);
if (!waasSession) {
throw new Error("No WaaS session");
}
return {
userInfo: {
user: userInfo,
idToken,
},
walletAddress: waasSession.wallet,
};
};
const signInWithAppleIOS = async () => {
// performs login request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
// Note: it appears putting FULL_NAME first is important, see issue #293
requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
});
// get current authentication state for user
// /!\ This method must be tested on a real device. On the iOS simulator it always throws an error.
const credentialState = await appleAuth.getCredentialStateForUser(
appleAuthRequestResponse.user
);
// use credentialState response to ensure the user is authenticated
if (credentialState === appleAuth.State.AUTHORIZED) {
// user is authenticated
const idToken = appleAuthRequestResponse.identityToken;
if (!idToken) {
throw new Error("No idToken");
}
const waasSession = await authenticateWithWaas(idToken);
if (!waasSession) {
throw new Error("No WaaS session");
}
return {
userInfo: {
user: appleAuthRequestResponse.user,
idToken,
},
walletAddress: waasSession.wallet,
};
}
};
const signInWithAppleAndroid = async () => {
// Configure the request
appleAuthAndroid.configure({
// The Service ID you registered with Apple
clientId: "com.horizon.waas-demo",
// Return URL added to your Apple dev console. We intercept this redirect, but it must still match
// the URL you provided to Apple. It can be an empty route on your backend as it's never called.
redirectUri: "https://waas-demo.sequence.app/callback",
// The type of response requested - code, id_token, or both.
responseType: appleAuthAndroid.ResponseType.ALL,
// The amount of user information requested from Apple.
scope: appleAuthAndroid.Scope.ALL,
});
// Open the browser window for user sign in
const response = await appleAuthAndroid.signIn();
const idToken = response.id_token;
if (!idToken) {
throw new Error("No idToken");
}
const waasSession = await authenticateWithWaas(idToken);
if (!waasSession) {
throw new Error("No WaaS session");
}
return {
userInfo: {
idToken,
},
walletAddress: waasSession.wallet,
};
};
const authenticateWithWaas = async (
idToken: string
): Promise<{ sessionId: string; wallet: string } | null> => {
try {
const signInResult = await sequenceWaas.signIn(
{
idToken,
},
randomName()
);
return signInResult;
} catch (e) {
console.log("error in authenticateWithWaas", JSON.stringify(e));
}
return null;
};
const fetchGoogleUserInfo = async (
accessToken: string
): Promise<GoogleUser["user"]> => {
const response = await fetch(
"https://www.googleapis.com/oauth2/v3/userinfo",
{
method: "GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
const json: any = await response.json();
return {
id: json.sub,
name: json.name,
givenName: json.given_name,
familyName: json.family_name,
photo: json.picture,
};
};