
Building an Ethereum Wallet App with Expo and TypeScript
In this guide, we'll walk through the creation of an Ethereum wallet app using Expo, TypeScript, and theethers.js
library. We'll focus on generating a mnemonic, accessing an Ethereum address, and checking balances from the blockchain, inspired by theX-Wallet example, which leveragesDomain-Driven Design (DDD) principles.
Understanding Ethereum Wallets
Ethereum wallets serve as gateways to interact with the Ethereum blockchain, allowing users to manage their Ether (ETH) and other tokens. They come in various forms:
- Hot Wallets: These are software or online wallets (like MetaMask) that offer convenience at the cost of security.
- Cold Wallets: Physical or hardware wallets (like Ledger or Trezor) provide enhanced security since they are not connected to the internet when not in use.
Key Concepts:
- Private Key: Used to sign transactions and prove ownership of cryptocurrencies.
- Public Key: Generated from the private key, used for receiving ETH.
- Address: Derived from the public key, an address where ETH can be sent.
🛠 Prerequisites and Setup
Software Requirements:
- Node.js: Installed on your development machine.
- Expo CLI: Install globally via
npm install -g expo-cli
. - React Native: Familiarity is beneficial, though not mandatory for this guide.
- TypeScript: Ensure your Expo project supports TypeScript.
Installation Commands:
expo init ethereum-wallet-app--template expo-template-blank-typescriptcdethereum-wallet-appnpminstallethers react-native-get-random-values @ethersproject/shims @dawar2151/bip39-expo
🚀 Step 1: Initialize Your Expo Project
Begin by setting up a new Expo project with TypeScript:
bash
expo init ethereum-wallet-app --template expo-template-blank-typescript
cd ethereum-wallet-app
expo start
🔐 Step 2: Wallet Management Services
Create WalletService.ts for handling wallet operations:
import'react-native-get-random-values';import'@ethersproject/shims';import{Wallet,JsonRpcProvider,Contract,BigNumberish}from'ethers';import{hdkey}from'ethereumjs-wallet';importBip39from'@dawar2151/bip39-expo';import{ERC20_ABI,PATH_DERIVE}from'@x/global/config/constants';// Assuming these constants existimport{NETWORKS,ANKR_KEY,INFURA_SECRET}from'@/global/constants';// Assuming these are defined elsewhereimport{typeToken}from'@/domain/tickers/models/token';// Assuming this type is definedimport{typeNetwork}from'@/global/types.constants';// Assuming this type is defined// Generate a new mnemonicexportconstgenerateNewMnemonic=async():Promise<string>=>Bip39.generateMnemonic();// Derive wallet from mnemonicexportasyncfunctiongetWallet(phrase:string,currentNetwork:Network):Promise<Wallet>{constseed=awaitBip39.mnemonicToSeed(phrase);consthdwallet=hdkey.fromMasterSeed(seed);constwallet=hdwallet.derivePath(PATH_DERIVE).getWallet();returnnewWallet(wallet.getPrivateKeyString(),getProvider(currentNetwork));}// Fetch native token balanceexportconstgetNativeTokenBalance=async(currentNetwork:Network,account:string):Promise<BigNumberish>=>{constprovider=getProvider(currentNetwork);returnprovider.getBalance(account);};// Fetch ERC20 token balanceexportconstgetTokenBalance=async(currentNetwork:Network,tokenAddress:string,account:string):Promise<BigNumberish>=>{constprovider=getProvider(currentNetwork);constcontract=newContract(tokenAddress,ERC20_ABI,provider);returncontract.balanceOf(account);};// Select provider based on networkexportfunctiongetProvider(currentNetwork:Network='sepolia'):JsonRpcProvider{switch(currentNetwork){caseNETWORKS.bsc:returnnewJsonRpcProvider(`https://rpc.ankr.com/bsc/${ANKR_KEY}`);caseNETWORKS.base:returnnewJsonRpcProvider(`https://rpc.ankr.com/base/${ANKR_KEY}`);default:returnnewJsonRpcProvider(`https://${currentNetwork}.infura.io/v3/${INFURA_SECRET}`);}}// Get balance for supported tokensexportasyncfunctiongetBalance(tokenId:string,supportedTokens:{[key:string]:Token},currentNetwork:Network,currentAddress:string):Promise<BigNumberish>{consttoken=supportedTokens[tokenId];if(token.isNative){returngetNativeTokenBalance(currentNetwork,currentAddress);}else{returngetTokenBalance(currentNetwork,token.address,currentAddress);}}
📲 Step 3: Crafting the User Interface
Update Wallet.tsx for basic wallet functionalities:
importReactfrom'react';import{StyleSheet,View}from'react-native';importXButtonfrom'@x/global/components/X/XButton';import{useSelector,useDispatch}from'react-redux';import{generatePhrase,setUpWallet}from'@x/wallets/XReducer';import{removeValue,saveValue}from'../../../infra/secureStorage';import{XContainer}from'@x/global/components/styled/Container';import{generateNewMnemonic}from'../../../infra/helpers';import{typeAppDispatch,typeRootState}from'@x/global/state/store';import{XActivityIndicator}from'@/global/components/X/XActiveIndicator';import{Routes}from'@/global/navigation/RouteNames';import{PHRASE_KEY}from'../constants';import{useNavigation}from'@react-navigation/native';importXLogofrom'@/domain/authorizations/components/XLogo';import{useXWalletHelper}from'../hooks/useXWalletHelper';exportfunctionWallet():JSX.Element{constnavigation=useNavigation();constloading=useSelector((state:RootState)=>state.x.loading);const{setLocalLoading}=useXWalletHelper();constdispatch=useDispatch<AppDispatch>();constgenerateMnemonic=async()=>{setLocalLoading();try{constphrase=awaitgenerateNewMnemonic();awaitsaveValue(PHRASE_KEY,phrase);awaitremoveValue('password');dispatch(generatePhrase(phrase));dispatch(setUpWallet({phrase}));setLocalLoading();navigation.navigate(Routes.DEFINE_PASSWORDasnever);}catch(error){console.error(error);}};return(<XContainer>{!loading?(<Viewstyle={styles.walletContainer}><XLogo/><XButtononPress={generateMnemonic}title="Generate new seed phrase"icon="wallet"/><XButtonicon="import"onPress={()=>navigation.navigate(Routes.IMPORT_MNEMONICasnever)}title="Import existing seed phrase"/></View>):(<XActivityIndicator/>)}</XContainer>);}conststyles=StyleSheet.create({walletContainer:{marginHorizontal:50,gap:20},});
`
🔑Key Features of X-Wallet
- Token Distribution: Bulk sending of native and ERC20 tokens with optimized gas fees.
- Wallet Management: Create, import, and export wallets using BIP-39 mnemonics.
- Network Switching: Support for various networks including testnets.
- User Interface: Balance display, QR code address sharing, and transaction history.
- Security: Password-protected access, enhanced gas settings, and token swapping.
🔗 Accessing Full Source Code
For the complete implementation of X-Wallet with advanced features, you can exploreCodeCrayon
This guide provides a foundation for building your own Ethereum wallet app. Happy coding! 🚀
🌟 Useful Tools for Blockchain Users
Top comments(1)
For further actions, you may consider blocking this person and/orreporting abuse