-
Notifications
You must be signed in to change notification settings - Fork 1
/
App.tsx
286 lines (273 loc) · 9.03 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
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* Generated with the TypeScript template
* https://github.com/react-native-community/react-native-template-typescript
*
* @format
*/
import AsyncStorage from '@react-native-async-storage/async-storage';
import {
clusterApiUrl,
Connection,
PublicKey,
SystemProgram,
Transaction,
} from '@solana/web3.js';
import {transact} from '@solana-mobile/mobile-wallet-adapter-protocol-web3js';
import React, {useCallback, useEffect, useState} from 'react';
import {
Button,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
TextInput,
useColorScheme,
View,
} from 'react-native';
import {Colors, Header} from 'react-native/Libraries/NewAppScreen';
import {Camera, CameraType} from 'react-native-camera-kit';
import {toByteArray} from 'react-native-quick-base64';
const App = () => {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
// Store details about the currently connected wallet.
const [currentAccount, setCurrentAccount] = useState<{
authToken: string;
pubkey: PublicKey;
} | null>(null);
const [currentAccountBalance, setCurrentAccountBalance] = useState(0);
async function refreshBalance(accountPubkey: PublicKey) {
const connection = new Connection(clusterApiUrl('testnet'));
setCurrentAccountBalance(
await connection.getBalance(accountPubkey, 'processed'),
);
}
// When the application boots up, check to see if we have a prior authorization.
useEffect(() => {
(async () => {
const [cachedAuthToken, cachedBase64Address] = await Promise.all([
AsyncStorage.getItem('authToken'),
AsyncStorage.getItem('base64Address'),
]);
if (cachedBase64Address && cachedAuthToken) {
const pubkeyAsByteArray = toByteArray(cachedBase64Address);
const cachedCurrentAccount = {
authToken: cachedAuthToken,
pubkey: new PublicKey(pubkeyAsByteArray),
};
setCurrentAccount(cachedCurrentAccount);
refreshBalance(cachedCurrentAccount.pubkey);
}
})();
}, []);
// Pressing the connect button should authorize this app with the wallet,
// cache the resulting auth token, and fetch the wallet's balance.
const handleConnectPress = useCallback(() => {
transact(async wallet => {
const {accounts, auth_token} = await wallet.authorize({
cluster: 'testnet',
identity: {
name: 'My amazing app',
},
});
const firstAccount = accounts[0];
AsyncStorage.setItem('authToken', auth_token);
AsyncStorage.setItem('base64Address', firstAccount.address);
const pubkeyAsByteArray = toByteArray(firstAccount.address);
const nextCurrentAccount = {
authToken: auth_token,
pubkey: new PublicKey(pubkeyAsByteArray),
};
setCurrentAccount(nextCurrentAccount);
refreshBalance(nextCurrentAccount.pubkey);
});
}, []);
// Store the destination address for the transfer, and the transfer amount.
const [recipientAddress, setRecipientAddress] = useState('');
const [transferAmount, setTransferAmount] = useState('');
// Create a flag that determines whether to show the QR code scanner.
const [showScanner, setShowScanner] = useState(false);
// Pressing the send button computes the number of lamports to send,
// creates the transaction and the transfer instruction, asks the
// wallet to sign and send the transaction, and updates the sender's balance.
const handleSendPress = useCallback(() => {
const lamports = Math.floor(parseFloat(transferAmount) * 10 ** 9);
transact(async wallet => {
if (currentAccount == null) {
throw new Error("Can't send without a current account");
}
try {
await wallet.reauthorize({
auth_token: currentAccount.authToken,
});
} catch (e: any) {
console.error(e.message);
setCurrentAccount(null);
}
const connection = new Connection(clusterApiUrl('testnet'));
const latestBlockhash = await connection.getLatestBlockhash('processed');
const sendTokensTransaction = new Transaction({
feePayer: currentAccount.pubkey,
...latestBlockhash,
});
sendTokensTransaction.add(
SystemProgram.transfer({
fromPubkey: currentAccount.pubkey,
toPubkey: new PublicKey(recipientAddress),
lamports,
}),
);
setRecipientAddress('');
setTransferAmount('');
const [signature] = await wallet.signAndSendTransactions({
transactions: [sendTokensTransaction],
});
await connection.confirmTransaction(signature, 'processed');
console.log(
`https://explorer.solana.com/tx/${signature}?cluster=testnet`,
);
refreshBalance(currentAccount.pubkey);
});
}, [currentAccount, recipientAddress, transferAmount]);
// Pressing the airdrop button requests an airdrop for the currently
// authorized wallet, then updates the balance.
const handleAirdropPress = useCallback(async () => {
const connection = new Connection(clusterApiUrl('testnet'));
await connection.confirmTransaction(
await connection.requestAirdrop(currentAccount!.pubkey, 1 * 10 ** 9),
'processed',
);
refreshBalance(currentAccount!.pubkey);
}, [currentAccount]);
// Pressing disconnect deauthorizes this app with the wallet, and clears
// all cached account information.
const handleDisconnectPress = useCallback(() => {
transact(async wallet => {
if (currentAccount == null) {
throw new Error('There is no current account to deauthorize');
}
await wallet.deauthorize({auth_token: currentAccount.authToken});
AsyncStorage.clear();
setCurrentAccount(null);
setCurrentAccountBalance(0);
});
}, [currentAccount]);
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
{showScanner ? (
<View style={styles.cameraContainer}>
<Camera
cameraType={CameraType.Back}
scanBarcode
onReadCode={(event: any) => {
setRecipientAddress(event.nativeEvent.codeStringValue);
setShowScanner(false);
}}
style={styles.camera}
/>
<Button
title="Cancel"
onPress={() => {
setShowScanner(false);
}}
/>
</View>
) : (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
...styles.mainContainer,
}}>
{currentAccount ? (
<>
<Text style={styles.header}>
My wallet ({currentAccount.pubkey.toBase58().slice(0, 6)}
…)
</Text>
<Text style={styles.balance}>
Current balance: {currentAccountBalance / 10 ** 9} SOL
</Text>
<Button title="Airdrop SOL" onPress={handleAirdropPress} />
<Button
color="darkred"
title="Disconnect"
onPress={handleDisconnectPress}
/>
<Text style={styles.header}>Recipient wallet address</Text>
<TextInput
style={styles.input}
value={recipientAddress}
onChangeText={newText => {
setRecipientAddress(newText);
}}
keyboardType="visible-password"
/>
<Button
title="Scan QR Code"
onPress={() => {
setShowScanner(true);
}}
/>
<Text style={styles.header}>Amount to transfer (SOL)</Text>
<TextInput
style={styles.input}
onChangeText={newText => {
setTransferAmount(newText);
}}
value={transferAmount}
keyboardType="numeric"
/>
<Button title="Send" onPress={handleSendPress} />
</>
) : (
<>
<Button title="Connect" onPress={handleConnectPress} />
</>
)}
</View>
</ScrollView>
)}
</SafeAreaView>
);
};
const styles = StyleSheet.create({
balance: {
marginBottom: 12,
},
camera: {
flexGrow: 1,
},
cameraContainer: {
height: '100%',
},
header: {
marginVertical: 12,
fontSize: 20,
fontWeight: 'bold',
},
input: {
height: 40,
padding: 10,
borderWidth: 1,
backgroundColor: 'white',
color: 'black',
},
mainContainer: {
padding: 16,
},
});
export default App;