import { IModule , IPrivateKeyFormat , IPrivateKeyStore , ITKeyApi } from "@tkey/common-types" ; import BN from "bn.js" ; import PrivateKeysError from "./errors" ; export const PRIVATE_KEY_MODULE_NAME = "privateKeyModule" ; class PrivateKeyModule implements IModule { moduleName : string ; tbSDK : ITKeyApi ; privateKeyFormats : IPrivateKeyFormat [ ] ; constructor ( formats ) { this . moduleName = PRIVATE_KEY_MODULE_NAME ; this . privateKeyFormats = formats ; } setModuleReferences ( tbSDK ) { this . tbSDK = tbSDK ; this . tbSDK . _addReconstructKeyMiddleware ( this . moduleName , this . getAccounts . bind ( this ) ) ; } async initialize ( ) { } async setPrivateKey ( privateKeyType , privateKey ? ) { const format = this . privateKeyFormats . find ( ( el ) => el . type === privateKeyType ) ; if ( ! format ) { throw PrivateKeysError . notSupported ( ) ; } if ( privateKey && ! format . validatePrivateKey ( privateKey ) ) { throw PrivateKeysError . invalidPrivateKey ( `${ privateKey }` ) ; } const privateKeyStore = format . createPrivateKeyStore ( privateKey ) ; return this . tbSDK . _setTKeyStoreItem ( this . moduleName , privateKeyStore ) ; } async getPrivateKeys ( ) { return this . tbSDK . getTKeyStore ( this . moduleName ) as Promise < IPrivateKeyStore [ ] > ; } async getAccounts ( ) { try { const privateKeys = await this . getPrivateKeys ( ) ; return privateKeys . reduce ( ( acc , x ) => { acc . push ( BN . isBN ( x . privateKey ) ? x . privateKey : new BN ( x . privateKey , "hex" ) ) ; return acc ; } , [ ] ) ; } catch ( err ) { return [ ] ; } } } export default PrivateKeyModule ;