-
Notifications
You must be signed in to change notification settings - Fork 27
/
App.tsx
365 lines (308 loc) · 11.6 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
import "react-native-get-random-values";
import "react-native-url-polyfill/auto";
import { clusterApiUrl, Connection, PublicKey, SystemProgram, Transaction } from "@solana/web3.js";
import bs58 from "bs58";
import { Buffer } from "buffer";
import * as Linking from "expo-linking";
import { StatusBar } from "expo-status-bar";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Button, Platform, ScrollView, Text, View } from "react-native";
import nacl from "tweetnacl";
global.Buffer = global.Buffer || Buffer;
const NETWORK = clusterApiUrl("mainnet-beta");
const onConnectRedirectLink = Linking.createURL("onConnect");
const onDisconnectRedirectLink = Linking.createURL("onDisconnect");
const onSignAndSendTransactionRedirectLink = Linking.createURL("onSignAndSendTransaction");
const onSignAllTransactionsRedirectLink = Linking.createURL("onSignAllTransactions");
const onSignTransactionRedirectLink = Linking.createURL("onSignTransaction");
const onSignMessageRedirectLink = Linking.createURL("onSignMessage");
/**
* If true, uses universal links instead of deep links. This is the recommended way for dapps
* and Phantom to handle deeplinks as we own the phantom.app domain.
*
* Set this to false to use normal deeplinks, starting with phantom://. This is easier for
* debugging with a local build such as Expo Dev Client builds.
*/
const useUniversalLinks = false;
const buildUrl = (path: string, params: URLSearchParams) =>
`${useUniversalLinks ? "https://phantom.app/ul/" : "phantom://"}v1/${path}?${params.toString()}`;
const decryptPayload = (data: string, nonce: string, sharedSecret?: Uint8Array) => {
if (!sharedSecret) throw new Error("missing shared secret");
const decryptedData = nacl.box.open.after(bs58.decode(data), bs58.decode(nonce), sharedSecret);
if (!decryptedData) {
throw new Error("Unable to decrypt data");
}
return JSON.parse(Buffer.from(decryptedData).toString("utf8"));
};
const encryptPayload = (payload: any, sharedSecret?: Uint8Array) => {
if (!sharedSecret) throw new Error("missing shared secret");
const nonce = nacl.randomBytes(24);
const encryptedPayload = nacl.box.after(
Buffer.from(JSON.stringify(payload)),
nonce,
sharedSecret
);
return [nonce, encryptedPayload];
};
export default function App() {
const [deepLink, setDeepLink] = useState<string>("");
const [logs, setLogs] = useState<string[]>([]);
const connection = new Connection(NETWORK);
const addLog = useCallback((log: string) => setLogs((logs) => [...logs, "> " + log]), []);
const clearLog = useCallback(() => setLogs(() => []), []);
const scrollViewRef = useRef<any>(null);
// store dappKeyPair, sharedSecret, session and account SECURELY on device
// to avoid having to reconnect users.
const [dappKeyPair] = useState(nacl.box.keyPair());
const [sharedSecret, setSharedSecret] = useState<Uint8Array>();
const [session, setSession] = useState<string>();
const [phantomWalletPublicKey, setPhantomWalletPublicKey] = useState<PublicKey>();
useEffect(() => {
(async () => {
const initialUrl = await Linking.getInitialURL();
if (initialUrl) {
setDeepLink(initialUrl);
}
})();
const subscription = Linking.addEventListener("url", handleDeepLink);
return () => {
subscription.remove();
};
}, []);
const handleDeepLink = ({ url }: Linking.EventType) => {
setDeepLink(url);
};
// handle inbounds links
useEffect(() => {
if (!deepLink) return;
const url = new URL(deepLink);
const params = url.searchParams;
if (params.get("errorCode")) {
addLog(JSON.stringify(Object.fromEntries([...params]), null, 2));
return;
}
if (/onConnect/.test(url.pathname || url.host)) {
const sharedSecretDapp = nacl.box.before(
bs58.decode(params.get("phantom_encryption_public_key")!),
dappKeyPair.secretKey
);
const connectData = decryptPayload(
params.get("data")!,
params.get("nonce")!,
sharedSecretDapp
);
setSharedSecret(sharedSecretDapp);
setSession(connectData.session);
setPhantomWalletPublicKey(new PublicKey(connectData.public_key));
addLog(JSON.stringify(connectData, null, 2));
} else if (/onDisconnect/.test(url.pathname || url.host)) {
addLog("Disconnected!");
} else if (/onSignAndSendTransaction/.test(url.pathname || url.host)) {
const signAndSendTransactionData = decryptPayload(
params.get("data")!,
params.get("nonce")!,
sharedSecret
);
addLog(JSON.stringify(signAndSendTransactionData, null, 2));
} else if (/onSignAllTransactions/.test(url.pathname || url.host)) {
const signAllTransactionsData = decryptPayload(
params.get("data")!,
params.get("nonce")!,
sharedSecret
);
const decodedTransactions = signAllTransactionsData.transactions.map((t: string) =>
Transaction.from(bs58.decode(t))
);
addLog(JSON.stringify(decodedTransactions, null, 2));
} else if (/onSignTransaction/.test(url.pathname || url.host)) {
const signTransactionData = decryptPayload(
params.get("data")!,
params.get("nonce")!,
sharedSecret
);
const decodedTransaction = Transaction.from(bs58.decode(signTransactionData.transaction));
addLog(JSON.stringify(decodedTransaction, null, 2));
} else if (/onSignMessage/.test(url.pathname || url.host)) {
const signMessageData = decryptPayload(
params.get("data")!,
params.get("nonce")!,
sharedSecret
);
addLog(JSON.stringify(signMessageData, null, 2));
}
}, [deepLink]);
const createTransferTransaction = async () => {
if (!phantomWalletPublicKey) throw new Error("missing public key from user");
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: phantomWalletPublicKey,
toPubkey: phantomWalletPublicKey,
lamports: 100
})
);
transaction.feePayer = phantomWalletPublicKey;
addLog("Getting recent blockhash");
const anyTransaction: any = transaction;
anyTransaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
return transaction;
};
const connect = async () => {
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappKeyPair.publicKey),
cluster: "mainnet-beta",
app_url: "https://phantom.app",
redirect_link: onConnectRedirectLink
});
const url = buildUrl("connect", params);
Linking.openURL(url);
};
const disconnect = async () => {
const payload = {
session
};
const [nonce, encryptedPayload] = encryptPayload(payload, sharedSecret);
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappKeyPair.publicKey),
nonce: bs58.encode(nonce),
redirect_link: onDisconnectRedirectLink,
payload: bs58.encode(encryptedPayload)
});
const url = buildUrl("disconnect", params);
Linking.openURL(url);
};
const signAndSendTransaction = async () => {
const transaction = await createTransferTransaction();
const serializedTransaction = transaction.serialize({
requireAllSignatures: false
});
const payload = {
session,
transaction: bs58.encode(serializedTransaction)
};
const [nonce, encryptedPayload] = encryptPayload(payload, sharedSecret);
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappKeyPair.publicKey),
nonce: bs58.encode(nonce),
redirect_link: onSignAndSendTransactionRedirectLink,
payload: bs58.encode(encryptedPayload)
});
addLog("Sending transaction...");
const url = buildUrl("signAndSendTransaction", params);
Linking.openURL(url);
};
const signAllTransactions = async () => {
const transactions = await Promise.all([
createTransferTransaction(),
createTransferTransaction()
]);
const serializedTransactions = transactions.map((t) =>
bs58.encode(
t.serialize({
requireAllSignatures: false
})
)
);
const payload = {
session,
transactions: serializedTransactions
};
const [nonce, encryptedPayload] = encryptPayload(payload, sharedSecret);
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappKeyPair.publicKey),
nonce: bs58.encode(nonce),
redirect_link: onSignAllTransactionsRedirectLink,
payload: bs58.encode(encryptedPayload)
});
addLog("Signing transactions...");
const url = buildUrl("signAllTransactions", params);
Linking.openURL(url);
};
const signTransaction = async () => {
const transaction = await createTransferTransaction();
const serializedTransaction = bs58.encode(
transaction.serialize({
requireAllSignatures: false
})
);
const payload = {
session,
transaction: serializedTransaction
};
const [nonce, encryptedPayload] = encryptPayload(payload, sharedSecret);
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappKeyPair.publicKey),
nonce: bs58.encode(nonce),
redirect_link: onSignTransactionRedirectLink,
payload: bs58.encode(encryptedPayload)
});
addLog("Signing transaction...");
const url = buildUrl("signTransaction", params);
Linking.openURL(url);
};
const signMessage = async () => {
const message = "To avoid digital dognappers, sign below to authenticate with CryptoCorgis.";
const payload = {
session,
message: bs58.encode(Buffer.from(message))
};
const [nonce, encryptedPayload] = encryptPayload(payload, sharedSecret);
const params = new URLSearchParams({
dapp_encryption_public_key: bs58.encode(dappKeyPair.publicKey),
nonce: bs58.encode(nonce),
redirect_link: onSignMessageRedirectLink,
payload: bs58.encode(encryptedPayload)
});
addLog("Signing message...");
const url = buildUrl("signMessage", params);
Linking.openURL(url);
};
return (
<View style={{ flex: 1, backgroundColor: "#333" }}>
<StatusBar style="light" />
<View style={{ flex: 1 }}>
<ScrollView
contentContainerStyle={{
backgroundColor: "#111",
padding: 20,
paddingTop: 100,
flexGrow: 1
}}
ref={scrollViewRef}
onContentSizeChange={() => {
scrollViewRef.current.scrollToEnd({ animated: true });
}}
style={{ flex: 1 }}
>
{logs.map((log, i) => (
<Text
key={`t-${i}`}
style={{
fontFamily: Platform.OS === "ios" ? "Courier New" : "monospace",
color: "#fff",
fontSize: 14
}}
>
{log}
</Text>
))}
</ScrollView>
</View>
<View style={{ flex: 0, paddingTop: 20, paddingBottom: 40 }}>
<Btn title="Connect" onPress={connect} />
<Btn title="Disconnect" onPress={disconnect} />
<Btn title="Sign And Send Transaction" onPress={signAndSendTransaction} />
<Btn title="Sign All Transactions" onPress={signAllTransactions} />
<Btn title="Sign Transaction" onPress={signTransaction} />
<Btn title="Sign Message" onPress={signMessage} />
<Btn title="Clear Logs" onPress={clearLog} />
</View>
</View>
);
}
const Btn = ({ title, onPress }: { title: string; onPress: () => void | Promise<void> }) => {
return (
<View style={{ marginVertical: 10 }}>
<Button title={title} onPress={onPress} />
</View>
);
};