import { utils, Wallet } from 'ethers'; import type { KeyStorageConfig } from './keyManagerTypes'; type ExpoObject = { modules: undefined | { [key: string]: any }; }; declare global { var expo: ExpoObject | undefined; var ExpoModules: undefined | { [key: string]: any }; } const LINKING_ERROR = "The package 'expo-secure-store' doesn't seem to be available please install it as a dependency if using expo."; type KeychainAccessibilityConstant = number; const WHEN_UNLOCKED: KeychainAccessibilityConstant = 5; const WHEN_UNLOCKED_THIS_DEVICE_ONLY: KeychainAccessibilityConstant = 6; type SecureStoreOptions = { keychainService?: string; requireAuthentication?: boolean; authenticationPrompt?: string; keychainAccessible?: KeychainAccessibilityConstant; }; let SecureStore: { getItemAsync: (mnemonic: string) => Promise; setItemAsync: ( key: string, value: string, options: SecureStoreOptions ) => Promise; deleteItemAsync: (key: string) => Promise; }; if (global.expo?.modules || global.ExpoModules) { try { SecureStore = require('expo-secure-store'); } catch (e) { throw new Error(LINKING_ERROR); } } else { throw new Error(LINKING_ERROR); } const MNEMONIC_ACCOUNT_KEY = 'BIP39_MNEMONIC'; export const getMnemonic = async (): Promise => { return SecureStore.getItemAsync(MNEMONIC_ACCOUNT_KEY); }; export const generateMnemonic = async (): Promise => { return utils.entropyToMnemonic(utils.randomBytes(24)); }; export const saveMnemonic = async ( mnemonic: string, options: KeyStorageConfig = { saveToCloud: true, rejectOnCloudSaveFailure: false, } ): Promise => { const keychainAccessible = options.saveToCloud ? WHEN_UNLOCKED : WHEN_UNLOCKED_THIS_DEVICE_ONLY; return SecureStore.setItemAsync(MNEMONIC_ACCOUNT_KEY, mnemonic, { keychainAccessible, }); }; export const deleteMnemonic = async (): Promise => { return SecureStore.deleteItemAsync(MNEMONIC_ACCOUNT_KEY); }; export const getPrivateKeyFromMnemonic = async ( mnemonic: string ): Promise => { return utils.arrayify(Wallet.fromMnemonic(mnemonic).privateKey); };