import { IModule , ISeedPhraseFormat , ISeedPhraseStore , ISeedPhraseStoreWithKeys , ITKeyApi } from "@tkey/common-types" ; import BN from "bn.js" ; import SeedPhraseError from "./errors" ; export const SEED_PHRASE_MODULE_NAME = "seedPhraseModule" ; class SeedPhraseModule implements IModule { moduleName : string ; tbSDK : ITKeyApi ; seedPhraseFormats : ISeedPhraseFormat [ ] ; constructor ( formats ) { this . moduleName = SEED_PHRASE_MODULE_NAME ; this . seedPhraseFormats = formats ; } setModuleReferences ( tbSDK ) { this . tbSDK = tbSDK ; this . tbSDK . _addReconstructKeyMiddleware ( this . moduleName , this . getAccounts . bind ( this ) ) ; } async initialize ( ) { } async setSeedPhrase ( seedPhraseType , seedPhrase ? ) { const format = this . seedPhraseFormats . find ( ( el ) => el . type === seedPhraseType ) ; if ( ! format ) { throw SeedPhraseError . notSupported ( ) ; } if ( seedPhrase && ! format . validateSeedPhrase ( seedPhrase ) ) { throw SeedPhraseError . invalid ( `${ seedPhraseType }` ) ; } const seedPhraseStore = await format . createSeedPhraseStore ( seedPhrase ) ; return this . tbSDK . _setTKeyStoreItem ( this . moduleName , seedPhraseStore ) ; } async setSeedPhraseStoreItem ( partialStore ) { const seedPhraseItem = ( await this . tbSDK . getTKeyStoreItem ( this . moduleName , partialStore . id ) ) as ISeedPhraseStore ; const originalItem = { id : seedPhraseItem . id , type : seedPhraseItem . type , seedPhrase : seedPhraseItem . seedPhrase } ; const finalItem = { ... partialStore , ... originalItem } ; return this . tbSDK . _setTKeyStoreItem ( this . moduleName , finalItem ) ; } async CRITICAL_changeSeedPhrase ( oldSeedPhrase , newSeedPhrase ) { const seedPhrases = await this . getSeedPhrases ( ) ; const itemToChange = seedPhrases . find ( ( x ) => x . seedPhrase === oldSeedPhrase ) ; itemToChange . seedPhrase = newSeedPhrase ; return this . tbSDK . _setTKeyStoreItem ( this . moduleName , itemToChange ) ; } async getSeedPhrases ( ) { return this . tbSDK . getTKeyStore ( this . moduleName ) as Promise < ISeedPhraseStore [ ] > ; } async getSeedPhrasesWithAccounts ( ) { try { const seedPhrases = await this . getSeedPhrases ( ) ; return await Promise . all ( seedPhrases . map ( async ( x ) => { const suitableFormat = this . seedPhraseFormats . find ( ( y ) => y . type === x . type ) ; const keys = await suitableFormat . deriveKeysFromSeedPhrase ( x ) ; return { ... x , keys } ; } ) ) ; } catch ( err ) { return [ ] ; } } async getAccounts ( ) { try { const seedPhrases = await this . getSeedPhrases ( ) ; const responses = await Promise . all ( seedPhrases . map ( async ( x ) => { const suitableFormat = this . seedPhraseFormats . find ( ( y ) => y . type === x . type ) ; return suitableFormat . deriveKeysFromSeedPhrase ( x ) ; } ) ) ; return responses . flatMap ( ( x ) => x ) ; } catch ( err ) { return [ ] ; } } } export default SeedPhraseModule ;