import { Buffer } from 'buffer';
import * as bip39 from 'bip39';
import { ethers } from 'ethers';
import * as Crypto from 'expo-crypto';
import { useEffect, useState } from 'react';
import { FlatList, Pressable, View, Text } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { saveMnemonic } from '@/components/SecureStoreHelper';
const CreateWallet = () => {
const [mnemonic, setMnemonic] = useState<string[]>([]);
const [wallet, setwallet] = useState<ethers.HDNodeWallet>();
function generateMnemonic() {
const randomBytes = Crypto.getRandomBytes(16);
const mnemonic = bip39.entropyToMnemonic(
Buffer.from(randomBytes).toString('hex'),
);
setMnemonic(mnemonic.split(' '));
}
const getWallet = () => {
if (!mnemonic.length) return;
const wallet = ethers.Wallet.fromPhrase(mnemonic.join(' '));
saveMnemonic(mnemonic.join(' '));
setwallet(wallet);
};
useEffect(() => {
generateMnemonic();
}, []);
useEffect(() => {
getWallet();
}, [mnemonic]);
return (
<SafeAreaView
style={{
flex: 1,
justifyContent: 'flex-start',
gap: 20,
padding: 20,
}}
>
<View>
<FlatList
data={mnemonic}
renderItem={({ item, index }) => (
<View
style={{
flex: 1,
padding: 5,
alignItems: 'center',
borderColor: 'gray',
borderWidth: 1,
margin: 5,
borderRadius: 5,
position: 'relative',
flexDirection: 'row',
}}
>
<Text style={{ marginHorizontal: 2 }}>{index + 1}</Text>
<Text style={{ flex: 1, textAlign: 'center' }}>{item}</Text>
</View>
)}
keyExtractor={(item) => item}
numColumns={3}
/>
</View>
<View style={{ gap: 20 }}>
<Text>Address: {wallet?.address}</Text>
<Text>Private Key: {wallet?.privateKey}</Text>
<Text>Public Key: {wallet?.publicKey}</Text>
</View>
<Pressable
onPress={() => {
generateMnemonic();
}}
>
<Text style={{ color: 'blue' }}>Reload</Text>
</Pressable>
</SafeAreaView>
);
};
export default CreateWallet;