From 7817294441f1a9fb9e076288b9949ae9089ee8c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bego=C3=B1a=20Alvarez?= Date: Wed, 22 Nov 2023 15:40:37 +0100 Subject: [PATCH 01/19] refactor(wip): create api core module --- packages/desktop/electron/preload.js | 28 ++++++------- .../components/inputs/AliasInput.svelte | 2 +- .../account/interfaces/account.interface.ts | 2 +- .../persisted-account-data.interface.ts | 3 +- .../lib/core/{profile-manager => }/api/api.ts | 2 +- packages/shared/lib/core/api/index.ts | 2 + .../lib/core/api/interfaces/api.interface.ts | 30 ++++++++++++++ .../shared/lib/core/api/interfaces/index.ts | 1 + .../core/new-profile/actions/createAccount.ts | 8 ++++ .../api => new-profile/actions}/getAccount.ts | 2 +- .../core/new-profile/actions/getAccounts.ts | 16 ++++++++ .../actions}/recoverAccounts.ts | 4 +- .../actions}/removeLatestAccount.ts | 0 .../core/profile-manager/api/createAccount.ts | 20 ---------- .../profile-manager/api/generateMnemonic.ts | 5 --- .../core/profile-manager/api/getAccounts.ts | 11 ------ .../profile-manager/api/verifyMnemonic.ts | 5 --- .../interfaces/api.interface.ts | 39 ------------------- .../core/profile-manager/interfaces/index.ts | 2 +- .../api => secret-manager/actions}/index.ts | 7 ++-- .../api => wallet/actions}/backup.ts | 0 .../actions}/changeStrongholdPassword.ts | 0 .../actions}/clearStrongholdPassword.ts | 0 .../api => wallet/actions}/getClient.ts | 0 .../actions}/getLedgerNanoStatus.ts | 0 .../api => wallet/actions}/getNodeInfo.ts | 2 +- .../shared/lib/core/wallet/actions/index.ts | 3 ++ .../actions}/isStrongholdUnlocked.ts | 0 .../api => wallet/actions}/restoreBackup.ts | 0 .../actions}/setClientOptions.ts | 0 .../actions}/setStrongholdPassword.ts | 0 .../setStrongholdPasswordClearInterval.ts | 0 .../actions}/startBackgroundSync.ts | 0 .../api => wallet/actions}/storeMnemonic.ts | 0 .../generateSingleAliasActivity.ts | 4 +- .../generateSingleFoundryActivity.ts | 2 +- .../utils/getBech32AddressFromAddressTypes.ts | 4 +- 37 files changed, 90 insertions(+), 114 deletions(-) rename packages/shared/lib/core/{profile-manager => }/api/api.ts (77%) create mode 100644 packages/shared/lib/core/api/index.ts create mode 100644 packages/shared/lib/core/api/interfaces/api.interface.ts create mode 100644 packages/shared/lib/core/api/interfaces/index.ts create mode 100644 packages/shared/lib/core/new-profile/actions/createAccount.ts rename packages/shared/lib/core/{profile-manager/api => new-profile/actions}/getAccount.ts (89%) create mode 100644 packages/shared/lib/core/new-profile/actions/getAccounts.ts rename packages/shared/lib/core/{profile-manager/api => new-profile/actions}/recoverAccounts.ts (79%) rename packages/shared/lib/core/{profile-manager/api => new-profile/actions}/removeLatestAccount.ts (100%) delete mode 100644 packages/shared/lib/core/profile-manager/api/createAccount.ts delete mode 100644 packages/shared/lib/core/profile-manager/api/generateMnemonic.ts delete mode 100644 packages/shared/lib/core/profile-manager/api/getAccounts.ts delete mode 100644 packages/shared/lib/core/profile-manager/api/verifyMnemonic.ts delete mode 100644 packages/shared/lib/core/profile-manager/interfaces/api.interface.ts rename packages/shared/lib/core/{profile-manager/api => secret-manager/actions}/index.ts (78%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/backup.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/changeStrongholdPassword.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/clearStrongholdPassword.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/getClient.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/getLedgerNanoStatus.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/getNodeInfo.ts (95%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/isStrongholdUnlocked.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/restoreBackup.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/setClientOptions.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/setStrongholdPassword.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/setStrongholdPasswordClearInterval.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/startBackgroundSync.ts (100%) rename packages/shared/lib/core/{profile-manager/api => wallet/actions}/storeMnemonic.ts (100%) diff --git a/packages/desktop/electron/preload.js b/packages/desktop/electron/preload.js index eb7acd45ad5..38570f4a054 100644 --- a/packages/desktop/electron/preload.js +++ b/packages/desktop/electron/preload.js @@ -113,7 +113,7 @@ try { bindMethodsAcrossContextBridge(IotaSdk.SecretManager.prototype, manager) return manager }, - // rename to createWallet + // TODO(2.0): rename to createWallet async createAccount(id, options) { const wallet = new IotaSdk.Wallet(options) wallet.id = id @@ -121,27 +121,23 @@ try { bindMethodsAcrossContextBridge(IotaSdk.Wallet.prototype, wallet) return wallet }, + // TODO(2.0): review this implementation deleteWallet(id) { if (id && id in wallets) { delete wallets[id] } }, - async getAccount(managerId, index) { - const manager = wallets[managerId] - const account = await manager.getAccount(index) - bindMethodsAcrossContextBridge(IotaSdk.Account.prototype, account) - return account - }, - async getAccounts(managerId, options) { - const accounts = [ - new IotaSdk.Wallet({ - ...options, - id: `${managerId}-0` - }) - ] - accounts.forEach((account) => bindMethodsAcrossContextBridge(IotaSdk.Account.prototype, account)) - return accounts + // TODO(2.0): Rename this to getWallet and fix all usages + async getAccount(id, walletOptions) { + let wallet = wallets[id] + if(!wallet){ + wallet = new IotaSdk.Wallet(walletOptions) + wallets[id] = wallet + bindMethodsAcrossContextBridge(IotaSdk.Account.prototype, wallet) + } + return wallet }, + // TODO(2.0): remove this method from here and move to new profile async recoverAccounts(managerId, payload) { const manager = wallets[managerId] const accounts = await manager.recoverAccounts(...Object.values(payload)) diff --git a/packages/shared/components/inputs/AliasInput.svelte b/packages/shared/components/inputs/AliasInput.svelte index 0a4413888d7..f5fe58e2563 100644 --- a/packages/shared/components/inputs/AliasInput.svelte +++ b/packages/shared/components/inputs/AliasInput.svelte @@ -15,7 +15,7 @@ const aliasOptions: IOption[] = $selectedAccount.balances?.aliases.map((hexAliasId, index) => { - const aliasId = api.aliasIdToBech32(hexAliasId, getNetworkHrp()) + const aliasId = api.accountIdToBech32(hexAliasId, getNetworkHrp()) return { key: 'Alias ' + (index + 1), value: aliasId } }) ?? [] diff --git a/packages/shared/lib/core/account/interfaces/account.interface.ts b/packages/shared/lib/core/account/interfaces/account.interface.ts index 34f231a9ab4..e7f368b778a 100644 --- a/packages/shared/lib/core/account/interfaces/account.interface.ts +++ b/packages/shared/lib/core/account/interfaces/account.interface.ts @@ -1,4 +1,3 @@ -import { Client } from '@iota/sdk' import type { AccountMetadata, AddressWithUnspentOutputs, @@ -6,6 +5,7 @@ import type { Balance, CreateNativeTokenParams, ConsolidationParams, + Client, FilterOptions, GenerateAddressOptions, MintNftParams, diff --git a/packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts b/packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts index f3052b8d0e1..23b24dda206 100644 --- a/packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts +++ b/packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts @@ -1,4 +1,4 @@ -import { ParticipationEventId } from '@iota/sdk/out/types' +import { ParticipationEventId, WalletOptions } from '@iota/sdk/out/types' export interface IPersistedAccountData { name: string @@ -6,4 +6,5 @@ export interface IPersistedAccountData { hidden: boolean shouldRevote: boolean removedProposalIds?: ParticipationEventId[] + walletOptions: WalletOptions } diff --git a/packages/shared/lib/core/profile-manager/api/api.ts b/packages/shared/lib/core/api/api.ts similarity index 77% rename from packages/shared/lib/core/profile-manager/api/api.ts rename to packages/shared/lib/core/api/api.ts index 18bb1fe9833..f325f3e5bf0 100644 --- a/packages/shared/lib/core/profile-manager/api/api.ts +++ b/packages/shared/lib/core/api/api.ts @@ -1,4 +1,4 @@ -import { IApi } from '../interfaces' +import { IApi } from './interfaces' declare global { interface Window { diff --git a/packages/shared/lib/core/api/index.ts b/packages/shared/lib/core/api/index.ts new file mode 100644 index 00000000000..aef4bcdadba --- /dev/null +++ b/packages/shared/lib/core/api/index.ts @@ -0,0 +1,2 @@ +export * from './api' +export * from './interfaces' diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts new file mode 100644 index 00000000000..98e052bab4e --- /dev/null +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -0,0 +1,30 @@ +import { IAccount } from '@core/account' +import { SecretManager } from '@iota/sdk' +import { AccountId, FoundryId, HexEncodedString, NftId, Output, OutputId, SecretManagerType, TransactionId, WalletOptions, Bech32Address } from '@iota/sdk/out/types' + +export interface IApi { + createSecretManager(options: SecretManagerType): Promise + createAccount(id: string, payload: WalletOptions): Promise + deleteWallet(id: string): void + getAccount(id: string, walletOptions: WalletOptions): Promise + migrateStrongholdSnapshotV2ToV3( + currentPath: string, + currentPassword: string, + newPath: string, + newPassword: string + ): Promise + migrateDbChrysalisToStardust(path: string, pinCode: string): Promise> + // Mapped from sdk#Utils + generateMnemonic(): Promise + verifyMnemonic(mnemonic: string): Promise + hexToBech32(hex: HexEncodedString, bech32Hrp: string): Bech32Address + bech32ToHex(bech32: Bech32Address): HexEncodedString + computeAccountId(outputId: string): AccountId + computeFoundryId(accountId: AccountId, serialNumber: number, tokenSchemeType: number): Promise + computeNftId(outputId: string): NftId + hexPublicKeyToBech32Address(hex: HexEncodedString, bech32Hrp: string): Bech32Address + accountIdToBech32(accountId: AccountId, bech32Hrp: string): Bech32Address + nftIdToBech32(nftId: string, bech32Hrp: string): Bech32Address + computeOutputId(id: TransactionId, index: number): Promise + outputHexBytes(output: Output): Promise +} diff --git a/packages/shared/lib/core/api/interfaces/index.ts b/packages/shared/lib/core/api/interfaces/index.ts new file mode 100644 index 00000000000..8502d426161 --- /dev/null +++ b/packages/shared/lib/core/api/interfaces/index.ts @@ -0,0 +1 @@ +export * from './api.interface' diff --git a/packages/shared/lib/core/new-profile/actions/createAccount.ts b/packages/shared/lib/core/new-profile/actions/createAccount.ts new file mode 100644 index 00000000000..78752f07f13 --- /dev/null +++ b/packages/shared/lib/core/new-profile/actions/createAccount.ts @@ -0,0 +1,8 @@ +import { IAccount } from '@core/account' +import * as api from '@core/api/actions' +import { WalletOptions } from '@iota/sdk/out/types' + +export function createAccount(id: string, walletOptions: WalletOptions): Promise { + // TODO(2.0): Add all necessary wallet options here + return api.createAccount(id, walletOptions) +} diff --git a/packages/shared/lib/core/profile-manager/api/getAccount.ts b/packages/shared/lib/core/new-profile/actions/getAccount.ts similarity index 89% rename from packages/shared/lib/core/profile-manager/api/getAccount.ts rename to packages/shared/lib/core/new-profile/actions/getAccount.ts index 4342c30242c..a8c487639f6 100644 --- a/packages/shared/lib/core/profile-manager/api/getAccount.ts +++ b/packages/shared/lib/core/new-profile/actions/getAccount.ts @@ -2,7 +2,7 @@ import { get } from 'svelte/store' import { IAccount } from '@core/account' -import { api } from './api' +import { api } from '../../api/api' import { profileManager } from '../stores' export function getAccount(index: number, manager = profileManager): Promise { diff --git a/packages/shared/lib/core/new-profile/actions/getAccounts.ts b/packages/shared/lib/core/new-profile/actions/getAccounts.ts new file mode 100644 index 00000000000..32771b2eee7 --- /dev/null +++ b/packages/shared/lib/core/new-profile/actions/getAccounts.ts @@ -0,0 +1,16 @@ +import { IAccount } from '@core/account' +import { activeProfile } from '@core/profile/stores' +import { get } from 'svelte/store' +import { api } from '../../api/api' + +// TODO(2.0): Fix all usages of this method +// TODO(2.0): Finalize when new profile is ready +export async function getAccounts(): Promise { + const profile = get(activeProfile) + let wallets: IAccount[] = [] + if (profile.accountPersistedData) { + wallets = await Promise.all(Object.entries(profile.accountPersistedData) + .map(([id, data]) => api.getAccount(id, data.walletOptions))) + } + return wallets +} diff --git a/packages/shared/lib/core/profile-manager/api/recoverAccounts.ts b/packages/shared/lib/core/new-profile/actions/recoverAccounts.ts similarity index 79% rename from packages/shared/lib/core/profile-manager/api/recoverAccounts.ts rename to packages/shared/lib/core/new-profile/actions/recoverAccounts.ts index c989821d238..7c74c202138 100644 --- a/packages/shared/lib/core/profile-manager/api/recoverAccounts.ts +++ b/packages/shared/lib/core/new-profile/actions/recoverAccounts.ts @@ -3,8 +3,8 @@ import { get } from 'svelte/store' import { IAccount } from '@core/account' import { profileManager } from '../stores' -import { api } from '../api' -import { RecoverAccountsPayload } from '../interfaces' +import { api } from '../../api' +import { RecoverAccountsPayload } from '../../api/interfaces' export function recoverAccounts( recoverAccountsPayload: RecoverAccountsPayload, diff --git a/packages/shared/lib/core/profile-manager/api/removeLatestAccount.ts b/packages/shared/lib/core/new-profile/actions/removeLatestAccount.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/removeLatestAccount.ts rename to packages/shared/lib/core/new-profile/actions/removeLatestAccount.ts diff --git a/packages/shared/lib/core/profile-manager/api/createAccount.ts b/packages/shared/lib/core/profile-manager/api/createAccount.ts deleted file mode 100644 index 0ac6083403c..00000000000 --- a/packages/shared/lib/core/profile-manager/api/createAccount.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { get, Writable } from 'svelte/store' - -import { CreateAccountPayload } from '@iota/sdk/out/types' - -import { IAccount } from '@core/account' - -import { api, IProfileManager, profileManager } from '..' -import { generateRandomId } from '@core/utils' - -export function createAccount( - payload: CreateAccountPayload, - manager: Writable = profileManager -): Promise { - const profileManager = get(manager) - const id = `${profileManager.id}-0`; - return api.createAccount(id, { - ...payload, - ...profileManager.getSecretManagerOptions() - }) -} diff --git a/packages/shared/lib/core/profile-manager/api/generateMnemonic.ts b/packages/shared/lib/core/profile-manager/api/generateMnemonic.ts deleted file mode 100644 index ab7168a2da4..00000000000 --- a/packages/shared/lib/core/profile-manager/api/generateMnemonic.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { api } from '../api' - -export function generateMnemonic(): Promise { - return api.generateMnemonic() -} diff --git a/packages/shared/lib/core/profile-manager/api/getAccounts.ts b/packages/shared/lib/core/profile-manager/api/getAccounts.ts deleted file mode 100644 index 3dfb3454b73..00000000000 --- a/packages/shared/lib/core/profile-manager/api/getAccounts.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IAccount } from '@core/account' -import { api } from './api' -import { get } from 'svelte/store' -import { profileManager } from '../stores' - -export async function getAccounts(): Promise { - const manager = get(profileManager) - return api.getAccounts(manager.id, { - ...manager - }) -} diff --git a/packages/shared/lib/core/profile-manager/api/verifyMnemonic.ts b/packages/shared/lib/core/profile-manager/api/verifyMnemonic.ts deleted file mode 100644 index 3e5e6d125a0..00000000000 --- a/packages/shared/lib/core/profile-manager/api/verifyMnemonic.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { api } from '../api' - -export async function verifyMnemonic(mnemonic: string): Promise { - return api.verifyMnemonic(mnemonic) -} diff --git a/packages/shared/lib/core/profile-manager/interfaces/api.interface.ts b/packages/shared/lib/core/profile-manager/interfaces/api.interface.ts deleted file mode 100644 index 1baf0400542..00000000000 --- a/packages/shared/lib/core/profile-manager/interfaces/api.interface.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { WalletOptions, CreateAccountPayload, TransactionId, OutputId } from '@iota/sdk/out/types' -import { AliasId, Client, FoundryId, HexEncodedString, NftId, Output } from '@iota/sdk' -import { IAuth } from '@core/network' -import { INodeInfoResponse } from '@core/network/interfaces' - -import { IAccount } from '@core/account' - -import { IProfileManager } from './profile-manager.interface' -import { RecoverAccountsPayload } from './recover-account-payload.interface' - -export interface IApi { - createSecretManager(options: any): Promise - getNodeInfo(profileManagerId: string, url?: string, auth?: IAuth): Promise - createAccount(id: string, payload: CreateAccountPayload): Promise - deleteWallet(id: string): void - getAccount(profileManagerId: string, index: number): Promise - getAccounts(profileManagerId: string, payload: CreateAccountPayload): Promise - recoverAccounts(profileManagerId: string, payload: RecoverAccountsPayload): Promise - migrateStrongholdSnapshotV2ToV3( - currentPath: string, - currentPassword: string, - newPath: string, - newPassword: string - ): Promise - migrateDbChrysalisToStardust(path: string, pinCode: string): Promise> - // Mapped from sdk#Utils - generateMnemonic(): Promise - verifyMnemonic(mnemonic: string): Promise - hexToBech32(hex: string, bech32Hrp: string): string - bech32ToHex(bech32: string): string - computeAliasId(outputId: string): AliasId - computeFoundryId(aliasId: AliasId, serialNumber: number, tokenSchemeType: number): Promise - computeNftId(outputId: string): NftId - hexPublicKeyToBech32Address(hex: string, bech32Hrp: string): string - aliasIdToBech32(aliasId: string, bech32Hrp: string): string - nftIdToBech32(nftId: string, bech32Hrp: string): string - computeOutputId(id: TransactionId, index: number): Promise - outputHexBytes(output: Output): Promise -} diff --git a/packages/shared/lib/core/profile-manager/interfaces/index.ts b/packages/shared/lib/core/profile-manager/interfaces/index.ts index d2d6418db9e..203468b41cf 100644 --- a/packages/shared/lib/core/profile-manager/interfaces/index.ts +++ b/packages/shared/lib/core/profile-manager/interfaces/index.ts @@ -1,4 +1,4 @@ -export * from './api.interface' +export * from '../../api/interfaces/api.interface' export * from './profile-manager.interface' export * from './recover-account-payload.interface' export * from './wallet-api-event-payload-wrapper.interface' diff --git a/packages/shared/lib/core/profile-manager/api/index.ts b/packages/shared/lib/core/secret-manager/actions/index.ts similarity index 78% rename from packages/shared/lib/core/profile-manager/api/index.ts rename to packages/shared/lib/core/secret-manager/actions/index.ts index 10c123085b7..4a10dba5cc4 100644 --- a/packages/shared/lib/core/profile-manager/api/index.ts +++ b/packages/shared/lib/core/secret-manager/actions/index.ts @@ -1,7 +1,6 @@ -export * from './api' -export * from './backup' -export * from './changeStrongholdPassword' -export * from './clearStrongholdPassword' +export * from '../../wallet/actions/backup' +export * from '../../wallet/actions/changeStrongholdPassword' +export * from '../../wallet/actions/clearStrongholdPassword' export * from './createAccount' export * from './generateMnemonic' export * from './getAccount' diff --git a/packages/shared/lib/core/profile-manager/api/backup.ts b/packages/shared/lib/core/wallet/actions/backup.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/backup.ts rename to packages/shared/lib/core/wallet/actions/backup.ts diff --git a/packages/shared/lib/core/profile-manager/api/changeStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/changeStrongholdPassword.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/changeStrongholdPassword.ts rename to packages/shared/lib/core/wallet/actions/changeStrongholdPassword.ts diff --git a/packages/shared/lib/core/profile-manager/api/clearStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/clearStrongholdPassword.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/clearStrongholdPassword.ts rename to packages/shared/lib/core/wallet/actions/clearStrongholdPassword.ts diff --git a/packages/shared/lib/core/profile-manager/api/getClient.ts b/packages/shared/lib/core/wallet/actions/getClient.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/getClient.ts rename to packages/shared/lib/core/wallet/actions/getClient.ts diff --git a/packages/shared/lib/core/profile-manager/api/getLedgerNanoStatus.ts b/packages/shared/lib/core/wallet/actions/getLedgerNanoStatus.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/getLedgerNanoStatus.ts rename to packages/shared/lib/core/wallet/actions/getLedgerNanoStatus.ts diff --git a/packages/shared/lib/core/profile-manager/api/getNodeInfo.ts b/packages/shared/lib/core/wallet/actions/getNodeInfo.ts similarity index 95% rename from packages/shared/lib/core/profile-manager/api/getNodeInfo.ts rename to packages/shared/lib/core/wallet/actions/getNodeInfo.ts index aefc46d9acf..e536731dab3 100644 --- a/packages/shared/lib/core/profile-manager/api/getNodeInfo.ts +++ b/packages/shared/lib/core/wallet/actions/getNodeInfo.ts @@ -2,7 +2,7 @@ import { IAuth } from '@core/network' import { INodeInfoResponse } from '@core/network/interfaces/node-info-response.interface' import { get } from 'svelte/store' import { profileManager } from '../stores' -import { api } from '../api' +import { api } from '../../api' import { selectedAccount } from '@core/account' export async function getNodeInfo(url?: string, auth?: IAuth): Promise { diff --git a/packages/shared/lib/core/wallet/actions/index.ts b/packages/shared/lib/core/wallet/actions/index.ts index 79e6705c0fe..bbb42feb225 100644 --- a/packages/shared/lib/core/wallet/actions/index.ts +++ b/packages/shared/lib/core/wallet/actions/index.ts @@ -1,6 +1,9 @@ +export * from './backup' export * from './burnAsset' export * from './burnNft' +export * from './changeStrongholdPassword' export * from './claimActivity' +export * from './clearStrongholdPassword' export * from './getAccountAssetsForSelectedAccount' export * from './generateAndStoreActivitiesForAllAccounts' export * from './rejectActivity' diff --git a/packages/shared/lib/core/profile-manager/api/isStrongholdUnlocked.ts b/packages/shared/lib/core/wallet/actions/isStrongholdUnlocked.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/isStrongholdUnlocked.ts rename to packages/shared/lib/core/wallet/actions/isStrongholdUnlocked.ts diff --git a/packages/shared/lib/core/profile-manager/api/restoreBackup.ts b/packages/shared/lib/core/wallet/actions/restoreBackup.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/restoreBackup.ts rename to packages/shared/lib/core/wallet/actions/restoreBackup.ts diff --git a/packages/shared/lib/core/profile-manager/api/setClientOptions.ts b/packages/shared/lib/core/wallet/actions/setClientOptions.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/setClientOptions.ts rename to packages/shared/lib/core/wallet/actions/setClientOptions.ts diff --git a/packages/shared/lib/core/profile-manager/api/setStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/setStrongholdPassword.ts rename to packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts diff --git a/packages/shared/lib/core/profile-manager/api/setStrongholdPasswordClearInterval.ts b/packages/shared/lib/core/wallet/actions/setStrongholdPasswordClearInterval.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/setStrongholdPasswordClearInterval.ts rename to packages/shared/lib/core/wallet/actions/setStrongholdPasswordClearInterval.ts diff --git a/packages/shared/lib/core/profile-manager/api/startBackgroundSync.ts b/packages/shared/lib/core/wallet/actions/startBackgroundSync.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/startBackgroundSync.ts rename to packages/shared/lib/core/wallet/actions/startBackgroundSync.ts diff --git a/packages/shared/lib/core/profile-manager/api/storeMnemonic.ts b/packages/shared/lib/core/wallet/actions/storeMnemonic.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/api/storeMnemonic.ts rename to packages/shared/lib/core/wallet/actions/storeMnemonic.ts diff --git a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleAliasActivity.ts b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleAliasActivity.ts index e2ca35244bf..a930f04c5df 100644 --- a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleAliasActivity.ts +++ b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleAliasActivity.ts @@ -68,6 +68,6 @@ export async function generateSingleAliasActivity( function getAliasId(output: AliasOutput, outputId: string): string { const isNewAlias = output.aliasId === EMPTY_HEX_ID - const aliasId = isNewAlias ? api.computeAliasId(outputId) : output.aliasId - return api.aliasIdToBech32(aliasId, getNetworkHrp()) + const aliasId = isNewAlias ? api.computeAccountId(outputId) : output.aliasId + return api.accountIdToBech32(aliasId, getNetworkHrp()) } diff --git a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleFoundryActivity.ts b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleFoundryActivity.ts index 2bd1adc3593..631c338b604 100644 --- a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleFoundryActivity.ts +++ b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleFoundryActivity.ts @@ -37,7 +37,7 @@ export async function generateSingleFoundryActivity( (unlockCondition) => unlockCondition.type === UnlockConditionType.ImmutableAliasAddress ) as ImmutableAliasAddressUnlockCondition const aliasId = (addressUnlockCondition?.address as AliasAddress)?.aliasId - const aliasAddress = aliasId ? api.aliasIdToBech32(aliasId, getNetworkHrp()) : undefined + const aliasAddress = aliasId ? api.accountIdToBech32(aliasId, getNetworkHrp()) : undefined const isHidden = false const isAssetHidden = false diff --git a/packages/shared/lib/core/wallet/utils/getBech32AddressFromAddressTypes.ts b/packages/shared/lib/core/wallet/utils/getBech32AddressFromAddressTypes.ts index 5675b966516..0b76385c501 100644 --- a/packages/shared/lib/core/wallet/utils/getBech32AddressFromAddressTypes.ts +++ b/packages/shared/lib/core/wallet/utils/getBech32AddressFromAddressTypes.ts @@ -7,8 +7,8 @@ export function getBech32AddressFromAddressTypes(address: Address): string { switch (address.type) { case AddressType.Ed25519: return api.hexToBech32((address as Ed25519Address).pubKeyHash, hrp) - case AddressType.Alias: - return api.aliasIdToBech32((address as AliasAddress).aliasId, hrp) + case AddressType.Account: + return api.accountIdToBech32((address as AliasAddress).aliasId, hrp) case AddressType.Nft: return api.nftIdToBech32((address as NftAddress).nftId, hrp) } From 33d0e27604dab8265bec39085ed596dafdd5e838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bego=C3=B1a=20Alvarez?= Date: Wed, 22 Nov 2023 17:22:36 +0100 Subject: [PATCH 02/19] refactor(wip): refactor profile core module --- packages/desktop/electron/preload.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/desktop/electron/preload.js b/packages/desktop/electron/preload.js index 38570f4a054..51693fbc8c6 100644 --- a/packages/desktop/electron/preload.js +++ b/packages/desktop/electron/preload.js @@ -121,7 +121,7 @@ try { bindMethodsAcrossContextBridge(IotaSdk.Wallet.prototype, wallet) return wallet }, - // TODO(2.0): review this implementation + // TODO(2.0): also remove from file system deleteWallet(id) { if (id && id in wallets) { delete wallets[id] @@ -144,6 +144,9 @@ try { accounts.forEach((account) => bindMethodsAcrossContextBridge(IotaSdk.Account.prototype, account)) return accounts }, + clearWalletsFromMemory() { + Object.keys(wallets).forEach((id) => delete wallets[id]) + }, async migrateStrongholdSnapshotV2ToV3(currentPath, newPath, currentPassword, newPassword) { const snapshotSaltV2 = 'wallet.rs' const snapshotRoundsV2 = 100 From ee2931c853cf39d0c4e722606c1a23975f155aec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bego=C3=B1a=20Alvarez?= Date: Thu, 23 Nov 2023 09:50:12 +0100 Subject: [PATCH 03/19] refactor(wip): refactor profile core module --- .../lib/core/api/interfaces/api.interface.ts | 1 + .../core/new-profile/actions/createAccount.ts | 8 ----- .../core/new-profile/actions/getAccount.ts | 13 ------- .../new-profile/actions/recoverAccounts.ts | 15 -------- .../actions/removeLatestAccount.ts | 8 ----- .../profile-manager/actions/deleteAccount.ts | 13 +++---- .../actions/destroyProfileManager.ts | 5 +-- .../interfaces/profile-manager.interface.ts | 1 - .../lib/core/profile/actions/createAccount.ts | 36 +++++++++++++++++++ .../lib/core/profile/actions/getAccount.ts | 13 +++++++ .../actions/getAccounts.ts | 2 +- .../shared/lib/core/profile/actions/index.ts | 5 +++ .../core/profile/actions/recoverAccounts.ts | 10 ++++++ .../lib/core/secret-manager/actions/index.ts | 1 - .../tests/__mocks__/profile-manager.mock.ts | 4 --- 15 files changed, 76 insertions(+), 59 deletions(-) delete mode 100644 packages/shared/lib/core/new-profile/actions/createAccount.ts delete mode 100644 packages/shared/lib/core/new-profile/actions/getAccount.ts delete mode 100644 packages/shared/lib/core/new-profile/actions/recoverAccounts.ts delete mode 100644 packages/shared/lib/core/new-profile/actions/removeLatestAccount.ts create mode 100644 packages/shared/lib/core/profile/actions/createAccount.ts create mode 100644 packages/shared/lib/core/profile/actions/getAccount.ts rename packages/shared/lib/core/{new-profile => profile}/actions/getAccounts.ts (94%) create mode 100644 packages/shared/lib/core/profile/actions/recoverAccounts.ts diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts index 98e052bab4e..37bc60da1ba 100644 --- a/packages/shared/lib/core/api/interfaces/api.interface.ts +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -7,6 +7,7 @@ export interface IApi { createAccount(id: string, payload: WalletOptions): Promise deleteWallet(id: string): void getAccount(id: string, walletOptions: WalletOptions): Promise + clearWalletsFromMemory(): void migrateStrongholdSnapshotV2ToV3( currentPath: string, currentPassword: string, diff --git a/packages/shared/lib/core/new-profile/actions/createAccount.ts b/packages/shared/lib/core/new-profile/actions/createAccount.ts deleted file mode 100644 index 78752f07f13..00000000000 --- a/packages/shared/lib/core/new-profile/actions/createAccount.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { IAccount } from '@core/account' -import * as api from '@core/api/actions' -import { WalletOptions } from '@iota/sdk/out/types' - -export function createAccount(id: string, walletOptions: WalletOptions): Promise { - // TODO(2.0): Add all necessary wallet options here - return api.createAccount(id, walletOptions) -} diff --git a/packages/shared/lib/core/new-profile/actions/getAccount.ts b/packages/shared/lib/core/new-profile/actions/getAccount.ts deleted file mode 100644 index a8c487639f6..00000000000 --- a/packages/shared/lib/core/new-profile/actions/getAccount.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { get } from 'svelte/store' - -import { IAccount } from '@core/account' - -import { api } from '../../api/api' -import { profileManager } from '../stores' - -export function getAccount(index: number, manager = profileManager): Promise { - const { id } = get(manager) ?? {} - if (id) { - return api.getAccount(id, index) - } -} diff --git a/packages/shared/lib/core/new-profile/actions/recoverAccounts.ts b/packages/shared/lib/core/new-profile/actions/recoverAccounts.ts deleted file mode 100644 index 7c74c202138..00000000000 --- a/packages/shared/lib/core/new-profile/actions/recoverAccounts.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { get } from 'svelte/store' - -import { IAccount } from '@core/account' - -import { profileManager } from '../stores' -import { api } from '../../api' -import { RecoverAccountsPayload } from '../../api/interfaces' - -export function recoverAccounts( - recoverAccountsPayload: RecoverAccountsPayload, - manager = profileManager -): Promise { - const { id } = get(manager) - return api.recoverAccounts(id, recoverAccountsPayload) -} diff --git a/packages/shared/lib/core/new-profile/actions/removeLatestAccount.ts b/packages/shared/lib/core/new-profile/actions/removeLatestAccount.ts deleted file mode 100644 index 877feb5131f..00000000000 --- a/packages/shared/lib/core/new-profile/actions/removeLatestAccount.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { get } from 'svelte/store' - -import { profileManager } from '../stores' - -export async function removeLatestAccount(): Promise { - const manager = get(profileManager) - return manager.removeLatestAccount() -} diff --git a/packages/shared/lib/core/profile-manager/actions/deleteAccount.ts b/packages/shared/lib/core/profile-manager/actions/deleteAccount.ts index 9bd50dd4c0a..becc9933d9d 100644 --- a/packages/shared/lib/core/profile-manager/actions/deleteAccount.ts +++ b/packages/shared/lib/core/profile-manager/actions/deleteAccount.ts @@ -1,14 +1,15 @@ import { get } from 'svelte/store' import { setSelectedAccount } from '@core/account/actions' +import { api } from '@core/api' import { AppContext } from '@core/app/enums' -import { removeAccountFromActiveAccounts, visibleActiveAccounts } from '@core/profile/stores' import { CannotRemoveAccountError, RemoveNotLastAccountError } from '@core/profile-manager/errors' -import { removeLatestAccount } from '@core/profile-manager/api' +import { removeAccountFromActiveAccounts, visibleActiveAccounts } from '@core/profile/stores' import { routerManager } from '@core/router/stores' -export async function deleteAccount(index: number): Promise { - const accountToBeDeleted = get(visibleActiveAccounts).find((account) => account?.index === index) +// TODO(2.0): replace all its usage, before it was numeric index, now it's id +export async function deleteAccount(id: string): Promise { + const accountToBeDeleted = get(visibleActiveAccounts).find((account) => account?.id === id) const accounts = get(visibleActiveAccounts) if (accountToBeDeleted !== accounts[accounts.length - 1]) { @@ -16,8 +17,8 @@ export async function deleteAccount(index: number): Promise { } try { - await removeLatestAccount() - removeAccountFromActiveAccounts(index) + await api.deleteWallet(id) + removeAccountFromActiveAccounts(id) setSelectedAccount(get(visibleActiveAccounts)?.[0]?.index ?? null) get(routerManager).resetRouterForAppContext(AppContext.Dashboard) } catch (err) { diff --git a/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts b/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts index bbd9e108765..cfce3d1dbbf 100644 --- a/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts +++ b/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts @@ -1,9 +1,10 @@ import { get, Writable } from 'svelte/store' -import { api } from '../api' +import { api } from '@core/api' import { IProfileManager } from '../interfaces' import { profileManager } from '../stores' +// TODO(2.0): replace all its usage with api.clearWalletsFromMemory() export async function destroyProfileManager( _profileManager: Writable = profileManager ): Promise { @@ -11,6 +12,6 @@ export async function destroyProfileManager( if (!manager) return _profileManager.set(null) - api.deleteWallet(manager?.id) + api.clearWalletsFromMemory() await manager.destroy() } diff --git a/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts b/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts index 5772d8b9578..214ee1b0b37 100644 --- a/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts +++ b/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts @@ -33,7 +33,6 @@ export interface IProfileManager { hexToBech32(hex: string, bech32Hrp?: string): Promise listen(eventTypes: WalletEventType[], callback: WalletApiEventHandler): Promise clearListeners(eventTypes: WalletEventType[]): Promise - removeLatestAccount(): Promise restoreBackup( source: string, password: string, diff --git a/packages/shared/lib/core/profile/actions/createAccount.ts b/packages/shared/lib/core/profile/actions/createAccount.ts new file mode 100644 index 00000000000..fd61d197fa9 --- /dev/null +++ b/packages/shared/lib/core/profile/actions/createAccount.ts @@ -0,0 +1,36 @@ +import { IAccount } from '@core/account'; +import { api } from '@core/api'; +import { generateRandomId } from '@core/utils'; +import { get } from 'svelte/store'; +import { activeProfile as activeProfileStore } from '../stores'; +import { getStorageDirectoryOfProfile } from '../utils'; + +// TODO(2.0): Fix and finish this method +/* - __storage__/ + - profile_id_1 + - secret manager + - __wallet1__/ + - __wallet2__/ +*/ +export async function createAccount(): Promise { + const id = generateRandomId(); + const storagePath = await getStorageDirectoryOfProfile(id); + const snapshotPath = '' + + const activeProfile = get(activeProfileStore) + + const walletOptions = { + clientOptions: activeProfile.clientOptions, + secretManager: { + stronghold: { + snapshotPath, + } + }, + } + const wallet = api.createAccount(id, { + ...walletOptions, + storagePath + }); + + return wallet +} diff --git a/packages/shared/lib/core/profile/actions/getAccount.ts b/packages/shared/lib/core/profile/actions/getAccount.ts new file mode 100644 index 00000000000..7ca092c412d --- /dev/null +++ b/packages/shared/lib/core/profile/actions/getAccount.ts @@ -0,0 +1,13 @@ +import { get } from 'svelte/store' +import { IAccount, IPersistedAccountData } from '@core/account' +import { api } from '../../api/api' +import { IPersistedProfile } from '../interfaces' +import {activeProfile } from '../stores' + +// TODO(2.0): Fix all usages of this method, before numeric index, now string +export async function getAccount(id: string): Promise { + const profile: IPersistedProfile = get(activeProfile) + const persistedWallet: IPersistedAccountData = profile?.accountPersistedData[id] + const wallet = await api.getAccount(id, persistedWallet.walletOptions) + return wallet +} diff --git a/packages/shared/lib/core/new-profile/actions/getAccounts.ts b/packages/shared/lib/core/profile/actions/getAccounts.ts similarity index 94% rename from packages/shared/lib/core/new-profile/actions/getAccounts.ts rename to packages/shared/lib/core/profile/actions/getAccounts.ts index 32771b2eee7..6f6bc63dea6 100644 --- a/packages/shared/lib/core/new-profile/actions/getAccounts.ts +++ b/packages/shared/lib/core/profile/actions/getAccounts.ts @@ -1,7 +1,7 @@ import { IAccount } from '@core/account' +import { api } from '@core/api' import { activeProfile } from '@core/profile/stores' import { get } from 'svelte/store' -import { api } from '../../api/api' // TODO(2.0): Fix all usages of this method // TODO(2.0): Finalize when new profile is ready diff --git a/packages/shared/lib/core/profile/actions/index.ts b/packages/shared/lib/core/profile/actions/index.ts index 1cb1c299d84..26adafb2fb5 100644 --- a/packages/shared/lib/core/profile/actions/index.ts +++ b/packages/shared/lib/core/profile/actions/index.ts @@ -1,3 +1,8 @@ +export * from './createAccount' +export * from './getAccount' +export * from './getAccounts' +export * from './recoverAccounts' + export * from './active-accounts' export * from './active-profile' export * from './profiles' diff --git a/packages/shared/lib/core/profile/actions/recoverAccounts.ts b/packages/shared/lib/core/profile/actions/recoverAccounts.ts new file mode 100644 index 00000000000..9e320bde13b --- /dev/null +++ b/packages/shared/lib/core/profile/actions/recoverAccounts.ts @@ -0,0 +1,10 @@ +import { IAccount } from '@core/account' +import { RecoverAccountsPayload } from '@core/profile-manager/interfaces' + +// TODO(2.0): Refactor all this, recover accounts has changed completely +// as it is not provided by the SDK anymore +export function recoverAccounts( + _recoverAccountsPayload: RecoverAccountsPayload, +): Promise { + return Promise.resolve([]) +} diff --git a/packages/shared/lib/core/secret-manager/actions/index.ts b/packages/shared/lib/core/secret-manager/actions/index.ts index 4a10dba5cc4..06eb3e28fa3 100644 --- a/packages/shared/lib/core/secret-manager/actions/index.ts +++ b/packages/shared/lib/core/secret-manager/actions/index.ts @@ -10,7 +10,6 @@ export * from './getLedgerNanoStatus' export * from './getNodeInfo' export * from './isStrongholdUnlocked' export * from './recoverAccounts' -export * from './removeLatestAccount' export * from './restoreBackup' export * from './setClientOptions' export * from './setStrongholdPassword' diff --git a/packages/shared/lib/tests/__mocks__/profile-manager.mock.ts b/packages/shared/lib/tests/__mocks__/profile-manager.mock.ts index dbab0ecb4de..3a18dd3d5cc 100644 --- a/packages/shared/lib/tests/__mocks__/profile-manager.mock.ts +++ b/packages/shared/lib/tests/__mocks__/profile-manager.mock.ts @@ -159,10 +159,6 @@ export class ProfileManagerMock implements IProfileManager { return Promise.resolve([]) } - removeLatestAccount(): Promise { - throw new Error('Method not implemented.') - } - restoreBackup( source: string, password: string, From 751df16d51e71365e284235e96b9db9d3dbf0cde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bego=C3=B1a=20Alvarez?= Date: Thu, 23 Nov 2023 13:29:46 +0100 Subject: [PATCH 04/19] refactor(wip): refactor profilemanager core module --- .../modals/AccountActionsMenu.svelte | 4 +- .../popups/DeleteAccountPopup.svelte | 4 +- packages/desktop/electron/preload.js | 8 +- .../login/views/SelectProfileView.svelte | 4 +- .../views/ChooseCreateProfileFlowView.svelte | 4 +- .../views/ChooseRestoreProfileFlowView.svelte | 4 +- .../views/ChangePasswordView.svelte | 1 + .../cleanupOnboardingProfileManager.ts | 4 +- .../createShimmerClaimingProfileManager.ts | 1 + .../actions/deleteOnboardingProfile.ts | 4 +- .../destroyShimmerClaimingProfileManager.ts | 4 +- .../actions/initialiseOnboardingFlow.ts | 4 +- .../actions/initialiseOnboardingProfile.ts | 4 +- ...liseProfileManagerFromOnboardingProfile.ts | 37 ++++---- .../migrateStrongholdFromOnboardingProfile.ts | 4 +- .../onboarding-profile.interface.ts | 7 +- .../lib/contexts/onboarding/stores/index.ts | 1 + .../stores/onboarding-profile.store.ts | 5 +- .../stores/onboarding-secret-manager.store.ts | 17 ++++ .../account/interfaces/account.interface.ts | 28 ++++++ .../lib/core/api/interfaces/api.interface.ts | 1 + .../core/network/interfaces/auth.interface.ts | 4 - .../lib/core/network/interfaces/index.ts | 1 - .../actions/destroyProfileManager.ts | 17 ---- .../lib/core/profile-manager/actions/index.ts | 8 -- .../actions/initialiseProfileManager.ts | 87 ------------------- .../actions/subscribeToWalletApiEvents.ts | 13 --- .../actions/unsubscribeFromWalletApiEvents.ts | 10 --- .../lib/core/profile-manager/errors/index.ts | 6 -- .../remove-account-with-balance.error.ts | 8 -- .../core/profile-manager/interfaces/index.ts | 5 -- .../interfaces/profile-manager.interface.ts | 47 ---------- .../lib/core/profile-manager/stores/index.ts | 1 - .../stores/profile-manager.store.ts | 8 -- .../lib/core/profile-manager/types/index.ts | 4 - .../types/profile-manager-options.type.ts | 6 -- .../types/transaction-progress-event.type.ts | 18 ---- ...ildProfileManagerOptionsFromProfileData.ts | 9 +- .../lib/core/profile-manager/utils/index.ts | 1 - .../profile/actions/active-profile/logout.ts | 4 +- .../changePasswordAndUnlockStronghold.ts | 0 .../profile/actions/clearProfileFromMemory.ts | 5 ++ .../actions/deleteAccount.ts | 2 +- .../shared/lib/core/profile/actions/index.ts | 2 + .../lib/core/profile/interfaces/index.ts | 1 + .../interfaces/persisted-profile.interface.ts | 2 + .../recover-account-payload.interface.ts | 0 .../profile/stores/active-profile-id.store.ts | 2 +- .../actions/changeStrongholdPassword.ts | 8 ++ .../actions/clearStrongholdPassword.ts | 7 ++ .../actions/generateEd25519Address.ts | 25 ++++++ .../actions/getLedgerNanoStatus.ts | 12 +++ .../lib/core/secret-manager/actions/index.ts | 20 +---- .../secret-manager/actions/storeMnemonic.ts | 11 +++ .../shared/lib/core/secret-manager/index.ts | 2 + .../lib/core/secret-manager/stores/index.ts | 1 + .../stores/secret-manager.store.ts | 17 ++++ .../actions/changeStrongholdPassword.ts | 7 -- .../wallet/actions/clearStrongholdPassword.ts | 8 -- .../events-handlers/handleNewOutputEvent.ts | 9 +- .../events-handlers/handleSpentOutputEvent.ts | 2 +- .../handleTransactionInclusionEvent.ts | 2 +- .../handleTransactionProgressEvent.ts | 17 ++-- .../actions/events-handlers/index.ts | 0 .../wallet/actions/getLedgerNanoStatus.ts | 8 -- .../shared/lib/core/wallet/actions/index.ts | 6 +- .../lib/core/wallet/actions/storeMnemonic.ts | 7 -- .../actions/subscribeToWalletApiEvents.ts | 15 ++++ .../actions/unsubscribeFromWalletApiEvents.ts | 10 +++ .../errors/cannot-remove-account.error.ts | 0 .../shared/lib/core/wallet/errors/index.ts | 5 ++ ...ransaction-progress-event-payload.error.ts | 0 .../errors/remove-not-last-account.error.ts | 0 .../wallet-api-event-validation.error.ts | 0 .../errors/wallet-api-event.error.ts | 0 .../lib/core/wallet/interfaces/index.ts | 2 + ...let-api-event-payload-wrapper.interface.ts | 0 ...nt-subscription-configuration.interface.ts | 5 +- .../tests/old-profile-manager-api.test.ts} | 7 +- .../shared/lib/core/wallet/types/index.ts | 2 + .../types/wallet-api-event-handler.type.ts | 0 .../types/wallet-api-event-map.type.ts | 0 .../shared/lib/core/wallet/utils/index.ts | 1 + .../utils/validateWalletApiEvent.ts | 0 84 files changed, 272 insertions(+), 365 deletions(-) create mode 100644 packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts delete mode 100644 packages/shared/lib/core/network/interfaces/auth.interface.ts delete mode 100644 packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts delete mode 100644 packages/shared/lib/core/profile-manager/actions/index.ts delete mode 100644 packages/shared/lib/core/profile-manager/actions/initialiseProfileManager.ts delete mode 100644 packages/shared/lib/core/profile-manager/actions/subscribeToWalletApiEvents.ts delete mode 100644 packages/shared/lib/core/profile-manager/actions/unsubscribeFromWalletApiEvents.ts delete mode 100644 packages/shared/lib/core/profile-manager/errors/index.ts delete mode 100644 packages/shared/lib/core/profile-manager/errors/remove-account-with-balance.error.ts delete mode 100644 packages/shared/lib/core/profile-manager/interfaces/index.ts delete mode 100644 packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts delete mode 100644 packages/shared/lib/core/profile-manager/stores/index.ts delete mode 100644 packages/shared/lib/core/profile-manager/stores/profile-manager.store.ts delete mode 100644 packages/shared/lib/core/profile-manager/types/index.ts delete mode 100644 packages/shared/lib/core/profile-manager/types/profile-manager-options.type.ts delete mode 100644 packages/shared/lib/core/profile-manager/types/transaction-progress-event.type.ts rename packages/shared/lib/core/{profile-manager => profile}/actions/changePasswordAndUnlockStronghold.ts (100%) create mode 100644 packages/shared/lib/core/profile/actions/clearProfileFromMemory.ts rename packages/shared/lib/core/{profile-manager => profile}/actions/deleteAccount.ts (94%) rename packages/shared/lib/core/{profile-manager => profile}/interfaces/recover-account-payload.interface.ts (100%) create mode 100644 packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts create mode 100644 packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts create mode 100644 packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts create mode 100644 packages/shared/lib/core/secret-manager/actions/getLedgerNanoStatus.ts create mode 100644 packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts create mode 100644 packages/shared/lib/core/secret-manager/index.ts create mode 100644 packages/shared/lib/core/secret-manager/stores/index.ts create mode 100644 packages/shared/lib/core/secret-manager/stores/secret-manager.store.ts delete mode 100644 packages/shared/lib/core/wallet/actions/changeStrongholdPassword.ts delete mode 100644 packages/shared/lib/core/wallet/actions/clearStrongholdPassword.ts rename packages/shared/lib/core/{profile-manager => wallet}/actions/events-handlers/handleNewOutputEvent.ts (91%) rename packages/shared/lib/core/{profile-manager => wallet}/actions/events-handlers/handleSpentOutputEvent.ts (97%) rename packages/shared/lib/core/{profile-manager => wallet}/actions/events-handlers/handleTransactionInclusionEvent.ts (98%) rename packages/shared/lib/core/{profile-manager => wallet}/actions/events-handlers/handleTransactionProgressEvent.ts (87%) rename packages/shared/lib/core/{profile-manager => wallet}/actions/events-handlers/index.ts (100%) delete mode 100644 packages/shared/lib/core/wallet/actions/getLedgerNanoStatus.ts delete mode 100644 packages/shared/lib/core/wallet/actions/storeMnemonic.ts create mode 100644 packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts create mode 100644 packages/shared/lib/core/wallet/actions/unsubscribeFromWalletApiEvents.ts rename packages/shared/lib/core/{profile-manager => wallet}/errors/cannot-remove-account.error.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/errors/missing-transaction-progress-event-payload.error.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/errors/remove-not-last-account.error.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/errors/wallet-api-event-validation.error.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/errors/wallet-api-event.error.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/interfaces/wallet-api-event-payload-wrapper.interface.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/interfaces/wallet-api-event-subscription-configuration.interface.ts (58%) rename packages/shared/lib/core/{profile-manager/tests/api.test.ts => wallet/tests/old-profile-manager-api.test.ts} (95%) rename packages/shared/lib/core/{profile-manager => wallet}/types/wallet-api-event-handler.type.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/types/wallet-api-event-map.type.ts (100%) rename packages/shared/lib/core/{profile-manager => wallet}/utils/validateWalletApiEvent.ts (100%) diff --git a/packages/desktop/components/modals/AccountActionsMenu.svelte b/packages/desktop/components/modals/AccountActionsMenu.svelte index 691e11a08bf..e5e6e4e29d8 100644 --- a/packages/desktop/components/modals/AccountActionsMenu.svelte +++ b/packages/desktop/components/modals/AccountActionsMenu.svelte @@ -4,7 +4,7 @@ import { selectedAccount } from '@core/account/stores' import { localize } from '@core/i18n' import { activeAccounts, activeProfile, isActiveLedgerProfile, visibleActiveAccounts } from '@core/profile/stores' - import { deleteAccount } from '@core/profile-manager/actions' + import { deleteWallet } from '@core/profile-manager/actions' import { Icon } from '@auxiliary/icon/enums' import { openPopup, PopupId } from '@auxiliary/popup' @@ -62,7 +62,7 @@ id: PopupId.DeleteAccount, props: { account: selectedAccount, - deleteAccount, + deleteWallet, }, }) modal?.close() diff --git a/packages/desktop/components/popups/DeleteAccountPopup.svelte b/packages/desktop/components/popups/DeleteAccountPopup.svelte index a324506393b..485ce49a9bf 100644 --- a/packages/desktop/components/popups/DeleteAccountPopup.svelte +++ b/packages/desktop/components/popups/DeleteAccountPopup.svelte @@ -8,7 +8,7 @@ import { handleError } from '@core/error/handlers/handleError' import { TextHintVariant } from 'shared/components/enums' - export let deleteAccount: (index: number) => Promise = async () => {} + export let deleteWallet: (index: number) => Promise = async () => {} let password: string let error: string @@ -26,7 +26,7 @@ if ($isSoftwareProfile) { await setStrongholdPassword(password) } - await deleteAccount($selectedAccount?.index) + await deleteWallet($selectedAccount?.index) closePopup() } catch (err) { error = err.error diff --git a/packages/desktop/electron/preload.js b/packages/desktop/electron/preload.js index 51693fbc8c6..601f8f285a8 100644 --- a/packages/desktop/electron/preload.js +++ b/packages/desktop/electron/preload.js @@ -124,6 +124,8 @@ try { // TODO(2.0): also remove from file system deleteWallet(id) { if (id && id in wallets) { + const wallet = wallets[id] + wallet.destroy() delete wallets[id] } }, @@ -145,7 +147,11 @@ try { return accounts }, clearWalletsFromMemory() { - Object.keys(wallets).forEach((id) => delete wallets[id]) + Object.keys(wallets).forEach((id) => { + const wallet = wallets[id] + wallet.destroy() + delete wallets[id] + }) }, async migrateStrongholdSnapshotV2ToV3(currentPath, newPath, currentPassword, newPassword) { const snapshotSaltV2 = 'wallet.rs' diff --git a/packages/desktop/views/login/views/SelectProfileView.svelte b/packages/desktop/views/login/views/SelectProfileView.svelte index d2130ea056d..596185dd7cb 100644 --- a/packages/desktop/views/login/views/SelectProfileView.svelte +++ b/packages/desktop/views/login/views/SelectProfileView.svelte @@ -9,7 +9,7 @@ } from '@core/app' import { localize } from '@core/i18n' import { ProfileType, loadPersistedProfileIntoActiveProfile, profiles, removeProfileFolder } from '@core/profile' - import { destroyProfileManager } from '@core/profile-manager/actions' + import { clearProfileFromMemory } from '@core/profile-manager/actions' import { loginRouter, routerManager } from '@core/router' import features from '@features/features' import { Icon, Logo, Profile } from '@ui' @@ -41,7 +41,7 @@ // Clean up if user has navigated back to this view from onboarding if ($onboardingProfile) { if ($onboardingProfile.hasInitialisedProfileManager) { - await destroyProfileManager() + await clearProfileFromMemory() await removeProfileFolder($onboardingProfile.id) } $onboardingProfile = undefined diff --git a/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte b/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte index da3c9189231..a84a87f6ad5 100644 --- a/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte +++ b/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte @@ -12,7 +12,7 @@ import { Animation, OnboardingButton, Text } from '@ui' import { onMount } from 'svelte' import { createProfileRouter } from '../create-profile-router' - import { destroyProfileManager } from '@core/profile-manager/actions' + import { clearProfileFromMemory } from '@core/profile-manager/actions' import { Icon as IconEnum } from '@auxiliary/icon' import { AnimationEnum } from '@auxiliary/animation' @@ -40,7 +40,7 @@ onMount(async () => { // Clean up if user has navigated back to this view if ($onboardingProfile.hasInitialisedProfileManager) { - await destroyProfileManager() + await clearProfileFromMemory() await removeProfileFolder($onboardingProfile.id) } updateOnboardingProfile({ type: undefined, createProfileType: undefined, hasInitialisedProfileManager: false }) diff --git a/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte b/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte index d1f29a7e3f2..869b6a900e3 100644 --- a/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte +++ b/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte @@ -13,7 +13,7 @@ import { Animation, OnboardingButton, Text } from '@ui' import { onMount } from 'svelte' import { restoreProfileRouter } from '../restore-profile-router' - import { destroyProfileManager } from '@core/profile-manager/actions' + import { clearProfileFromMemory } from '@core/profile-manager/actions' import { Icon as IconEnum } from '@auxiliary/icon' import { AnimationEnum } from '@auxiliary/animation' @@ -42,7 +42,7 @@ onMount(async () => { // Clean up if user has navigated back to this view if ($onboardingProfile.hasInitialisedProfileManager) { - await destroyProfileManager() + await clearProfileFromMemory() await removeProfileFolder($onboardingProfile.id) } updateOnboardingProfile({ type: undefined, restoreProfileType: undefined, hasInitialisedProfileManager: false }) diff --git a/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte b/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte index abdb32375ec..0e2f330d8e9 100644 --- a/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte +++ b/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte @@ -104,6 +104,7 @@ const profileManagerOptions = await buildProfileManagerOptionsFromProfileData($activeProfile) const { storagePath, coinType, clientOptions, secretManager } = profileManagerOptions updateActiveProfile({ clientOptions }) + // TODO(2.0): Update initialiseProfileManager to new logic const manager = await initialiseProfileManager( $activeProfile?.id, storagePath, diff --git a/packages/shared/lib/contexts/onboarding/actions/cleanupOnboardingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/cleanupOnboardingProfileManager.ts index bd48627e29e..c2d9eee2a27 100644 --- a/packages/shared/lib/contexts/onboarding/actions/cleanupOnboardingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/cleanupOnboardingProfileManager.ts @@ -1,6 +1,6 @@ import { get } from 'svelte/store' -import { destroyProfileManager, profileManager } from '@core/profile-manager' +import { clearProfileFromMemory, profileManager } from '@core/profile-manager' import { removeProfileFolder } from '@core/profile' export async function cleanupOnboardingProfileManager(): Promise { @@ -10,6 +10,6 @@ export async function cleanupOnboardingProfileManager(): Promise { const { id } = get(profileManager) - await destroyProfileManager() + await clearProfileFromMemory() await removeProfileFolder(id) } diff --git a/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts index b64d522667a..a8a5dd1ae8f 100644 --- a/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts @@ -18,6 +18,7 @@ export async function createShimmerClaimingProfileManager(): Promise { const clientOptions = $onboardingProfile?.clientOptions const secretManager = getSecretManagerFromProfileType($onboardingProfile?.type, storagePath) + // TODO(2.0): Fix all shimmer claiming const manager = await initialiseProfileManager( generateRandomId(), storagePath, diff --git a/packages/shared/lib/contexts/onboarding/actions/deleteOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/deleteOnboardingProfile.ts index fd2435dc354..30dc05790be 100644 --- a/packages/shared/lib/contexts/onboarding/actions/deleteOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/deleteOnboardingProfile.ts @@ -1,4 +1,4 @@ -import { destroyProfileManager } from '@core/profile-manager' +import { clearProfileFromMemory } from '@core/profile-manager' import { get } from 'svelte/store' import { onboardingProfile } from '../stores' import { removeProfileFolder } from '@core/profile/utils' @@ -12,7 +12,7 @@ export async function deleteOnboardingProfile(): Promise { const profile = get(onboardingProfile) if (profile) { try { - await destroyProfileManager() + await clearProfileFromMemory() await removeProfileFolder(profile.id) } catch (err) { console.error(err) diff --git a/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts index 126ea5f66ae..27d7addafe2 100644 --- a/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts @@ -1,6 +1,6 @@ import { get } from 'svelte/store' -import { destroyProfileManager } from '@core/profile-manager' +import { clearProfileFromMemory } from '@core/profile-manager' import { Platform } from '@core/app' import { getTemporaryProfileManagerStorageDirectory } from '../helpers' @@ -11,7 +11,7 @@ export async function destroyShimmerClaimingProfileManager(): Promise { if (!_shimmerClaimingProfileManager) { return } - await destroyProfileManager(shimmerClaimingProfileManager) + await clearProfileFromMemory(shimmerClaimingProfileManager) const profilePath = await getTemporaryProfileManagerStorageDirectory() await Platform.removeProfileFolder(profilePath) } diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingFlow.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingFlow.ts index db127e5499d..87191b532b9 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingFlow.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingFlow.ts @@ -3,7 +3,7 @@ import { get } from 'svelte/store' import { stopPollingLedgerNanoStatus } from '@core/ledger/actions' import { isPollingLedgerDeviceStatus } from '@core/ledger/stores' import { getDefaultPersistedNetwork } from '@core/network/utils' -import { destroyProfileManager, unsubscribeFromWalletApiEvents } from '@core/profile-manager/actions' +import { clearProfileFromMemory, unsubscribeFromWalletApiEvents } from '@core/profile-manager/actions' import { resetActiveProfile } from '@core/profile/actions' import { IOnboardingInitialisationOptions } from '../interfaces' @@ -20,7 +20,7 @@ export async function initialiseOnboardingFlow(options: IOnboardingInitialisatio stopPollingLedgerNanoStatus() } await unsubscribeFromWalletApiEvents() - await destroyProfileManager() + await clearProfileFromMemory() const { isDeveloperProfile, networkId } = options diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts index d9be8aa7e1c..d8f15d2035e 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts @@ -1,5 +1,5 @@ import { stopPollingLedgerNanoStatus } from '@core/ledger' -import { destroyProfileManager, profileManager } from '@core/profile-manager' +import { clearProfileFromMemory, profileManager } from '@core/profile-manager' import { get } from 'svelte/store' import { OnboardingProfileManagerAlreadyInitializedError } from '../errors' import { buildInitialOnboardingProfile } from '../helpers' @@ -17,7 +17,7 @@ export async function initialiseOnboardingProfile( if (get(isOnboardingLedgerProfile)) { stopPollingLedgerNanoStatus() } - await destroyProfileManager() + await clearProfileFromMemory() } else { throw new OnboardingProfileManagerAlreadyInitializedError() } diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseProfileManagerFromOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseProfileManagerFromOnboardingProfile.ts index b4672f674fc..f3bdf8a45fe 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseProfileManagerFromOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseProfileManagerFromOnboardingProfile.ts @@ -1,29 +1,32 @@ import { get } from 'svelte/store' import { - buildProfileManagerOptionsFromProfileData, - initialiseProfileManager, - profileManager, + getSecretManagerFromProfileType } from '@core/profile-manager' +import { onboardingProfileSecretManager } from '../stores' +import { getStorageDirectoryOfProfile, removeProfileFolder } from '@core/profile' import { onboardingProfile, updateOnboardingProfile } from '../stores' -import { removeProfileFolder } from '@core/profile' - -export async function initialiseProfileManagerFromOnboardingProfile(checkForExistingManager?: boolean): Promise { - const existingManager = get(profileManager) - if (existingManager) { - if (!checkForExistingManager) { - await existingManager.destroy() - removeProfileFolder(existingManager.id) + +export async function initialiseProfileManagerFromOnboardingProfile(checkForExistingSecretManager?: boolean): Promise { + const secretManager = get(onboardingProfileSecretManager) + const activeOnboardingProfile = get(onboardingProfile) + + if (!activeOnboardingProfile) { + return + } + + if (secretManager) { + if (!checkForExistingSecretManager) { + removeProfileFolder(activeOnboardingProfile.id) } else { return } } - const profileManagerOptions = await buildProfileManagerOptionsFromProfileData(get(onboardingProfile)) - const { storagePath, coinType, clientOptions, secretManager } = profileManagerOptions - const { id } = get(onboardingProfile) - const manager = await initialiseProfileManager(id, storagePath, coinType, clientOptions, secretManager) - profileManager.set(manager) - updateOnboardingProfile({ hasInitialisedProfileManager: true }) + const storagePath = await getStorageDirectoryOfProfile(activeOnboardingProfile.id) + + const secretManagerOptions = getSecretManagerFromProfileType(activeOnboardingProfile.type, storagePath) + + updateOnboardingProfile({ secretManagerOptions, hasInitialisedProfileManager: true }) } diff --git a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts index bc89a960054..9f1d68198cd 100644 --- a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts @@ -1,7 +1,7 @@ import { get } from 'svelte/store' import { getStorageDirectoryOfProfile } from '@core/profile/utils' -import { destroyProfileManager } from '@core/profile-manager/actions' +import { clearProfileFromMemory } from '@core/profile-manager/actions' import { api } from '@core/profile-manager/api' import { getSecretManagerPath } from '@core/profile-manager/utils' import { StrongholdVersion } from '@core/stronghold/enums' @@ -23,6 +23,6 @@ export async function migrateStrongholdFromOnboardingProfile(password: string): updateOnboardingProfile({ strongholdVersion: StrongholdVersion.V3 }) } - await destroyProfileManager() + await clearProfileFromMemory() await initialiseProfileManagerFromOnboardingProfile() } diff --git a/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts b/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts index 965cf55bdf3..1744dc321d0 100644 --- a/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts +++ b/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts @@ -1,9 +1,12 @@ -import { IPersistedProfile } from '@core/profile' +import { IPersistedProfile, ProfileType } from '@core/profile' import { CreateProfileType, OnboardingType, RestoreProfileType } from '../enums' import { ImportFile, Mnemonic } from '../types' import { IShimmerClaimingAccount } from './shimmer-claiming-account.interface' -export interface IOnboardingProfile extends IPersistedProfile { +export interface IOnboardingProfile extends Omit, 'id' | 'type'> { + id: string, + type: ProfileType + // Onboarding flow indicators onboardingType?: OnboardingType createProfileType?: CreateProfileType diff --git a/packages/shared/lib/contexts/onboarding/stores/index.ts b/packages/shared/lib/contexts/onboarding/stores/index.ts index d46fbb5aa00..d8a20c14a30 100644 --- a/packages/shared/lib/contexts/onboarding/stores/index.ts +++ b/packages/shared/lib/contexts/onboarding/stores/index.ts @@ -1,3 +1,4 @@ export * from './onboarding-profile.store' +export * from './onboarding-secret-manager.store' export * from './shimmer-claiming-profile-manager.store' export * from './shimmer-claiming-transactions.store' diff --git a/packages/shared/lib/contexts/onboarding/stores/onboarding-profile.store.ts b/packages/shared/lib/contexts/onboarding/stores/onboarding-profile.store.ts index 05bb340800d..bee74ec4aa0 100644 --- a/packages/shared/lib/contexts/onboarding/stores/onboarding-profile.store.ts +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-profile.store.ts @@ -1,12 +1,13 @@ import { derived, get, Readable, writable } from 'svelte/store' -import { isLedgerProfile } from '@core/profile' +import { isLedgerProfile, ProfileType } from '@core/profile' import { IOnboardingProfile, IShimmerClaimingAccount } from '../interfaces' import { IBaseToken } from '@core/wallet/interfaces' import { IPersistedNetwork } from '@core/network' -export const onboardingProfile = writable>(null) + +export const onboardingProfile = writable(null) export const isOnboardingLedgerProfile: Readable = derived(onboardingProfile, ($onboardingProfile) => isLedgerProfile($onboardingProfile?.type) diff --git a/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts b/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts new file mode 100644 index 00000000000..02074f07692 --- /dev/null +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts @@ -0,0 +1,17 @@ +import { onboardingProfile } from '@contexts/onboarding/stores'; +import { api } from '@core/api'; +import { SecretManager } from '@iota/sdk'; +import { Readable, derived } from 'svelte/store'; + +const onboardingProfileSecretManagerOptions = derived(onboardingProfile, (onboardingProfile) => onboardingProfile.secretManagerOptions); + +export const onboardingProfileSecretManager: Readable = derived(onboardingProfileSecretManagerOptions, (onboardingProfileSecretManagerOptions, set) => { + if (onboardingProfileSecretManagerOptions) { + api.createSecretManager(onboardingProfileSecretManagerOptions) + .then((secretManager) => { + set(secretManager) + }) + } else { + set(null) + } +}) diff --git a/packages/shared/lib/core/account/interfaces/account.interface.ts b/packages/shared/lib/core/account/interfaces/account.interface.ts index e7f368b778a..553cdca5c94 100644 --- a/packages/shared/lib/core/account/interfaces/account.interface.ts +++ b/packages/shared/lib/core/account/interfaces/account.interface.ts @@ -35,8 +35,21 @@ import type { ParticipationEventType, ParticipationEventId, Burn, + WalletEventType, + IAuth, } from '@iota/sdk/out/types' +import type { + IClientOptions, + GenerateAddressOptions, + LedgerNanoStatus, + INodeInfoWrapper, + SyncOptions, + WalletEvent, + WalletEventType, +} from '@iota/sdk/out/types' +import { WalletApiEventHandler } from '@core/wallet' +// TODO(2.0): rename to IWallet & check all functions in this interface to make sure they still exist export interface IAccount { isStrongholdPasswordAvailable(): Promise getClient(): Promise @@ -118,4 +131,19 @@ export interface IAccount { transactions(): Promise unspentOutputs(filterOptions?: FilterOptions): Promise prepareVote(eventId?: string, answers?: number[]): Promise + listen(eventTypes: WalletEventType[], callback: WalletApiEventHandler): Promise + clearListeners(eventTypes: WalletEventType[]): Promise + backup(destination: string, password: string): Promise + destroy(): Promise + emitTestEvent(event: WalletEvent): Promise + restoreBackup( + source: string, + password: string, + ignoreIfCoinTypeMismatch: boolean, + ignoreIfBech32Mismatch: string + ): Promise + setClientOptions(options: IClientOptions): Promise + startBackgroundSync(options?: SyncOptions, intervalInMilliseconds?: number): Promise + stopBackgroundSync(): Promise + updateNodeAuth(url: string, auth?: IAuth): Promise } diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts index 37bc60da1ba..c1af960209e 100644 --- a/packages/shared/lib/core/api/interfaces/api.interface.ts +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -2,6 +2,7 @@ import { IAccount } from '@core/account' import { SecretManager } from '@iota/sdk' import { AccountId, FoundryId, HexEncodedString, NftId, Output, OutputId, SecretManagerType, TransactionId, WalletOptions, Bech32Address } from '@iota/sdk/out/types' +// TODO(2.0): Every method should return a promise (maybe except Utils, needs research) export interface IApi { createSecretManager(options: SecretManagerType): Promise createAccount(id: string, payload: WalletOptions): Promise diff --git a/packages/shared/lib/core/network/interfaces/auth.interface.ts b/packages/shared/lib/core/network/interfaces/auth.interface.ts deleted file mode 100644 index 026e8f8afdd..00000000000 --- a/packages/shared/lib/core/network/interfaces/auth.interface.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface IAuth { - jwt?: string - basicAuthNamePwd?: [string, string] -} diff --git a/packages/shared/lib/core/network/interfaces/index.ts b/packages/shared/lib/core/network/interfaces/index.ts index 228da613644..d9244a4e24a 100644 --- a/packages/shared/lib/core/network/interfaces/index.ts +++ b/packages/shared/lib/core/network/interfaces/index.ts @@ -1,4 +1,3 @@ -export * from './auth.interface' export * from './chain-metadata.interface' export * from './connected-chain.interface' export * from './client-options.interface' diff --git a/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts b/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts deleted file mode 100644 index cfce3d1dbbf..00000000000 --- a/packages/shared/lib/core/profile-manager/actions/destroyProfileManager.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { get, Writable } from 'svelte/store' - -import { api } from '@core/api' -import { IProfileManager } from '../interfaces' -import { profileManager } from '../stores' - -// TODO(2.0): replace all its usage with api.clearWalletsFromMemory() -export async function destroyProfileManager( - _profileManager: Writable = profileManager -): Promise { - const manager = get(_profileManager) - if (!manager) return - - _profileManager.set(null) - api.clearWalletsFromMemory() - await manager.destroy() -} diff --git a/packages/shared/lib/core/profile-manager/actions/index.ts b/packages/shared/lib/core/profile-manager/actions/index.ts deleted file mode 100644 index 57b2bde5829..00000000000 --- a/packages/shared/lib/core/profile-manager/actions/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * from './events-handlers' - -export * from './changePasswordAndUnlockStronghold' -export * from './deleteAccount' -export * from './destroyProfileManager' -export * from './initialiseProfileManager' -export * from './subscribeToWalletApiEvents' -export * from './unsubscribeFromWalletApiEvents' diff --git a/packages/shared/lib/core/profile-manager/actions/initialiseProfileManager.ts b/packages/shared/lib/core/profile-manager/actions/initialiseProfileManager.ts deleted file mode 100644 index 480c13a13b6..00000000000 --- a/packages/shared/lib/core/profile-manager/actions/initialiseProfileManager.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { IClientOptions, CoinType, SecretManagerType, GenerateAddressOptions, Bip44 } from '@iota/sdk/out/types' - -import { generateRandomId } from '@core/utils' - -import { IProfileManager } from '../interfaces' -import { api } from '../api'; -import { SecretManager } from '@iota/sdk'; - -// TODO: Rename this to something like WalletManager or whatever -class ProfileManager { - storagePath: string; - clientOptions?: IClientOptions; - secretManager?: SecretManagerType; - secretManagerBind?: SecretManager; - bipPath: Bip44 - id: string - - constructor( storagePath: string, - id: string, - secretManager?: SecretManagerType, - clientOptions?: IClientOptions, - coinType?: CoinType, - secretManagerBind?: SecretManager -){ - this.id = id; - this.storagePath = storagePath; - this.clientOptions = clientOptions; - this.bipPath = { - coinType: coinType - } - this.secretManager = secretManager; - this.secretManagerBind = secretManagerBind; - } - - async generateEd25519Address( - accountIndex: number, - options: GenerateAddressOptions, - bech32Hrp: string - ): Promise { - if(!this.secretManager){ - return undefined - } - // Ledger secret manager doesn't support this - return (await this.secretManagerBind?.generateEd25519Addresses({ - accountIndex, options, bech32Hrp, - range: { - start: 0, - end: 1, - }, - }))[0] - } - - async storeMnemonic(mnemonic: string): Promise { - return this.secretManagerBind?.storeMnemonic(mnemonic) - } - - getSecretManagerOptions(){ - return { - storagePath: this.storagePath, - clientOptions: this.clientOptions, - bipPath: this.bipPath, - secretManager: this.secretManager - } - } -} - -export async function initialiseProfileManager( - id: string, - storagePath: string, - coinType: CoinType, - clientOptions?: IClientOptions, - secretManager?: SecretManagerType, -): Promise { - - const secretManagerBind = await api.createSecretManager(secretManager); - - const profileManager = new ProfileManager( - storagePath, - id, - secretManager, - clientOptions, - coinType, - secretManagerBind - ); - - return profileManager as unknown as IProfileManager; -} diff --git a/packages/shared/lib/core/profile-manager/actions/subscribeToWalletApiEvents.ts b/packages/shared/lib/core/profile-manager/actions/subscribeToWalletApiEvents.ts deleted file mode 100644 index 72a912ff955..00000000000 --- a/packages/shared/lib/core/profile-manager/actions/subscribeToWalletApiEvents.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { get } from 'svelte/store' - -import { IWalletApiEventSubscriptionConfiguration } from '../interfaces' -import { profileManager as _profileManager } from '../stores' - -export function subscribeToWalletApiEvents(configuration: IWalletApiEventSubscriptionConfiguration): void { - const { eventMap, profileManager } = configuration - const manager = profileManager ?? get(_profileManager) - Object.entries(eventMap).forEach(([event, callback]) => { - const eventId = Number(event) - void manager.listen([eventId], callback) - }) -} diff --git a/packages/shared/lib/core/profile-manager/actions/unsubscribeFromWalletApiEvents.ts b/packages/shared/lib/core/profile-manager/actions/unsubscribeFromWalletApiEvents.ts deleted file mode 100644 index 60fe4553e5f..00000000000 --- a/packages/shared/lib/core/profile-manager/actions/unsubscribeFromWalletApiEvents.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { get, Writable } from 'svelte/store' - -import { IProfileManager } from '../interfaces' -import { profileManager as _profileManager } from '../stores' - -export async function unsubscribeFromWalletApiEvents( - profileManager: Writable = _profileManager -): Promise { - await get(profileManager)?.clearListeners([]) -} diff --git a/packages/shared/lib/core/profile-manager/errors/index.ts b/packages/shared/lib/core/profile-manager/errors/index.ts deleted file mode 100644 index 112c40b4b11..00000000000 --- a/packages/shared/lib/core/profile-manager/errors/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './cannot-remove-account.error' -export * from './missing-transaction-progress-event-payload.error' -export * from './remove-account-with-balance.error' -export * from './remove-not-last-account.error' -export * from './wallet-api-event.error' -export * from './wallet-api-event-validation.error' diff --git a/packages/shared/lib/core/profile-manager/errors/remove-account-with-balance.error.ts b/packages/shared/lib/core/profile-manager/errors/remove-account-with-balance.error.ts deleted file mode 100644 index 91f132c2e50..00000000000 --- a/packages/shared/lib/core/profile-manager/errors/remove-account-with-balance.error.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { BaseError } from '@core/error' -import { localize } from '@core/i18n' - -export class RemoveAccountWithBalanceError extends BaseError { - constructor() { - super({ message: localize('error.account.withBalance'), logToConsole: true }) - } -} diff --git a/packages/shared/lib/core/profile-manager/interfaces/index.ts b/packages/shared/lib/core/profile-manager/interfaces/index.ts deleted file mode 100644 index 203468b41cf..00000000000 --- a/packages/shared/lib/core/profile-manager/interfaces/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from '../../api/interfaces/api.interface' -export * from './profile-manager.interface' -export * from './recover-account-payload.interface' -export * from './wallet-api-event-payload-wrapper.interface' -export * from './wallet-api-event-subscription-configuration.interface' diff --git a/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts b/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts deleted file mode 100644 index 214ee1b0b37..00000000000 --- a/packages/shared/lib/core/profile-manager/interfaces/profile-manager.interface.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { - IClientOptions, - GenerateAddressOptions, - LedgerNanoStatus, - INodeInfoWrapper, - SyncOptions, - WalletEvent, - WalletEventType, -} from '@iota/sdk/out/types' - -import { IAccount } from '@core/account/interfaces' -import { IAuth } from '@core/network/interfaces' - -import { WalletApiEventHandler } from '../types' - -export interface IProfileManager { - id: string - getSecretManagerOptions(): any, // TODO: Use proper type - backup(destination: string, password: string): Promise - bech32ToHex(bech32Address: string): Promise - destroy(): Promise - emitTestEvent(event: WalletEvent): Promise - generateEd25519Address( - accountIndex: number, - options?: GenerateAddressOptions, - bech32Hrp?: string - ): Promise - getAccountIndexes(): Promise - getAccount(accountIndex: number): Promise - getAccounts(): Promise - getNodeInfo(url?: string, auth?: IAuth): Promise - getLedgerNanoStatus(): Promise - hexToBech32(hex: string, bech32Hrp?: string): Promise - listen(eventTypes: WalletEventType[], callback: WalletApiEventHandler): Promise - clearListeners(eventTypes: WalletEventType[]): Promise - restoreBackup( - source: string, - password: string, - ignoreIfCoinTypeMismatch: boolean, - ignoreIfBech32Mismatch: string - ): Promise - setClientOptions(options: IClientOptions): Promise - startBackgroundSync(options?: SyncOptions, intervalInMilliseconds?: number): Promise - stopBackgroundSync(): Promise - storeMnemonic(mnemonic: string): Promise - updateNodeAuth(url: string, auth?: IAuth): Promise -} diff --git a/packages/shared/lib/core/profile-manager/stores/index.ts b/packages/shared/lib/core/profile-manager/stores/index.ts deleted file mode 100644 index e666a8b5b7e..00000000000 --- a/packages/shared/lib/core/profile-manager/stores/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './profile-manager.store' diff --git a/packages/shared/lib/core/profile-manager/stores/profile-manager.store.ts b/packages/shared/lib/core/profile-manager/stores/profile-manager.store.ts deleted file mode 100644 index 84a9619d3b5..00000000000 --- a/packages/shared/lib/core/profile-manager/stores/profile-manager.store.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { get, writable } from 'svelte/store' -import { IProfileManager } from '../interfaces' - -export const profileManager = writable(null) - -export function getProfileManager(): IProfileManager { - return get(profileManager) -} diff --git a/packages/shared/lib/core/profile-manager/types/index.ts b/packages/shared/lib/core/profile-manager/types/index.ts deleted file mode 100644 index c891ec9df20..00000000000 --- a/packages/shared/lib/core/profile-manager/types/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './profile-manager-options.type' -export * from './transaction-progress-event.type' -export * from './wallet-api-event-handler.type' -export * from './wallet-api-event-map.type' diff --git a/packages/shared/lib/core/profile-manager/types/profile-manager-options.type.ts b/packages/shared/lib/core/profile-manager/types/profile-manager-options.type.ts deleted file mode 100644 index eeba13fe361..00000000000 --- a/packages/shared/lib/core/profile-manager/types/profile-manager-options.type.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ClientOptions } from '@core/network/interfaces' -import { WalletOptions } from '@iota/sdk/out/types' - -export type ProfileManagerOptions = Omit & { - clientOptions: ClientOptions -} diff --git a/packages/shared/lib/core/profile-manager/types/transaction-progress-event.type.ts b/packages/shared/lib/core/profile-manager/types/transaction-progress-event.type.ts deleted file mode 100644 index 2a2ffa52554..00000000000 --- a/packages/shared/lib/core/profile-manager/types/transaction-progress-event.type.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { - SelectingInputsProgress, - GeneratingRemainderDepositAddressProgress, - PreparedTransactionProgress, - PreparedTransactionEssenceHashProgress, - SigningTransactionProgress, - PerformingPowProgress, - BroadcastingProgress, -} from '@iota/sdk/out/types' - -export type TransactionProgressEventPayload = - | SelectingInputsProgress - | GeneratingRemainderDepositAddressProgress - | PreparedTransactionProgress - | PreparedTransactionEssenceHashProgress - | SigningTransactionProgress - | PerformingPowProgress - | BroadcastingProgress diff --git a/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts b/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts index b0e14f7a9ef..12b5308c4b2 100644 --- a/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts +++ b/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts @@ -1,10 +1,11 @@ import { getStorageDirectoryOfProfile, IPersistedProfile } from '@core/profile' -import { getSecretManagerFromProfileType, ProfileManagerOptions } from '@core/profile-manager' +import { getSecretManagerFromProfileType } from '@core/profile-manager' import { COIN_TYPE, getDefaultClientOptions } from '@core/network' +import { WalletOptions } from '@iota/sdk/out/types' export async function buildProfileManagerOptionsFromProfileData( profileData: Partial -): Promise { +): Promise { const { id, type, network } = profileData const storagePath = await getStorageDirectoryOfProfile(id) const coinType = network?.coinType ? network?.coinType : network ? COIN_TYPE[network?.id] ?? 1 : 1 @@ -17,7 +18,9 @@ export async function buildProfileManagerOptionsFromProfileData( return { storagePath, - coinType, + bipPath: { + coinType + }, clientOptions, secretManager, } diff --git a/packages/shared/lib/core/profile-manager/utils/index.ts b/packages/shared/lib/core/profile-manager/utils/index.ts index a6266fa919a..6641f7a3fe1 100644 --- a/packages/shared/lib/core/profile-manager/utils/index.ts +++ b/packages/shared/lib/core/profile-manager/utils/index.ts @@ -1,4 +1,3 @@ export * from './buildProfileManagerOptionsFromProfileData' export * from './getSecretManagerFromProfileType' export * from './getSecretManagerPath' -export * from './validateWalletApiEvent' diff --git a/packages/shared/lib/core/profile/actions/active-profile/logout.ts b/packages/shared/lib/core/profile/actions/active-profile/logout.ts index ad204a1ef33..31ce84e7372 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/logout.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/logout.ts @@ -14,7 +14,7 @@ import { stopDownloadingNftMediaFromQueue } from '@core/nfts/actions' import { lockStronghold, resetActiveProfile } from '@core/profile/actions' import { activeAccounts, activeProfile, isSoftwareProfile, isDestroyingManager } from '@core/profile/stores' import { isLedgerProfile } from '@core/profile/utils' -import { destroyProfileManager, unsubscribeFromWalletApiEvents } from '@core/profile-manager/actions' +import { clearProfileFromMemory, unsubscribeFromWalletApiEvents } from '@core/profile-manager/actions' import { IProfileManager } from '@core/profile-manager/interfaces' import { profileManager } from '@core/profile-manager/stores' import { routerManager } from '@core/router/stores' @@ -71,6 +71,6 @@ async function destroyWalletRsObjects(manager: IProfileManager): Promise { isDestroyingManager.set(true) await manager?.stopBackgroundSync() await unsubscribeFromWalletApiEvents() - await destroyProfileManager() + await clearProfileFromMemory() isDestroyingManager.set(false) } diff --git a/packages/shared/lib/core/profile-manager/actions/changePasswordAndUnlockStronghold.ts b/packages/shared/lib/core/profile/actions/changePasswordAndUnlockStronghold.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/actions/changePasswordAndUnlockStronghold.ts rename to packages/shared/lib/core/profile/actions/changePasswordAndUnlockStronghold.ts diff --git a/packages/shared/lib/core/profile/actions/clearProfileFromMemory.ts b/packages/shared/lib/core/profile/actions/clearProfileFromMemory.ts new file mode 100644 index 00000000000..7fd6db98ee3 --- /dev/null +++ b/packages/shared/lib/core/profile/actions/clearProfileFromMemory.ts @@ -0,0 +1,5 @@ +import { api } from '@core/api' + +export async function clearProfileFromMemory(): Promise { + await api.clearWalletsFromMemory() +} diff --git a/packages/shared/lib/core/profile-manager/actions/deleteAccount.ts b/packages/shared/lib/core/profile/actions/deleteAccount.ts similarity index 94% rename from packages/shared/lib/core/profile-manager/actions/deleteAccount.ts rename to packages/shared/lib/core/profile/actions/deleteAccount.ts index becc9933d9d..5b3060b2e99 100644 --- a/packages/shared/lib/core/profile-manager/actions/deleteAccount.ts +++ b/packages/shared/lib/core/profile/actions/deleteAccount.ts @@ -8,7 +8,7 @@ import { removeAccountFromActiveAccounts, visibleActiveAccounts } from '@core/pr import { routerManager } from '@core/router/stores' // TODO(2.0): replace all its usage, before it was numeric index, now it's id -export async function deleteAccount(id: string): Promise { +export async function deleteWallet(id: string): Promise { const accountToBeDeleted = get(visibleActiveAccounts).find((account) => account?.id === id) const accounts = get(visibleActiveAccounts) diff --git a/packages/shared/lib/core/profile/actions/index.ts b/packages/shared/lib/core/profile/actions/index.ts index 26adafb2fb5..945afc3d231 100644 --- a/packages/shared/lib/core/profile/actions/index.ts +++ b/packages/shared/lib/core/profile/actions/index.ts @@ -2,6 +2,8 @@ export * from './createAccount' export * from './getAccount' export * from './getAccounts' export * from './recoverAccounts' +export * from './clearProfileFromMemory' +export * from './deleteAccount' export * from './active-accounts' export * from './active-profile' diff --git a/packages/shared/lib/core/profile/interfaces/index.ts b/packages/shared/lib/core/profile/interfaces/index.ts index f143d0b8f02..c34e63fbb87 100644 --- a/packages/shared/lib/core/profile/interfaces/index.ts +++ b/packages/shared/lib/core/profile/interfaces/index.ts @@ -4,3 +4,4 @@ export * from './persisted-profile.interface' export * from './profile-settings.interface' export * from './profile.interface' export * from './chrysalis-persisted-profile.interface' +export * from './recover-account-payload.interface' diff --git a/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts b/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts index 8a3131ed0a1..40adc1571eb 100644 --- a/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts @@ -2,6 +2,7 @@ import { IPersistedAccountData } from '@core/account' import { ClientOptions, IPersistedNetwork } from '@core/network' import { INft } from '@core/nfts' import { StrongholdVersion } from '@core/stronghold/enums' +import { SecretManagerType } from '@iota/sdk/out/types' import { ProfileType } from '../enums' import { IProfileSettings } from './profile-settings.interface' @@ -19,6 +20,7 @@ export interface IPersistedProfile { hasVisitedDashboard?: boolean lastUsedAccountIndex?: number clientOptions: ClientOptions + secretManagerOptions: SecretManagerType, forceAssetRefresh: boolean strongholdVersion?: StrongholdVersion needsChrysalisToStardustDbMigration?: boolean diff --git a/packages/shared/lib/core/profile-manager/interfaces/recover-account-payload.interface.ts b/packages/shared/lib/core/profile/interfaces/recover-account-payload.interface.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/interfaces/recover-account-payload.interface.ts rename to packages/shared/lib/core/profile/interfaces/recover-account-payload.interface.ts diff --git a/packages/shared/lib/core/profile/stores/active-profile-id.store.ts b/packages/shared/lib/core/profile/stores/active-profile-id.store.ts index 53b5796e80d..1397705204a 100644 --- a/packages/shared/lib/core/profile/stores/active-profile-id.store.ts +++ b/packages/shared/lib/core/profile/stores/active-profile-id.store.ts @@ -1,3 +1,3 @@ import { persistent } from '@core/utils/store' -export const activeProfileId = persistent('activeProfileId', null) +export const activeProfileId = persistent('activeProfileId', null) diff --git a/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts b/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts new file mode 100644 index 00000000000..955aaa9aa31 --- /dev/null +++ b/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts @@ -0,0 +1,8 @@ +import { get } from 'svelte/store' +import { activeProfileSecretManager } from '../stores' + +export async function changeStrongholdPassword(currentPassword: string, newPassword: string): Promise { + const activeProfileSecretManagerInstance = get(activeProfileSecretManager) + await activeProfileSecretManagerInstance.changeStrongholdPassword(currentPassword, newPassword) +} + diff --git a/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts b/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts new file mode 100644 index 00000000000..257aed16b20 --- /dev/null +++ b/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts @@ -0,0 +1,7 @@ +import { get } from 'svelte/store' +import { activeProfileSecretManager as activeProfileSecretManagerStore } from '../stores' + +export async function clearStrongholdPassword(): Promise { + const activeProfileSecretManagerInstance = get(activeProfileSecretManagerStore) + await activeProfileSecretManagerInstance?.clearStrongholdPassword() +} diff --git a/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts b/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts new file mode 100644 index 00000000000..fa6f4059e13 --- /dev/null +++ b/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts @@ -0,0 +1,25 @@ +import { GenerateAddressOptions } from '@iota/sdk/out/types' +import { activeSecretManager } from '../stores' +import { get } from 'svelte/store' + +// TODO(2.0): Fix all usages +export async function generateEd25519Address( + accountIndex: number, + options: GenerateAddressOptions, + bech32Hrp: string +): Promise { + const secretManager = get(activeSecretManager) + + if(!secretManager){ + return undefined + } + + // TODO(2.0) Ledger secret manager doesn't support this + return (await secretManager.generateEd25519Addresses({ + accountIndex, options, bech32Hrp, + range: { + start: 0, + end: 1, + }, + }))[0] +} diff --git a/packages/shared/lib/core/secret-manager/actions/getLedgerNanoStatus.ts b/packages/shared/lib/core/secret-manager/actions/getLedgerNanoStatus.ts new file mode 100644 index 00000000000..7ecaee6e22e --- /dev/null +++ b/packages/shared/lib/core/secret-manager/actions/getLedgerNanoStatus.ts @@ -0,0 +1,12 @@ +import { LedgerNanoStatus } from '@iota/sdk/out/types' +import { get } from 'svelte/store' +import { activeProfileSecretManager } from '../stores' + +// TODO(2.0): Fix all of usages of this +export async function getLedgerNanoStatus(): Promise { + const secretManager = get(activeProfileSecretManager) + if (!secretManager) { + return null + } + return secretManager.getLedgerNanoStatus() +} diff --git a/packages/shared/lib/core/secret-manager/actions/index.ts b/packages/shared/lib/core/secret-manager/actions/index.ts index 06eb3e28fa3..909b24bc450 100644 --- a/packages/shared/lib/core/secret-manager/actions/index.ts +++ b/packages/shared/lib/core/secret-manager/actions/index.ts @@ -1,19 +1,5 @@ -export * from '../../wallet/actions/backup' -export * from '../../wallet/actions/changeStrongholdPassword' -export * from '../../wallet/actions/clearStrongholdPassword' -export * from './createAccount' -export * from './generateMnemonic' -export * from './getAccount' -export * from './getAccounts' -export * from './getClient' +export * from './changeStrongholdPassword' +export * from './clearStrongholdPassword' +export * from './generateEd25519Address' export * from './getLedgerNanoStatus' -export * from './getNodeInfo' -export * from './isStrongholdUnlocked' -export * from './recoverAccounts' -export * from './restoreBackup' -export * from './setClientOptions' -export * from './setStrongholdPassword' -export * from './setStrongholdPasswordClearInterval' -export * from './startBackgroundSync' export * from './storeMnemonic' -export * from './verifyMnemonic' diff --git a/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts b/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts new file mode 100644 index 00000000000..c9fe6006745 --- /dev/null +++ b/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts @@ -0,0 +1,11 @@ +import { get } from 'svelte/store' +import { activeProfileSecretManager } from '../stores' + +export async function storeMnemonic(mnemonic: string): Promise { + const secretManager = get(activeProfileSecretManager) + + if (!secretManager) { + return undefined + } + return secretManager.storeMnemonic(mnemonic) +} diff --git a/packages/shared/lib/core/secret-manager/index.ts b/packages/shared/lib/core/secret-manager/index.ts new file mode 100644 index 00000000000..cc7b3ae4cec --- /dev/null +++ b/packages/shared/lib/core/secret-manager/index.ts @@ -0,0 +1,2 @@ +export * from './actions' +export * from './stores' diff --git a/packages/shared/lib/core/secret-manager/stores/index.ts b/packages/shared/lib/core/secret-manager/stores/index.ts new file mode 100644 index 00000000000..ed1c6432dfe --- /dev/null +++ b/packages/shared/lib/core/secret-manager/stores/index.ts @@ -0,0 +1 @@ +export * from './secret-manager.store'; diff --git a/packages/shared/lib/core/secret-manager/stores/secret-manager.store.ts b/packages/shared/lib/core/secret-manager/stores/secret-manager.store.ts new file mode 100644 index 00000000000..18ac27d1f23 --- /dev/null +++ b/packages/shared/lib/core/secret-manager/stores/secret-manager.store.ts @@ -0,0 +1,17 @@ +import { api } from '@core/api'; +import { activeProfile } from '@core/profile'; +import { SecretManager } from '@iota/sdk'; +import { Readable, derived } from 'svelte/store'; + +const activeProfileSecretManagerOptions = derived(activeProfile, ($activeProfile) => $activeProfile.secretManagerOptions); + +export const activeProfileSecretManager: Readable = derived(activeProfileSecretManagerOptions, (activeProfileSecretManagerOptions, set) => { + if (activeProfileSecretManagerOptions) { + api.createSecretManager(activeProfileSecretManagerOptions) + .then((secretManager) => { + set(secretManager) + }) + } else { + set(null) + } +}) diff --git a/packages/shared/lib/core/wallet/actions/changeStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/changeStrongholdPassword.ts deleted file mode 100644 index 9e617c6d989..00000000000 --- a/packages/shared/lib/core/wallet/actions/changeStrongholdPassword.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { profileManager } from '@core/profile-manager/stores' -import { get } from 'svelte/store' - -export async function changeStrongholdPassword(currentPassword: string, newPassword: string): Promise { - const manager = get(profileManager) - await manager.changeStrongholdPassword(currentPassword, newPassword) -} diff --git a/packages/shared/lib/core/wallet/actions/clearStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/clearStrongholdPassword.ts deleted file mode 100644 index 77767117a15..00000000000 --- a/packages/shared/lib/core/wallet/actions/clearStrongholdPassword.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { get } from 'svelte/store' -import { profileManager } from '../stores' - -export async function clearStrongholdPassword(): Promise { - const manager = get(profileManager) - // TODO: Find the root cause that makes the profileManager be `null` https://github.com/iotaledger/firefly/issues/7456 - await manager?.clearStrongholdPassword() -} diff --git a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleNewOutputEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts similarity index 91% rename from packages/shared/lib/core/profile-manager/actions/events-handlers/handleNewOutputEvent.ts rename to packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts index 50c15627698..fd22c62bb85 100644 --- a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleNewOutputEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts @@ -1,4 +1,4 @@ -import { AliasOutput, Event, NewOutputWalletEvent, OutputType, WalletEventType } from '@iota/sdk/out/types' +import { Event, NewOutputWalletEvent, OutputType, WalletEventType } from '@iota/sdk/out/types' import { getAddressesWithOutputs } from '@core/account' import { syncBalance } from '@core/account/actions/syncBalance' @@ -19,7 +19,7 @@ import { import { getBech32AddressFromAddressTypes } from '@core/wallet/utils/getBech32AddressFromAddressTypes' import { preprocessGroupedOutputs } from '@core/wallet/utils/outputs/preprocessGroupedOutputs' import { get } from 'svelte/store' -import { validateWalletApiEvent } from '../../utils' +import { validateWalletApiEvent } from '../../../profile-manager/utils' export function handleNewOutputEvent(error: Error, rawEvent: Event): void { const { accountIndex, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.NewOutput) @@ -35,12 +35,11 @@ export async function handleNewOutputEventInternal(accountIndex: number, payload if (!account || !outputData) return - const output = outputData.output as AliasOutput + const output = outputData.output const address = getBech32AddressFromAddressTypes(outputData.address) const isNewAliasOutput = - output.type === OutputType.Alias && - output.stateIndex === 0 && + output.type === OutputType.Account && !get(allAccountActivities)[accountIndex].find((_activity) => _activity.id === outputData.outputId) const isNftOutput = output.type === OutputType.Nft diff --git a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleSpentOutputEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts similarity index 97% rename from packages/shared/lib/core/profile-manager/actions/events-handlers/handleSpentOutputEvent.ts rename to packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts index 7d2d1ed5af9..556424d9c3a 100644 --- a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleSpentOutputEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts @@ -6,7 +6,7 @@ import { activeAccounts, updateActiveAccount } from '@core/profile/stores' import { ActivityAsyncStatus, ActivityType } from '@core/wallet' import { allAccountActivities, updateAsyncDataByTransactionId } from '@core/wallet/stores/all-account-activities.store' import { get } from 'svelte/store' -import { validateWalletApiEvent } from '../../utils' +import { validateWalletApiEvent } from '../../../profile-manager/utils' import { getAddressesWithOutputs } from '@core/account' export async function handleSpentOutputEvent(error: Error, rawEvent: Event): Promise { diff --git a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleTransactionInclusionEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts similarity index 98% rename from packages/shared/lib/core/profile-manager/actions/events-handlers/handleTransactionInclusionEvent.ts rename to packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts index 9e26bb663b7..a5b63f8aeb9 100644 --- a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleTransactionInclusionEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts @@ -14,7 +14,7 @@ import { updateActivityByTransactionId, } from '@core/wallet/stores/all-account-activities.store' import { get } from 'svelte/store' -import { validateWalletApiEvent } from '../../utils' +import { validateWalletApiEvent } from '../../../profile-manager/utils' export function handleTransactionInclusionEvent(error: Error, rawEvent: Event): void { const { accountIndex, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.TransactionInclusion) diff --git a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleTransactionProgressEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts similarity index 87% rename from packages/shared/lib/core/profile-manager/actions/events-handlers/handleTransactionProgressEvent.ts rename to packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts index d8e814a0590..326db9abcf2 100644 --- a/packages/shared/lib/core/profile-manager/actions/events-handlers/handleTransactionProgressEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts @@ -2,9 +2,10 @@ import { get } from 'svelte/store' import { Event, TransactionProgressWalletEvent, - PreparedTransactionEssenceHashProgress, + PreparedTransactionSigningHashProgress, WalletEventType, TransactionProgressType, + TransactionProgress, } from '@iota/sdk/out/types' import { selectedAccountIndex } from '@core/account' @@ -14,9 +15,8 @@ import { isOnboardingLedgerProfile } from '@contexts/onboarding' import { closePopup, openPopup, PopupId } from '@auxiliary/popup' import { deconstructLedgerVerificationProps } from '@core/ledger/helpers' -import { MissingTransactionProgressEventPayloadError } from '../../errors' -import { TransactionProgressEventPayload } from '../../types' -import { validateWalletApiEvent } from '../../utils' +import { MissingTransactionProgressEventPayloadError } from '../../../profile-manager/errors' +import { validateWalletApiEvent } from '../../../profile-manager/utils' export function handleTransactionProgressEvent(error: Error, rawEvent: Event): void { const { accountIndex, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.TransactionProgress) @@ -29,7 +29,7 @@ export function handleTransactionProgressEvent(error: Error, rawEvent: Event): v export function handleTransactionProgressEventInternal( accountIndex: number, - payload: TransactionProgressEventPayload + payload: TransactionProgress ): void { if (get(isActiveLedgerProfile)) { if (get(selectedAccountIndex) === accountIndex) { @@ -42,7 +42,7 @@ export function handleTransactionProgressEventInternal( } } -function openPopupIfVerificationNeeded(payload: TransactionProgressEventPayload): void { +function openPopupIfVerificationNeeded(payload: TransactionProgress): void { if (payload) { const type = payload.type if (type === TransactionProgressType.PreparedTransaction) { @@ -54,14 +54,14 @@ function openPopupIfVerificationNeeded(payload: TransactionProgressEventPayload) ...deconstructLedgerVerificationProps(), }, }) - } else if (type === TransactionProgressType.PreparedTransactionEssenceHash) { + } else if (type === TransactionProgressType.PreparedTransactionSigningHash) { if (get(ledgerNanoStatus)?.blindSigningEnabled) { openPopup({ id: PopupId.VerifyLedgerTransaction, hideClose: true, preventClose: true, props: { - hash: (payload as PreparedTransactionEssenceHashProgress).hash, + hash: (payload as PreparedTransactionSigningHashProgress).hash, }, }) } else { @@ -71,6 +71,7 @@ function openPopupIfVerificationNeeded(payload: TransactionProgressEventPayload) preventClose: true, }) } + // TODO(2.0): check if this is still needed (PerformingPow) } else if (type === TransactionProgressType.PerformingPow) { closePopup(true) } diff --git a/packages/shared/lib/core/profile-manager/actions/events-handlers/index.ts b/packages/shared/lib/core/wallet/actions/events-handlers/index.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/actions/events-handlers/index.ts rename to packages/shared/lib/core/wallet/actions/events-handlers/index.ts diff --git a/packages/shared/lib/core/wallet/actions/getLedgerNanoStatus.ts b/packages/shared/lib/core/wallet/actions/getLedgerNanoStatus.ts deleted file mode 100644 index 7d4eccf10b8..00000000000 --- a/packages/shared/lib/core/wallet/actions/getLedgerNanoStatus.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { LedgerNanoStatus } from '@iota/sdk/out/types' -import { get } from 'svelte/store' -import { profileManager as _profileManager } from '@core/profile-manager/stores' - -export function getLedgerNanoStatus(profileManager = _profileManager): Promise { - const manager = get(profileManager) - return manager.getLedgerNanoStatus() -} diff --git a/packages/shared/lib/core/wallet/actions/index.ts b/packages/shared/lib/core/wallet/actions/index.ts index bbb42feb225..0987abd6cb0 100644 --- a/packages/shared/lib/core/wallet/actions/index.ts +++ b/packages/shared/lib/core/wallet/actions/index.ts @@ -1,9 +1,7 @@ export * from './backup' export * from './burnAsset' export * from './burnNft' -export * from './changeStrongholdPassword' export * from './claimActivity' -export * from './clearStrongholdPassword' export * from './getAccountAssetsForSelectedAccount' export * from './generateAndStoreActivitiesForAllAccounts' export * from './rejectActivity' @@ -15,3 +13,7 @@ export * from './mintNft' export * from './createNativeToken' export * from './getOrRequestAssetFromPersistedAssets' export * from './activities' +export * from './subscribeToWalletApiEvents' +export * from './unsubscribeFromWalletApiEvents' + +export * from './events-handlers' diff --git a/packages/shared/lib/core/wallet/actions/storeMnemonic.ts b/packages/shared/lib/core/wallet/actions/storeMnemonic.ts deleted file mode 100644 index 16b94c60612..00000000000 --- a/packages/shared/lib/core/wallet/actions/storeMnemonic.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { get } from 'svelte/store' -import { profileManager } from '../stores' - -export async function storeMnemonic(mnemonic: string): Promise { - const manager = get(profileManager) - await manager.storeMnemonic(mnemonic) -} diff --git a/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts b/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts new file mode 100644 index 00000000000..d82628b6bed --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts @@ -0,0 +1,15 @@ +import { selectedAccount } from '@core/account/stores'; +import { get } from 'svelte/store'; +import { IWalletApiEventSubscriptionConfiguration } from '../interfaces'; + +// TODO(2.0): Fix all of usages of this +export function subscribeToWalletApiEvents(configuration: IWalletApiEventSubscriptionConfiguration): void { + const { eventMap, wallet } = configuration + + const selectedWallet = wallet && get(selectedAccount); + + Object.entries(eventMap).forEach(([event, callback]) => { + const eventId = Number(event) + void selectedWallet?.listen([eventId], callback) + }) +} diff --git a/packages/shared/lib/core/wallet/actions/unsubscribeFromWalletApiEvents.ts b/packages/shared/lib/core/wallet/actions/unsubscribeFromWalletApiEvents.ts new file mode 100644 index 00000000000..8dbbae883ab --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/unsubscribeFromWalletApiEvents.ts @@ -0,0 +1,10 @@ +import { IAccount } from '@core/account/interfaces' +import { selectedAccount } from '@core/account/stores' +import { get, Readable } from 'svelte/store' + +// TODO(2.0): Fix all of usages of this +export async function unsubscribeFromWalletApiEvents( + wallet: Readable = selectedAccount +): Promise { + await get(wallet)?.clearListeners([]) +} diff --git a/packages/shared/lib/core/profile-manager/errors/cannot-remove-account.error.ts b/packages/shared/lib/core/wallet/errors/cannot-remove-account.error.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/errors/cannot-remove-account.error.ts rename to packages/shared/lib/core/wallet/errors/cannot-remove-account.error.ts diff --git a/packages/shared/lib/core/wallet/errors/index.ts b/packages/shared/lib/core/wallet/errors/index.ts index 81af82f03bd..a1c0a68b5ef 100644 --- a/packages/shared/lib/core/wallet/errors/index.ts +++ b/packages/shared/lib/core/wallet/errors/index.ts @@ -1 +1,6 @@ export * from './missing-transaction-id.error' +export * from './cannot-remove-account.error' +export * from './missing-transaction-progress-event-payload.error' +export * from './remove-not-last-account.error' +export * from './wallet-api-event.error' +export * from './wallet-api-event-validation.error' diff --git a/packages/shared/lib/core/profile-manager/errors/missing-transaction-progress-event-payload.error.ts b/packages/shared/lib/core/wallet/errors/missing-transaction-progress-event-payload.error.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/errors/missing-transaction-progress-event-payload.error.ts rename to packages/shared/lib/core/wallet/errors/missing-transaction-progress-event-payload.error.ts diff --git a/packages/shared/lib/core/profile-manager/errors/remove-not-last-account.error.ts b/packages/shared/lib/core/wallet/errors/remove-not-last-account.error.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/errors/remove-not-last-account.error.ts rename to packages/shared/lib/core/wallet/errors/remove-not-last-account.error.ts diff --git a/packages/shared/lib/core/profile-manager/errors/wallet-api-event-validation.error.ts b/packages/shared/lib/core/wallet/errors/wallet-api-event-validation.error.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/errors/wallet-api-event-validation.error.ts rename to packages/shared/lib/core/wallet/errors/wallet-api-event-validation.error.ts diff --git a/packages/shared/lib/core/profile-manager/errors/wallet-api-event.error.ts b/packages/shared/lib/core/wallet/errors/wallet-api-event.error.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/errors/wallet-api-event.error.ts rename to packages/shared/lib/core/wallet/errors/wallet-api-event.error.ts diff --git a/packages/shared/lib/core/wallet/interfaces/index.ts b/packages/shared/lib/core/wallet/interfaces/index.ts index 6e91f5c2042..e90d58356d9 100644 --- a/packages/shared/lib/core/wallet/interfaces/index.ts +++ b/packages/shared/lib/core/wallet/interfaces/index.ts @@ -17,3 +17,5 @@ export * from './persisted-asset.interface' export * from './persisted-assets.interface' export * from './processed-transaction.interface' export * from './wrapped-output.interface' +export * from './wallet-api-event-payload-wrapper.interface' +export * from './wallet-api-event-subscription-configuration.interface' diff --git a/packages/shared/lib/core/profile-manager/interfaces/wallet-api-event-payload-wrapper.interface.ts b/packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/interfaces/wallet-api-event-payload-wrapper.interface.ts rename to packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts diff --git a/packages/shared/lib/core/profile-manager/interfaces/wallet-api-event-subscription-configuration.interface.ts b/packages/shared/lib/core/wallet/interfaces/wallet-api-event-subscription-configuration.interface.ts similarity index 58% rename from packages/shared/lib/core/profile-manager/interfaces/wallet-api-event-subscription-configuration.interface.ts rename to packages/shared/lib/core/wallet/interfaces/wallet-api-event-subscription-configuration.interface.ts index e3a0ddc4fe4..68d6fa3af8a 100644 --- a/packages/shared/lib/core/profile-manager/interfaces/wallet-api-event-subscription-configuration.interface.ts +++ b/packages/shared/lib/core/wallet/interfaces/wallet-api-event-subscription-configuration.interface.ts @@ -1,8 +1,7 @@ import { WalletApiEventMap } from '../types' - -import { IProfileManager } from './profile-manager.interface' +import { IAccount } from '@core/account/interfaces' export interface IWalletApiEventSubscriptionConfiguration { eventMap: WalletApiEventMap - profileManager?: IProfileManager + wallet: IAccount } diff --git a/packages/shared/lib/core/profile-manager/tests/api.test.ts b/packages/shared/lib/core/wallet/tests/old-profile-manager-api.test.ts similarity index 95% rename from packages/shared/lib/core/profile-manager/tests/api.test.ts rename to packages/shared/lib/core/wallet/tests/old-profile-manager-api.test.ts index d36ab23f511..746c342d09c 100644 --- a/packages/shared/lib/core/profile-manager/tests/api.test.ts +++ b/packages/shared/lib/core/wallet/tests/old-profile-manager-api.test.ts @@ -4,13 +4,14 @@ import { MOCK_MNEMONIC } from '@mocks/api.mock' import { get } from 'svelte/store' -import { generateRandomId } from '../../../core/utils/' +import { generateRandomId } from '../../utils' -import { destroyProfileManager } from '../actions' +import { clearProfileFromMemory } from '../actions' import { generateMnemonic, setStrongholdPassword, storeMnemonic, verifyMnemonic, backup, restoreBackup } from '../api' import { profileManager } from '../stores' import { IApi } from '../interfaces' +// TODO(2.0): fix all these tests describe('File: api.test.ts', () => { let profileManagerMock: ProfileManagerMock let spy: jest.SpyInstance @@ -29,7 +30,7 @@ describe('File: api.test.ts', () => { }) it('should destroy the profile manager correctly', async () => { - await destroyProfileManager() + await clearProfileFromMemory() expect(get(profileManager)).toBeNull() }) diff --git a/packages/shared/lib/core/wallet/types/index.ts b/packages/shared/lib/core/wallet/types/index.ts index 44340de0211..2e10eac3694 100644 --- a/packages/shared/lib/core/wallet/types/index.ts +++ b/packages/shared/lib/core/wallet/types/index.ts @@ -5,3 +5,5 @@ export * from './subject.type' export * from './activities' export * from './new-transaction-details.type' export * from './token-metadata.type' +export * from './wallet-api-event-handler.type' +export * from './wallet-api-event-map.type' diff --git a/packages/shared/lib/core/profile-manager/types/wallet-api-event-handler.type.ts b/packages/shared/lib/core/wallet/types/wallet-api-event-handler.type.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/types/wallet-api-event-handler.type.ts rename to packages/shared/lib/core/wallet/types/wallet-api-event-handler.type.ts diff --git a/packages/shared/lib/core/profile-manager/types/wallet-api-event-map.type.ts b/packages/shared/lib/core/wallet/types/wallet-api-event-map.type.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/types/wallet-api-event-map.type.ts rename to packages/shared/lib/core/wallet/types/wallet-api-event-map.type.ts diff --git a/packages/shared/lib/core/wallet/utils/index.ts b/packages/shared/lib/core/wallet/utils/index.ts index 69a605fb96c..6508d99efcb 100644 --- a/packages/shared/lib/core/wallet/utils/index.ts +++ b/packages/shared/lib/core/wallet/utils/index.ts @@ -25,6 +25,7 @@ export * from './parseGovernanceMetadata' export * from './processAndAddToActivities' export * from './validateIrc30Metadata' export * from './validateTokenAmount' +export * from './validateWalletApiEvent' // Folders export * from './generateActivity' diff --git a/packages/shared/lib/core/profile-manager/utils/validateWalletApiEvent.ts b/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts similarity index 100% rename from packages/shared/lib/core/profile-manager/utils/validateWalletApiEvent.ts rename to packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts From e05e7bbd4c00569bd6be011f4de89d55182cf20d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bego=C3=B1a=20Alvarez?= Date: Thu, 23 Nov 2023 15:21:16 +0100 Subject: [PATCH 05/19] refactor(wip): refactor profilemanager core module --- .../lib/core/account/actions/buildAccountState.ts | 2 +- .../actions/buildAccountStateAndPersistedData.ts | 2 +- .../lib/core/account/actions/createNewAccount.ts | 10 +++++----- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/shared/lib/core/account/actions/buildAccountState.ts b/packages/shared/lib/core/account/actions/buildAccountState.ts index 5c704f1eee7..d6e3c73c702 100644 --- a/packages/shared/lib/core/account/actions/buildAccountState.ts +++ b/packages/shared/lib/core/account/actions/buildAccountState.ts @@ -27,7 +27,7 @@ export async function buildAccountState( potentiallyLockedOutputs: {}, aliases: [], } - const accountIndex = 0; // TODO: CHANGE THIS + const accountIndex = 0; // TODO(2.0): CHANGE THIS let depositAddress = '' let votingPower = '' try { diff --git a/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts b/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts index 50c8f76e241..8910be8b607 100644 --- a/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts +++ b/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts @@ -8,7 +8,7 @@ export async function buildAccountStateAndPersistedData( name?: string, color?: string ): Promise<[IAccountState, IPersistedAccountData]> { - const index = 0; // TODO: CHANGE THIS + const index = 0; // TODO(2.0): CHANGE THIS const persistedAccountData: IPersistedAccountData = { name: name || `${localize('general.account')} ${index + 1}`, color: color || getRandomAccountColor(), diff --git a/packages/shared/lib/core/account/actions/createNewAccount.ts b/packages/shared/lib/core/account/actions/createNewAccount.ts index 4ddb4671d79..e114b3c4a0c 100644 --- a/packages/shared/lib/core/account/actions/createNewAccount.ts +++ b/packages/shared/lib/core/account/actions/createNewAccount.ts @@ -14,17 +14,17 @@ export async function createNewAccount(name?: string, color?: string): Promise Date: Tue, 28 Nov 2023 15:41:21 +0100 Subject: [PATCH 06/19] merge account into wallet --- .../popups/CreateAccountPopup.svelte | 4 +- packages/shared/components/AssetIcon.svelte | 2 +- .../shared/components/ProfilePicture.svelte | 2 +- .../components/inputs/RecipientInput.svelte | 22 ++- .../components/interfaces/option.interface.ts | 2 +- .../buildAccountStateAndPersistedData.ts | 20 --- .../core/account/actions/createNewAccount.ts | 30 ---- .../shared/lib/core/account/actions/index.ts | 12 -- .../lib/core/account/actions/loadAccount.ts | 22 --- .../actions/resetSelectedAccountIndex.ts | 5 - .../account/actions/setNextSelectedAccount.ts | 17 -- .../account/actions/setSelectedAccount.ts | 21 --- .../lib/core/account/actions/syncBalance.ts | 14 -- .../core/account/actions/syncVotingPower.ts | 14 -- .../account/api/createAliasIfNecessary.ts | 9 -- .../shared/lib/core/account/api/getBalance.ts | 6 - .../account/api/getParticipationOverview.ts | 7 - .../lib/core/account/api/getVotingPower.ts | 6 - packages/shared/lib/core/account/api/index.ts | 5 - .../lib/core/account/constants/index.ts | 2 - .../max-account-name-length.constant.ts | 1 - .../shared/lib/core/account/enums/index.ts | 2 - .../shared/lib/core/account/errors/index.ts | 1 - packages/shared/lib/core/account/index.ts | 8 - .../interfaces/account-balances.interface.ts | 12 -- .../account/interfaces/account.interface.ts | 149 ------------------ .../lib/core/account/interfaces/index.ts | 4 - .../shared/lib/core/account/stores/index.ts | 2 - .../stores/selected-account-id.store.ts | 3 - .../account/stores/selected-account.store.ts | 19 --- .../core/account/tests/buildBip32Path.test.ts | 12 -- .../tests/deconstructBip32Path.test.ts | 21 --- .../lib/core/account/utils/buildBip32Path.ts | 3 - .../account/utils/deconstructBip32Path.ts | 26 --- .../core/account/utils/getAccountColorById.ts | 6 - .../core/account/utils/getDepositAddress.ts | 7 - .../account/utils/getRandomAccountColor.ts | 6 - .../shared/lib/core/account/utils/index.ts | 12 -- .../account/utils/sumBalanceForAccounts.ts | 8 - .../account/utils/syncAccountsInParallel.ts | 7 - .../account/utils/syncAccountsInSeries.ts | 12 -- .../lib/core/api/interfaces/api.interface.ts | 6 +- .../active-accounts/getWalletColorById.ts | 7 + .../profile/actions/active-accounts/index.ts | 1 + .../updateActiveAccountPersistedData.ts | 17 +- .../profile/actions/active-profile/index.ts | 2 +- .../actions/active-profile/loadAccounts.ts | 20 --- .../actions/active-profile/loadWallets.ts | 20 +++ .../profile/actions/active-profile/login.ts | 2 +- .../profile/actions/active-profile/logout.ts | 4 +- .../{createAccount.ts => createWallet.ts} | 6 +- .../{deleteAccount.ts => deleteWallet.ts} | 14 +- .../lib/core/profile/actions/getAccount.ts | 12 +- .../lib/core/profile/actions/getAccounts.ts | 6 +- .../shared/lib/core/profile/actions/index.ts | 4 +- .../lib/core/profile/interfaces/index.ts | 1 + .../interfaces/persisted-profile.interface.ts | 8 +- .../profile/interfaces/profile.interface.ts | 2 +- .../profile/interfaces/wallet.interface.ts | 6 + .../profile/stores/active-accounts.store.ts | 41 ----- .../profile/stores/active-profile.store.ts | 27 ++-- .../profile/stores/active-wallets.store.ts | 41 +++++ .../shared/lib/core/profile/stores/index.ts | 2 +- .../setAsyncStatusOfAccountActivities.ts | 2 +- .../actions/buildWalletState.ts} | 38 ++--- .../buildWalletStateAndPersistedData.ts | 23 +++ .../core/wallet/actions/createNewWallet.ts | 33 ++++ .../events-handlers/handleNewOutputEvent.ts | 7 +- .../events-handlers/handleSpentOutputEvent.ts | 21 +-- .../actions/findBalances.ts | 4 +- .../actions/getAddressesWithOutputs.ts | 14 +- .../lib/core/wallet/actions/getBalance.ts | 7 + .../actions/getParticipationOverview.ts | 7 + .../lib/core/wallet/actions/getVotingPower.ts | 7 + .../shared/lib/core/wallet/actions/index.ts | 8 +- .../lib/core/wallet/actions/loadWallet.ts | 24 +++ .../api => wallet/actions}/prepareOutput.ts | 7 +- .../wallet/actions/resetSelectedWalletId.ts | 5 + .../wallet/actions/setNextSelectedWallet.ts | 20 +++ .../core/wallet/actions/setSelectedWallet.ts | 22 +++ .../lib/core/wallet/actions/syncBalance.ts | 15 ++ .../core/wallet/actions/syncVotingPower.ts | 15 ++ .../actions/tryCreateAdditionalWalet.ts} | 17 +- .../default-sync-options.constant.ts | 10 +- .../shared/lib/core/wallet/constants/index.ts | 2 + .../max-wallet-name-length.constant.ts | 1 + .../shared/lib/core/wallet/enums/index.ts | 2 + .../enums/search-algorithm.enum.ts | 0 .../enums/wallet-colors.enum.ts} | 2 +- .../errors/cannot-remove-account.error.ts | 1 + .../shared/lib/core/wallet/errors/index.ts | 1 + .../unable-to-get-bound-wallet.error.ts} | 2 +- .../interfaces/account-state.interface.ts | 9 +- .../address-with-outputs.interface.ts | 0 .../lib/core/wallet/interfaces/index.ts | 3 + .../persisted-account-data.interface.ts | 2 +- ...let-api-event-payload-wrapper.interface.ts | 2 +- .../shared/lib/core/wallet/stores/index.ts | 1 + .../selected-account-activities.store.ts | 2 +- .../wallet/stores/selected-wallet-id.store.ts | 4 + .../wallet/stores/selected-wallet.store.ts | 19 +++ .../utils/getBoundWallet.ts} | 25 +-- .../core/wallet/utils/getDepositAddress.ts | 6 + .../utils/getIconColorFromString.ts | 0 .../core/wallet/utils/getRandomWalletColor.ts | 6 + .../shared/lib/core/wallet/utils/index.ts | 6 + .../core/wallet/utils/sumBalanceForWallets.ts | 9 ++ .../utils/sumTotalFromOutputs.ts | 1 + .../wallet/utils/syncWalletsInParallel.ts | 6 + .../core/wallet/utils/syncWalletsInSeries.ts | 12 ++ .../wallet/utils/validateWalletApiEvent.ts | 4 +- .../utils/validateWalletName.ts} | 15 +- 112 files changed, 507 insertions(+), 734 deletions(-) delete mode 100644 packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts delete mode 100644 packages/shared/lib/core/account/actions/createNewAccount.ts delete mode 100644 packages/shared/lib/core/account/actions/index.ts delete mode 100644 packages/shared/lib/core/account/actions/loadAccount.ts delete mode 100644 packages/shared/lib/core/account/actions/resetSelectedAccountIndex.ts delete mode 100644 packages/shared/lib/core/account/actions/setNextSelectedAccount.ts delete mode 100644 packages/shared/lib/core/account/actions/setSelectedAccount.ts delete mode 100644 packages/shared/lib/core/account/actions/syncBalance.ts delete mode 100644 packages/shared/lib/core/account/actions/syncVotingPower.ts delete mode 100644 packages/shared/lib/core/account/api/createAliasIfNecessary.ts delete mode 100644 packages/shared/lib/core/account/api/getBalance.ts delete mode 100644 packages/shared/lib/core/account/api/getParticipationOverview.ts delete mode 100644 packages/shared/lib/core/account/api/getVotingPower.ts delete mode 100644 packages/shared/lib/core/account/api/index.ts delete mode 100644 packages/shared/lib/core/account/constants/index.ts delete mode 100644 packages/shared/lib/core/account/constants/max-account-name-length.constant.ts delete mode 100644 packages/shared/lib/core/account/enums/index.ts delete mode 100644 packages/shared/lib/core/account/errors/index.ts delete mode 100644 packages/shared/lib/core/account/index.ts delete mode 100644 packages/shared/lib/core/account/interfaces/account-balances.interface.ts delete mode 100644 packages/shared/lib/core/account/interfaces/account.interface.ts delete mode 100644 packages/shared/lib/core/account/interfaces/index.ts delete mode 100644 packages/shared/lib/core/account/stores/index.ts delete mode 100644 packages/shared/lib/core/account/stores/selected-account-id.store.ts delete mode 100644 packages/shared/lib/core/account/stores/selected-account.store.ts delete mode 100644 packages/shared/lib/core/account/tests/buildBip32Path.test.ts delete mode 100644 packages/shared/lib/core/account/tests/deconstructBip32Path.test.ts delete mode 100644 packages/shared/lib/core/account/utils/buildBip32Path.ts delete mode 100644 packages/shared/lib/core/account/utils/deconstructBip32Path.ts delete mode 100644 packages/shared/lib/core/account/utils/getAccountColorById.ts delete mode 100644 packages/shared/lib/core/account/utils/getDepositAddress.ts delete mode 100644 packages/shared/lib/core/account/utils/getRandomAccountColor.ts delete mode 100644 packages/shared/lib/core/account/utils/index.ts delete mode 100644 packages/shared/lib/core/account/utils/sumBalanceForAccounts.ts delete mode 100644 packages/shared/lib/core/account/utils/syncAccountsInParallel.ts delete mode 100644 packages/shared/lib/core/account/utils/syncAccountsInSeries.ts create mode 100644 packages/shared/lib/core/profile/actions/active-accounts/getWalletColorById.ts delete mode 100644 packages/shared/lib/core/profile/actions/active-profile/loadAccounts.ts create mode 100644 packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts rename packages/shared/lib/core/profile/actions/{createAccount.ts => createWallet.ts} (85%) rename packages/shared/lib/core/profile/actions/{deleteAccount.ts => deleteWallet.ts} (54%) create mode 100644 packages/shared/lib/core/profile/interfaces/wallet.interface.ts delete mode 100644 packages/shared/lib/core/profile/stores/active-accounts.store.ts create mode 100644 packages/shared/lib/core/profile/stores/active-wallets.store.ts rename packages/shared/lib/core/{account/actions/buildAccountState.ts => wallet/actions/buildWalletState.ts} (56%) create mode 100644 packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts create mode 100644 packages/shared/lib/core/wallet/actions/createNewWallet.ts rename packages/shared/lib/core/{account => wallet}/actions/findBalances.ts (98%) rename packages/shared/lib/core/{account => wallet}/actions/getAddressesWithOutputs.ts (61%) create mode 100644 packages/shared/lib/core/wallet/actions/getBalance.ts create mode 100644 packages/shared/lib/core/wallet/actions/getParticipationOverview.ts create mode 100644 packages/shared/lib/core/wallet/actions/getVotingPower.ts create mode 100644 packages/shared/lib/core/wallet/actions/loadWallet.ts rename packages/shared/lib/core/{account/api => wallet/actions}/prepareOutput.ts (52%) create mode 100644 packages/shared/lib/core/wallet/actions/resetSelectedWalletId.ts create mode 100644 packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts create mode 100644 packages/shared/lib/core/wallet/actions/setSelectedWallet.ts create mode 100644 packages/shared/lib/core/wallet/actions/syncBalance.ts create mode 100644 packages/shared/lib/core/wallet/actions/syncVotingPower.ts rename packages/shared/lib/core/{account/actions/tryCreateAdditionalAccount.ts => wallet/actions/tryCreateAdditionalWalet.ts} (66%) rename packages/shared/lib/core/{account => wallet}/constants/default-sync-options.constant.ts (63%) create mode 100644 packages/shared/lib/core/wallet/constants/max-wallet-name-length.constant.ts rename packages/shared/lib/core/{account => wallet}/enums/search-algorithm.enum.ts (100%) rename packages/shared/lib/core/{account/enums/account-colors.enum.ts => wallet/enums/wallet-colors.enum.ts} (95%) rename packages/shared/lib/core/{account/errors/unable-to-get-bound-account.error.ts => wallet/errors/unable-to-get-bound-wallet.error.ts} (78%) rename packages/shared/lib/core/{account => wallet}/interfaces/account-state.interface.ts (55%) rename packages/shared/lib/core/{account => wallet}/interfaces/address-with-outputs.interface.ts (100%) rename packages/shared/lib/core/{account => wallet}/interfaces/persisted-account-data.interface.ts (85%) create mode 100644 packages/shared/lib/core/wallet/stores/selected-wallet-id.store.ts create mode 100644 packages/shared/lib/core/wallet/stores/selected-wallet.store.ts rename packages/shared/lib/core/{account/utils/getBoundAccount.ts => wallet/utils/getBoundWallet.ts} (54%) create mode 100644 packages/shared/lib/core/wallet/utils/getDepositAddress.ts rename packages/shared/lib/core/{account => wallet}/utils/getIconColorFromString.ts (100%) create mode 100644 packages/shared/lib/core/wallet/utils/getRandomWalletColor.ts create mode 100644 packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts rename packages/shared/lib/core/{account => wallet}/utils/sumTotalFromOutputs.ts (89%) create mode 100644 packages/shared/lib/core/wallet/utils/syncWalletsInParallel.ts create mode 100644 packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts rename packages/shared/lib/core/{account/utils/validateAccountName.ts => wallet/utils/validateWalletName.ts} (50%) diff --git a/packages/desktop/components/popups/CreateAccountPopup.svelte b/packages/desktop/components/popups/CreateAccountPopup.svelte index d85b21d3925..e93d7d8768f 100644 --- a/packages/desktop/components/popups/CreateAccountPopup.svelte +++ b/packages/desktop/components/popups/CreateAccountPopup.svelte @@ -1,7 +1,7 @@ @@ -78,6 +76,6 @@ let:option > {#if option?.id} - + {/if} diff --git a/packages/shared/components/interfaces/option.interface.ts b/packages/shared/components/interfaces/option.interface.ts index 2a70cbecfe6..e1a80035486 100644 --- a/packages/shared/components/interfaces/option.interface.ts +++ b/packages/shared/components/interfaces/option.interface.ts @@ -1,5 +1,5 @@ export interface IOption { - id?: number + id?: string key?: string value?: string } diff --git a/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts b/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts deleted file mode 100644 index 8910be8b607..00000000000 --- a/packages/shared/lib/core/account/actions/buildAccountStateAndPersistedData.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { localize } from '@core/i18n' -import { IAccount, IAccountState, IPersistedAccountData } from '../interfaces' -import { getRandomAccountColor } from '../utils' -import { buildAccountState } from './buildAccountState' - -export async function buildAccountStateAndPersistedData( - account: IAccount, - name?: string, - color?: string -): Promise<[IAccountState, IPersistedAccountData]> { - const index = 0; // TODO(2.0): CHANGE THIS - const persistedAccountData: IPersistedAccountData = { - name: name || `${localize('general.account')} ${index + 1}`, - color: color || getRandomAccountColor(), - hidden: false, - shouldRevote: false, - } - const accountState = await buildAccountState(account, persistedAccountData) - return [accountState, persistedAccountData] -} diff --git a/packages/shared/lib/core/account/actions/createNewAccount.ts b/packages/shared/lib/core/account/actions/createNewAccount.ts deleted file mode 100644 index e114b3c4a0c..00000000000 --- a/packages/shared/lib/core/account/actions/createNewAccount.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { localize } from '@core/i18n' -import { activeAccounts, addAccountPersistedDataToActiveProfile, addAccountToActiveAccounts } from '@core/profile' -import { createAccount } from '@core/profile-manager' -import { addEmptyAccountActivitiesToAllAccountActivities } from '@core/wallet/stores' -import { get } from 'svelte/store' - -import { DEFAULT_SYNC_OPTIONS } from '../constants' -import { IAccountState } from '../interfaces' - -import { buildAccountStateAndPersistedData } from './buildAccountStateAndPersistedData' - -export async function createNewAccount(name?: string, color?: string): Promise { - const account = await createAccount({ - alias: name || `${localize('general.account')} ${(get(activeAccounts)?.length ?? 0) + 1}`, - }) - - // TODO(2.0): test & fix sync when we have iota2.0 nodes - //await account.sync(DEFAULT_SYNC_OPTIONS) - - const [newAccount, accountPersistedData] = await buildAccountStateAndPersistedData(account, name, color) - - const accountIndex = 0 // TODO(2.0): CHANGE THIS - - addAccountToActiveAccounts(newAccount) - addAccountPersistedDataToActiveProfile(accountIndex, accountPersistedData) - addEmptyAccountActivitiesToAllAccountActivities(accountIndex) - - - return newAccount -} diff --git a/packages/shared/lib/core/account/actions/index.ts b/packages/shared/lib/core/account/actions/index.ts deleted file mode 100644 index f06ad973da5..00000000000 --- a/packages/shared/lib/core/account/actions/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from './buildAccountState' -export * from './buildAccountStateAndPersistedData' -export * from './createNewAccount' -export * from './loadAccount' -export * from './resetSelectedAccountIndex' -export * from './setNextSelectedAccount' -export * from './setSelectedAccount' -export * from './syncBalance' -export * from './syncVotingPower' -export * from './tryCreateAdditionalAccount' -export * from './getAddressesWithOutputs' -export * from './findBalances' diff --git a/packages/shared/lib/core/account/actions/loadAccount.ts b/packages/shared/lib/core/account/actions/loadAccount.ts deleted file mode 100644 index a3b0314559f..00000000000 --- a/packages/shared/lib/core/account/actions/loadAccount.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { addAccountPersistedDataToActiveProfile, getActiveProfilePersistedAccountData } from '@core/profile' -import { DEFAULT_SYNC_OPTIONS } from '../constants' -import { IAccount, IAccountState } from '../interfaces' -import { buildAccountState } from './buildAccountState' -import { buildAccountStateAndPersistedData } from './buildAccountStateAndPersistedData' - -export async function loadAccount(account: IAccount): Promise { - // Temporary sync on load until we enable background sync and event listeners - const accountIndex = account.getMetadata().index - const addresses = await account.addresses() - await account.sync({ ...DEFAULT_SYNC_OPTIONS, addresses: addresses.map((a) => a.address) }) - const accountPersistedData = getActiveProfilePersistedAccountData(accountIndex) - let accountState: IAccountState - if (accountPersistedData) { - accountState = await buildAccountState(account, accountPersistedData) - } else { - const [newAccountState, accountPersistedData] = await buildAccountStateAndPersistedData(account) - addAccountPersistedDataToActiveProfile(accountIndex, accountPersistedData) - accountState = newAccountState - } - return accountState -} diff --git a/packages/shared/lib/core/account/actions/resetSelectedAccountIndex.ts b/packages/shared/lib/core/account/actions/resetSelectedAccountIndex.ts deleted file mode 100644 index 209b786e789..00000000000 --- a/packages/shared/lib/core/account/actions/resetSelectedAccountIndex.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { selectedAccountIndex } from '../stores' - -export function resetSelectedAccountIndex(): void { - selectedAccountIndex.set(null) -} diff --git a/packages/shared/lib/core/account/actions/setNextSelectedAccount.ts b/packages/shared/lib/core/account/actions/setNextSelectedAccount.ts deleted file mode 100644 index 83cda7cd429..00000000000 --- a/packages/shared/lib/core/account/actions/setNextSelectedAccount.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { selectedAccount, setSelectedAccount } from '@core/account' -import { nonHiddenActiveAccounts } from '@core/profile' -import { get } from 'svelte/store' - -export function setNextSelectedAccount(): void { - const account = get(selectedAccount) - const otherAccounts = get(nonHiddenActiveAccounts) - if (otherAccounts.length > 0) { - if (account?.hidden) { - const nextSelectedAccountIndex = - otherAccounts[account?.index]?.index ?? otherAccounts[otherAccounts?.length - 1]?.index - setSelectedAccount(nextSelectedAccountIndex) - } - } else { - throw new Error('No accounts to select from') - } -} diff --git a/packages/shared/lib/core/account/actions/setSelectedAccount.ts b/packages/shared/lib/core/account/actions/setSelectedAccount.ts deleted file mode 100644 index 9b04b379a16..00000000000 --- a/packages/shared/lib/core/account/actions/setSelectedAccount.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { get } from 'svelte/store' -import { activeAccounts, updateActiveProfile } from '@core/profile/stores' -import { resetSendOptionIndex } from '@core/wallet/stores' - -import { selectedAccountIndex } from '../stores' -import { clearFilters } from '@core/utils' -import { resetNftDownloadQueue } from '@core/nfts' - -export function setSelectedAccount(index: number): void { - resetNftDownloadQueue(true) - - const account = get(activeAccounts)?.find((_account) => _account.index === index) - if (account) { - selectedAccountIndex.set(index) - updateActiveProfile({ lastUsedAccountIndex: index }) - clearFilters() - resetSendOptionIndex() - } else { - throw new Error(`Account with ID ${index} cannot be found!`) - } -} diff --git a/packages/shared/lib/core/account/actions/syncBalance.ts b/packages/shared/lib/core/account/actions/syncBalance.ts deleted file mode 100644 index ad25435189f..00000000000 --- a/packages/shared/lib/core/account/actions/syncBalance.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { getBalance } from '../api/getBalance' -import { selectedAccount, updateSelectedAccount } from '../stores' -import { updateActiveAccount } from '@core/profile' -import { get } from 'svelte/store' - -export async function syncBalance(accountIndex: number): Promise { - const balances = await getBalance(accountIndex) - if (get(selectedAccount)?.index === accountIndex) { - updateSelectedAccount({ balances }) - } else { - updateActiveAccount(accountIndex, { balances }) - } - return -} diff --git a/packages/shared/lib/core/account/actions/syncVotingPower.ts b/packages/shared/lib/core/account/actions/syncVotingPower.ts deleted file mode 100644 index 2776da58172..00000000000 --- a/packages/shared/lib/core/account/actions/syncVotingPower.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { get } from 'svelte/store' -import { selectedAccountIndex, updateSelectedAccount } from '../stores' -import { getVotingPower } from '../api/getVotingPower' -import { updateActiveAccount } from '@core/profile' - -export async function syncVotingPower(accountIndex = get(selectedAccountIndex)): Promise { - const votingPower = await getVotingPower(accountIndex) - if (get(selectedAccountIndex) === accountIndex) { - updateSelectedAccount({ votingPower }) - } else { - updateActiveAccount(accountIndex, { votingPower }) - } - return -} diff --git a/packages/shared/lib/core/account/api/createAliasIfNecessary.ts b/packages/shared/lib/core/account/api/createAliasIfNecessary.ts deleted file mode 100644 index bf9d068bf00..00000000000 --- a/packages/shared/lib/core/account/api/createAliasIfNecessary.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { IAccountState } from '@core/account/interfaces' - -export async function createAliasIfNecessary(account: IAccountState): Promise { - const { aliases } = await account.getBalance() - if (aliases.length === 0) { - await account.prepareCreateAliasOutput() - await new Promise((resolve) => setTimeout(resolve, 7500)) - } -} diff --git a/packages/shared/lib/core/account/api/getBalance.ts b/packages/shared/lib/core/account/api/getBalance.ts deleted file mode 100644 index 468e6bf0b22..00000000000 --- a/packages/shared/lib/core/account/api/getBalance.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Balance } from '@iota/sdk/out/types' -import { getAccount } from '@core/profile-manager' - -export async function getBalance(index?: number): Promise { - return (await getAccount(index))?.getBalance() -} diff --git a/packages/shared/lib/core/account/api/getParticipationOverview.ts b/packages/shared/lib/core/account/api/getParticipationOverview.ts deleted file mode 100644 index c883f785346..00000000000 --- a/packages/shared/lib/core/account/api/getParticipationOverview.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { ParticipationOverview } from '@iota/sdk/out/types' - -import { getAccount } from '@core/profile-manager/api' - -export async function getParticipationOverview(accountIndex: number, eventId?: string): Promise { - return (await getAccount(accountIndex))?.getParticipationOverview(eventId ? [eventId] : undefined) -} diff --git a/packages/shared/lib/core/account/api/getVotingPower.ts b/packages/shared/lib/core/account/api/getVotingPower.ts deleted file mode 100644 index f3511b240fa..00000000000 --- a/packages/shared/lib/core/account/api/getVotingPower.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { getBalance } from '@core/account/api' - -export async function getVotingPower(index?: number): Promise { - const balance = await getBalance(index) - return balance.baseCoin.votingPower -} diff --git a/packages/shared/lib/core/account/api/index.ts b/packages/shared/lib/core/account/api/index.ts deleted file mode 100644 index 73051d7343b..00000000000 --- a/packages/shared/lib/core/account/api/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './createAliasIfNecessary' -export * from './getBalance' -export * from './getParticipationOverview' -export * from './getVotingPower' -export * from './prepareOutput' diff --git a/packages/shared/lib/core/account/constants/index.ts b/packages/shared/lib/core/account/constants/index.ts deleted file mode 100644 index 1a4ff88c301..00000000000 --- a/packages/shared/lib/core/account/constants/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './default-sync-options.constant' -export * from './max-account-name-length.constant' diff --git a/packages/shared/lib/core/account/constants/max-account-name-length.constant.ts b/packages/shared/lib/core/account/constants/max-account-name-length.constant.ts deleted file mode 100644 index 6c934622745..00000000000 --- a/packages/shared/lib/core/account/constants/max-account-name-length.constant.ts +++ /dev/null @@ -1 +0,0 @@ -export const MAX_ACCOUNT_NAME_LENGTH = 20 diff --git a/packages/shared/lib/core/account/enums/index.ts b/packages/shared/lib/core/account/enums/index.ts deleted file mode 100644 index a88b9ad8d57..00000000000 --- a/packages/shared/lib/core/account/enums/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './account-colors.enum' -export * from './search-algorithm.enum' diff --git a/packages/shared/lib/core/account/errors/index.ts b/packages/shared/lib/core/account/errors/index.ts deleted file mode 100644 index 2c5ddd6a5eb..00000000000 --- a/packages/shared/lib/core/account/errors/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './unable-to-get-bound-account.error' diff --git a/packages/shared/lib/core/account/index.ts b/packages/shared/lib/core/account/index.ts deleted file mode 100644 index 391307033be..00000000000 --- a/packages/shared/lib/core/account/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * from './actions' -export * from './api' -export * from './constants' -export * from './enums' -export * from './errors' -export * from './interfaces' -export * from './stores' -export * from './utils' diff --git a/packages/shared/lib/core/account/interfaces/account-balances.interface.ts b/packages/shared/lib/core/account/interfaces/account-balances.interface.ts deleted file mode 100644 index b81ba9cf4b2..00000000000 --- a/packages/shared/lib/core/account/interfaces/account-balances.interface.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { RequiredStorageDeposit } from '@iota/sdk/out/types' - -export interface IAccountBalances { - aliases: unknown[] - available: number - foundries: unknown[] - nativeToken: Record - nfts: unknown[] - potentiallLockedOutputs: unknown[] - requiredStorageDeposit: RequiredStorageDeposit - total: number -} diff --git a/packages/shared/lib/core/account/interfaces/account.interface.ts b/packages/shared/lib/core/account/interfaces/account.interface.ts deleted file mode 100644 index 553cdca5c94..00000000000 --- a/packages/shared/lib/core/account/interfaces/account.interface.ts +++ /dev/null @@ -1,149 +0,0 @@ -import type { - AccountMetadata, - AddressWithUnspentOutputs, - AliasOutputParams, - Balance, - CreateNativeTokenParams, - ConsolidationParams, - Client, - FilterOptions, - GenerateAddressOptions, - MintNftParams, - OutputData, - OutputParams, - OutputsToClaim, - ParticipationEventMap, - ParticipationEventRegistrationOptions, - ParticipationEventStatus, - ParticipationEventWithNodes, - ParticipationOverview, - PreparedTransactionData, - SendNativeTokensParams, - SendNftParams, - SendParams, - SignedTransactionEssence, - SyncOptions, - Transaction, - TransactionOptions, - FoundryOutput, - HexEncodedAmount, - Output, - INode, - AccountAddress, - PreparedTransaction, - PreparedCreateNativeTokenTransaction, - ParticipationEventType, - ParticipationEventId, - Burn, - WalletEventType, - IAuth, -} from '@iota/sdk/out/types' -import type { - IClientOptions, - GenerateAddressOptions, - LedgerNanoStatus, - INodeInfoWrapper, - SyncOptions, - WalletEvent, - WalletEventType, -} from '@iota/sdk/out/types' -import { WalletApiEventHandler } from '@core/wallet' - -// TODO(2.0): rename to IWallet & check all functions in this interface to make sure they still exist -export interface IAccount { - isStrongholdPasswordAvailable(): Promise - getClient(): Promise - setStrongholdPassword(password: string): Promise - setStrongholdPasswordClearInterval(intervalInMilliseconds?: number): Promise - changeStrongholdPassword(currentPassword: string, newPassword: string): Promise - clearStrongholdPassword(): Promise - addresses(): Promise - addressesWithUnspentOutputs(): Promise - prepareBurn(burn: Burn, transactionOptions?: TransactionOptions): Promise - prepareBurnNativeToken( - tokenId: string, - burnAmount: HexEncodedAmount, - transactionOptions?: TransactionOptions - ): Promise - prepareBurnNft(nftId: string, transactionOptions?: TransactionOptions): Promise - claimOutputs(outputIds: string[]): Promise - prepareConsolidateOutputs(params: ConsolidationParams): Promise - prepareCreateAliasOutput( - params?: AliasOutputParams, - transactionOptions?: TransactionOptions - ): Promise - prepareMeltNativeToken( - tokenId: string, - meltAmount: HexEncodedAmount, - transactionOptions?: TransactionOptions - ): Promise - prepareDecreaseVotingPower(amount: string): Promise - deregisterParticipationEvent(eventId: string): Promise - prepareDestroyAlias(aliasId: string, transactionOptions?: TransactionOptions): Promise - prepareDestroyFoundry(foundryId: string, transactionOptions?: TransactionOptions): Promise - generateEd25519Addresses(amount: number, options?: GenerateAddressOptions): Promise - getBalance(): Promise - getFoundryOutput(tokenId: string): Promise - getIncomingTransaction(transactionId: string): Promise - getMetadata(): AccountMetadata - getOutput(outputId: string): Promise - claimableOutputs(outputs: OutputsToClaim): Promise - getParticipationEvent(eventId: string): Promise - getParticipationEventIds(node: INode, eventType?: ParticipationEventType): Promise - getParticipationEvents(): Promise - getParticipationEventStatus(eventId: string): Promise - getParticipationOverview(eventIds?: string[]): Promise - getTransaction(transactionId: string): Promise - incomingTransactions(): Promise - prepareMintNativeToken( - tokenId: string, - mintAmount: HexEncodedAmount, - transactionOptions?: TransactionOptions - ): Promise - prepareIncreaseVotingPower(amount: string): Promise - prepareCreateNativeToken( - params: CreateNativeTokenParams, - transactionOptions?: TransactionOptions - ): Promise - prepareMintNfts(params: MintNftParams[], transactionOptions?: TransactionOptions): Promise - outputs(filterOptions?: FilterOptions): Promise - prepareOutput(params: OutputParams, transactionOptions?: TransactionOptions): Promise - pendingTransactions(): Promise - prepareSend(params: SendParams[], options?: TransactionOptions): Promise - prepareTransaction(outputs: Output[], options?: TransactionOptions): Promise - registerParticipationEvents(options: ParticipationEventRegistrationOptions): Promise - retryTransactionUntilIncluded(transactionId: string, interval?: number, maxAttempts?: number): Promise - send(amount: bigint | string, address: string, transactionOptions?: TransactionOptions): Promise - sendWithParams(params: SendParams[], transactionOptions?: TransactionOptions): Promise - prepareSendNativeTokens( - params: SendNativeTokensParams[], - transactionOptions?: TransactionOptions - ): Promise - prepareSendNft(params: SendNftParams[], transactionOptions?: TransactionOptions): Promise - sendOutputs(outputs: Output[], transactionOptions?: TransactionOptions): Promise - setAlias(alias: string): Promise - setDefaultSyncOptions(options: SyncOptions): Promise - signTransactionEssence(preparedTransactionData: PreparedTransactionData): Promise - prepareStopParticipating(eventId: string): Promise - signAndSubmitTransaction(preparedTransactionData: PreparedTransactionData): Promise - submitAndStoreTransaction(signedTransactionData: SignedTransactionEssence): Promise - sync(options?: SyncOptions): Promise - transactions(): Promise - unspentOutputs(filterOptions?: FilterOptions): Promise - prepareVote(eventId?: string, answers?: number[]): Promise - listen(eventTypes: WalletEventType[], callback: WalletApiEventHandler): Promise - clearListeners(eventTypes: WalletEventType[]): Promise - backup(destination: string, password: string): Promise - destroy(): Promise - emitTestEvent(event: WalletEvent): Promise - restoreBackup( - source: string, - password: string, - ignoreIfCoinTypeMismatch: boolean, - ignoreIfBech32Mismatch: string - ): Promise - setClientOptions(options: IClientOptions): Promise - startBackgroundSync(options?: SyncOptions, intervalInMilliseconds?: number): Promise - stopBackgroundSync(): Promise - updateNodeAuth(url: string, auth?: IAuth): Promise -} diff --git a/packages/shared/lib/core/account/interfaces/index.ts b/packages/shared/lib/core/account/interfaces/index.ts deleted file mode 100644 index 96cac9a4d35..00000000000 --- a/packages/shared/lib/core/account/interfaces/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './account-state.interface' -export * from './account.interface' -export * from './address-with-outputs.interface' -export * from './persisted-account-data.interface' diff --git a/packages/shared/lib/core/account/stores/index.ts b/packages/shared/lib/core/account/stores/index.ts deleted file mode 100644 index b716a39369c..00000000000 --- a/packages/shared/lib/core/account/stores/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './selected-account-id.store' -export * from './selected-account.store' diff --git a/packages/shared/lib/core/account/stores/selected-account-id.store.ts b/packages/shared/lib/core/account/stores/selected-account-id.store.ts deleted file mode 100644 index a29b9f53542..00000000000 --- a/packages/shared/lib/core/account/stores/selected-account-id.store.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { writable } from 'svelte/store' - -export const selectedAccountIndex = writable(null) diff --git a/packages/shared/lib/core/account/stores/selected-account.store.ts b/packages/shared/lib/core/account/stores/selected-account.store.ts deleted file mode 100644 index a71d692aae2..00000000000 --- a/packages/shared/lib/core/account/stores/selected-account.store.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { derived, get, Readable } from 'svelte/store' -import type { IAccountState } from '../interfaces' -import { selectedAccountIndex } from '../stores' -import { activeAccounts, updateActiveAccount } from '@core/profile/stores' - -export const selectedAccount: Readable = derived( - [selectedAccountIndex, activeAccounts], - ([$selectedAccountIndex, $activeAccounts]) => { - return $activeAccounts?.find((account) => account.index === $selectedAccountIndex) - } -) - -export function getSelectedAccount(): IAccountState | undefined { - return get(selectedAccount) -} - -export function updateSelectedAccount(payload: Partial): void { - updateActiveAccount(get(selectedAccountIndex), payload) -} diff --git a/packages/shared/lib/core/account/tests/buildBip32Path.test.ts b/packages/shared/lib/core/account/tests/buildBip32Path.test.ts deleted file mode 100644 index 010ac0c6459..00000000000 --- a/packages/shared/lib/core/account/tests/buildBip32Path.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { buildBip32Path } from '../utils/buildBip32Path' - -describe('File: buildBip32Path.ts', () => { - it('should correctly give BIP32 path', () => { - const coinType = 60 - const accountIndex = 1 - const bip32Path = buildBip32Path(coinType, accountIndex) - const expectedBip32Path = "44'/60'/1'/0/0" - - expect(expectedBip32Path).toStrictEqual(bip32Path) - }) -}) diff --git a/packages/shared/lib/core/account/tests/deconstructBip32Path.test.ts b/packages/shared/lib/core/account/tests/deconstructBip32Path.test.ts deleted file mode 100644 index b56ce77d85e..00000000000 --- a/packages/shared/lib/core/account/tests/deconstructBip32Path.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { deconstructBip32Path } from '../utils/deconstructBip32Path' - -describe('File: deconstructBip32Path.ts', () => { - it('should throw error if path not long enough', () => { - expect(() => { - deconstructBip32Path(`44'/60'`) - }).toThrow() - }) - - it('should correctly give BIP32 path', () => { - const bip32Path = deconstructBip32Path(`44/60'/0/1/2`) - const expectedBip32Path = { - coinType: 60, - accountIndex: 0, - change: 1, - addressIndex: 2, - } - - expect(expectedBip32Path).toStrictEqual(bip32Path) - }) -}) diff --git a/packages/shared/lib/core/account/utils/buildBip32Path.ts b/packages/shared/lib/core/account/utils/buildBip32Path.ts deleted file mode 100644 index 04d38f8216a..00000000000 --- a/packages/shared/lib/core/account/utils/buildBip32Path.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function buildBip32Path(coinType: number, accountIndex: number): string { - return `44'/${coinType}'/${accountIndex}'/0/0` -} diff --git a/packages/shared/lib/core/account/utils/deconstructBip32Path.ts b/packages/shared/lib/core/account/utils/deconstructBip32Path.ts deleted file mode 100644 index 29f64cea5f4..00000000000 --- a/packages/shared/lib/core/account/utils/deconstructBip32Path.ts +++ /dev/null @@ -1,26 +0,0 @@ -const BIP_32_LEVELS = 5 - -export function deconstructBip32Path(path: string): { - coinType: number - accountIndex: number - change: number - addressIndex: number -} { - const pathArray = path.split('/') - if (pathArray.length !== BIP_32_LEVELS) { - throw new Error('Invalid BIP-32 path length') - } - - const _path = pathArray.map((p) => { - // eslint-disable-next-line quotes - const sanitizedPath = p.replace("'", '') - return Number(sanitizedPath) - }) - - return { - coinType: _path[1], - accountIndex: _path[2], - change: _path[3], - addressIndex: _path[4], - } -} diff --git a/packages/shared/lib/core/account/utils/getAccountColorById.ts b/packages/shared/lib/core/account/utils/getAccountColorById.ts deleted file mode 100644 index e17c09fddc6..00000000000 --- a/packages/shared/lib/core/account/utils/getAccountColorById.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { visibleActiveAccounts } from '@core/profile/stores/active-accounts.store' -import { get } from 'svelte/store' - -export function getAccountColorById(id: number): string { - return get(visibleActiveAccounts)?.find((account) => account.index === id)?.color -} diff --git a/packages/shared/lib/core/account/utils/getDepositAddress.ts b/packages/shared/lib/core/account/utils/getDepositAddress.ts deleted file mode 100644 index f5c854d5302..00000000000 --- a/packages/shared/lib/core/account/utils/getDepositAddress.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { IAccount } from '@core/account' - -export async function getDepositAddress(account: IAccount): Promise { - const addresses = await account.addresses() - const address = addresses.find((address) => address.internal === false && address.keyIndex === 0) - return address.address -} diff --git a/packages/shared/lib/core/account/utils/getRandomAccountColor.ts b/packages/shared/lib/core/account/utils/getRandomAccountColor.ts deleted file mode 100644 index 23b3f5d337f..00000000000 --- a/packages/shared/lib/core/account/utils/getRandomAccountColor.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { AccountColors } from '../enums' - -export function getRandomAccountColor(): string { - const colors = Object.values(AccountColors).filter((_, i) => !(i % 2)) - return colors[Math.floor(Math.random() * colors.length)].toString() -} diff --git a/packages/shared/lib/core/account/utils/index.ts b/packages/shared/lib/core/account/utils/index.ts deleted file mode 100644 index 28d10cf8981..00000000000 --- a/packages/shared/lib/core/account/utils/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from './buildBip32Path' -export * from './deconstructBip32Path' -export * from './getAccountColorById' -export * from './getBoundAccount' -export * from './getDepositAddress' -export * from './getIconColorFromString' -export * from './getRandomAccountColor' -export * from './sumBalanceForAccounts' -export * from './sumTotalFromOutputs' -export * from './syncAccountsInParallel' -export * from './syncAccountsInSeries' -export * from './validateAccountName' diff --git a/packages/shared/lib/core/account/utils/sumBalanceForAccounts.ts b/packages/shared/lib/core/account/utils/sumBalanceForAccounts.ts deleted file mode 100644 index 12966e538a7..00000000000 --- a/packages/shared/lib/core/account/utils/sumBalanceForAccounts.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { IAccountState } from '@core/account' - -export function sumBalanceForAccounts(accounts: IAccountState[]): number { - return accounts.reduce( - (total: number, account: IAccountState) => (total += Number(account.balances.baseCoin.total)), - 0 - ) -} diff --git a/packages/shared/lib/core/account/utils/syncAccountsInParallel.ts b/packages/shared/lib/core/account/utils/syncAccountsInParallel.ts deleted file mode 100644 index 1e256fc8321..00000000000 --- a/packages/shared/lib/core/account/utils/syncAccountsInParallel.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Balance, SyncOptions } from '@iota/sdk/out/types' - -import { IAccount } from '../interfaces' - -export async function syncAccountsInParallel(syncOptions: SyncOptions, ...accounts: IAccount[]): Promise { - return Promise.all(accounts.map((account) => account?.sync(syncOptions))) -} diff --git a/packages/shared/lib/core/account/utils/syncAccountsInSeries.ts b/packages/shared/lib/core/account/utils/syncAccountsInSeries.ts deleted file mode 100644 index a1dfa4d3d75..00000000000 --- a/packages/shared/lib/core/account/utils/syncAccountsInSeries.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Balance, SyncOptions } from '@iota/sdk/out/types' - -import { IAccount } from '@core/account' - -export async function syncAccountsInSeries(syncOptions: SyncOptions, ...accounts: IAccount[]): Promise { - const accountBalances: Balance[] = [] - for (const account of accounts) { - const balance = await account?.sync(syncOptions) - accountBalances.push(balance) - } - return accountBalances -} diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts index c1af960209e..0b1c420ed39 100644 --- a/packages/shared/lib/core/api/interfaces/api.interface.ts +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -1,13 +1,13 @@ -import { IAccount } from '@core/account' import { SecretManager } from '@iota/sdk' import { AccountId, FoundryId, HexEncodedString, NftId, Output, OutputId, SecretManagerType, TransactionId, WalletOptions, Bech32Address } from '@iota/sdk/out/types' +import { IWallet } from '@core/profile/interfaces' // TODO(2.0): Every method should return a promise (maybe except Utils, needs research) export interface IApi { createSecretManager(options: SecretManagerType): Promise - createAccount(id: string, payload: WalletOptions): Promise + createAccount(id: string, payload: WalletOptions): Promise deleteWallet(id: string): void - getAccount(id: string, walletOptions: WalletOptions): Promise + getAccount(id: string, walletOptions: WalletOptions): Promise clearWalletsFromMemory(): void migrateStrongholdSnapshotV2ToV3( currentPath: string, diff --git a/packages/shared/lib/core/profile/actions/active-accounts/getWalletColorById.ts b/packages/shared/lib/core/profile/actions/active-accounts/getWalletColorById.ts new file mode 100644 index 00000000000..8acb27fb37a --- /dev/null +++ b/packages/shared/lib/core/profile/actions/active-accounts/getWalletColorById.ts @@ -0,0 +1,7 @@ +import { get } from 'svelte/store' +import { visibleActiveWallets } from '../../stores' + +// TODO(2.0) Fix all usages +export function getWalletColorById(walletId: string): string { + return get(visibleActiveWallets)?.find((wallet) => wallet.id === walletId)?.color as string +} diff --git a/packages/shared/lib/core/profile/actions/active-accounts/index.ts b/packages/shared/lib/core/profile/actions/active-accounts/index.ts index cd6795603e1..88085deb5d3 100644 --- a/packages/shared/lib/core/profile/actions/active-accounts/index.ts +++ b/packages/shared/lib/core/profile/actions/active-accounts/index.ts @@ -1,2 +1,3 @@ export * from './findActiveAccountWithAddress' export * from './updateActiveAccountPersistedData' +export * from './getWalletColorById' \ No newline at end of file diff --git a/packages/shared/lib/core/profile/actions/active-accounts/updateActiveAccountPersistedData.ts b/packages/shared/lib/core/profile/actions/active-accounts/updateActiveAccountPersistedData.ts index 38e6680114b..a6345469354 100644 --- a/packages/shared/lib/core/profile/actions/active-accounts/updateActiveAccountPersistedData.ts +++ b/packages/shared/lib/core/profile/actions/active-accounts/updateActiveAccountPersistedData.ts @@ -1,14 +1,15 @@ -import { selectedAccountIndex, updateSelectedAccount } from '@core/account/stores' -import { IPersistedAccountData } from '@core/account/interfaces' -import { updateAccountPersistedDataOnActiveProfile } from '@core/profile' +import { updateWalletPersistedDataOnActiveProfile } from '@core/profile' +import { IPersistedWalletData, updateSelectedWallet } from 'shared/lib/core/account' +import { selectedWalletId } from 'shared/lib/core/wallet/stores/selected-wallet-id.store' import { get } from 'svelte/store' +// TODO(2.0) Update this this and fix all usages export function updateActiveAccountPersistedData( - acccountIndex: number, - partialAccountPersistedData: Partial + walletId: string, + partialWalletPersistedData: Partial ): void { - if (get(selectedAccountIndex) === acccountIndex) { - updateSelectedAccount(partialAccountPersistedData) + if (get(selectedWalletId) === walletId) { + updateSelectedWallet(partialWalletPersistedData) } - updateAccountPersistedDataOnActiveProfile(acccountIndex, partialAccountPersistedData) + updateWalletPersistedDataOnActiveProfile(walletId, partialWalletPersistedData) } diff --git a/packages/shared/lib/core/profile/actions/active-profile/index.ts b/packages/shared/lib/core/profile/actions/active-profile/index.ts index a39cdddbf6d..4f903793ec2 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/index.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/index.ts @@ -4,7 +4,7 @@ export * from './checkAndUpdateActiveProfileNetwork' export * from './getBaseToken' export * from './getCoinType' export * from './getNetworkHrp' -export * from './loadAccounts' +export * from './loadWallets' export * from './loadPersistedProfileIntoActiveProfile' export * from './lockStronghold' export * from './login' diff --git a/packages/shared/lib/core/profile/actions/active-profile/loadAccounts.ts b/packages/shared/lib/core/profile/actions/active-profile/loadAccounts.ts deleted file mode 100644 index 91335db9bb8..00000000000 --- a/packages/shared/lib/core/profile/actions/active-profile/loadAccounts.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { loadAccount } from '@core/account' -import { getAccounts } from '@core/profile-manager' -import { get } from 'svelte/store' -import { activeAccounts, activeProfile } from '../../stores' - -export async function loadAccounts(): Promise { - const { hasLoadedAccounts } = get(activeProfile) - const accountsResponse = await getAccounts() - if (accountsResponse.length === 0) { - hasLoadedAccounts.set(true) - return - } - if (accountsResponse) { - const loadedAccounts = await Promise.all( - accountsResponse?.map((accountResponse) => loadAccount(accountResponse)) - ) - activeAccounts.set(loadedAccounts.sort((a, b) => a.getMetadata().index - b.getMetadata().index)) - hasLoadedAccounts.set(true) - } -} diff --git a/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts b/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts new file mode 100644 index 00000000000..55bec9b1e44 --- /dev/null +++ b/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts @@ -0,0 +1,20 @@ +import { loadWallet } from '@core/wallet' +import { get } from 'svelte/store' +import { activeAccounts, activeProfile } from '../../stores' +import { getAccounts } from '../getAccounts' + +export async function loadWallets(): Promise { + const { hasLoadedAccounts } = get(activeProfile) + const walletResponse = await getAccounts() + if (walletResponse.length === 0) { + hasLoadedAccounts.set(true) + return + } + if (walletResponse) { + const loadedWallets = await Promise.all( + walletResponse?.map((accountResponse) => loadWallet(accountResponse)) + ) + activeAccounts.set(loadedWallets) // TODO(2.0) We can't sort this like this: sort((a, b) => a.getMetadata().index - b.getMetadata().index) + hasLoadedAccounts.set(true) + } +} diff --git a/packages/shared/lib/core/profile/actions/active-profile/login.ts b/packages/shared/lib/core/profile/actions/active-profile/login.ts index 7553b108da4..7038c422b8c 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/login.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/login.ts @@ -43,7 +43,7 @@ import { updateActiveProfile, } from '../../stores' import { isLedgerProfile } from '../../utils' -import { loadAccounts } from './loadAccounts' +import { loadAccounts } from './loadWallets' import { logout } from './logout' import { subscribeToWalletApiEventsForActiveProfile } from './subscribeToWalletApiEventsForActiveProfile' import { checkAndUpdateActiveProfileNetwork } from './checkAndUpdateActiveProfileNetwork' diff --git a/packages/shared/lib/core/profile/actions/active-profile/logout.ts b/packages/shared/lib/core/profile/actions/active-profile/logout.ts index 31ce84e7372..d851abc2c54 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/logout.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/logout.ts @@ -1,6 +1,6 @@ import { get } from 'svelte/store' -import { resetSelectedAccountIndex } from '@core/account/actions' +import { resetSelectedWalletId } from '@core/account/actions' import { clearSelectedParticipationEventStatus, resetProposalOverviews, @@ -50,7 +50,7 @@ function cleanupProfileState(clearActiveProfile: boolean): void { loggedIn.set(false) lastActiveAt.set(new Date()) hasLoadedAccounts.set(false) - resetSelectedAccountIndex() + resetSelectedWalletId() void stopDownloadingNftMediaFromQueue() diff --git a/packages/shared/lib/core/profile/actions/createAccount.ts b/packages/shared/lib/core/profile/actions/createWallet.ts similarity index 85% rename from packages/shared/lib/core/profile/actions/createAccount.ts rename to packages/shared/lib/core/profile/actions/createWallet.ts index fd61d197fa9..331308559dc 100644 --- a/packages/shared/lib/core/profile/actions/createAccount.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -1,7 +1,7 @@ -import { IAccount } from '@core/account'; import { api } from '@core/api'; import { generateRandomId } from '@core/utils'; import { get } from 'svelte/store'; +import { IWallet } from '../interfaces'; import { activeProfile as activeProfileStore } from '../stores'; import { getStorageDirectoryOfProfile } from '../utils'; @@ -12,7 +12,7 @@ import { getStorageDirectoryOfProfile } from '../utils'; - __wallet1__/ - __wallet2__/ */ -export async function createAccount(): Promise { +export async function createWallet(): Promise { const id = generateRandomId(); const storagePath = await getStorageDirectoryOfProfile(id); const snapshotPath = '' @@ -27,7 +27,7 @@ export async function createAccount(): Promise { } }, } - const wallet = api.createAccount(id, { + const wallet = await api.createAccount(id, { ...walletOptions, storagePath }); diff --git a/packages/shared/lib/core/profile/actions/deleteAccount.ts b/packages/shared/lib/core/profile/actions/deleteWallet.ts similarity index 54% rename from packages/shared/lib/core/profile/actions/deleteAccount.ts rename to packages/shared/lib/core/profile/actions/deleteWallet.ts index 5b3060b2e99..b32591f0e18 100644 --- a/packages/shared/lib/core/profile/actions/deleteAccount.ts +++ b/packages/shared/lib/core/profile/actions/deleteWallet.ts @@ -1,16 +1,16 @@ import { get } from 'svelte/store' -import { setSelectedAccount } from '@core/account/actions' import { api } from '@core/api' import { AppContext } from '@core/app/enums' -import { CannotRemoveAccountError, RemoveNotLastAccountError } from '@core/profile-manager/errors' -import { removeAccountFromActiveAccounts, visibleActiveAccounts } from '@core/profile/stores' import { routerManager } from '@core/router/stores' +import { visibleActiveWallets } from '../stores' +import { CannotRemoveAccountError, RemoveNotLastAccountError, setSelectedWallet } from '@core/wallet' // TODO(2.0): replace all its usage, before it was numeric index, now it's id export async function deleteWallet(id: string): Promise { - const accountToBeDeleted = get(visibleActiveAccounts).find((account) => account?.id === id) - const accounts = get(visibleActiveAccounts) + const accounts = get(visibleActiveWallets) + const accountToBeDeleted = accounts.find((account) => account?.id === id) + if (accountToBeDeleted !== accounts[accounts.length - 1]) { throw new RemoveNotLastAccountError() @@ -18,8 +18,8 @@ export async function deleteWallet(id: string): Promise { try { await api.deleteWallet(id) - removeAccountFromActiveAccounts(id) - setSelectedAccount(get(visibleActiveAccounts)?.[0]?.index ?? null) + // TODO(2.0) do we need this?: removeAccountFromActiveAccounts(id) + setSelectedWallet(accounts[0]?.id ?? null) get(routerManager).resetRouterForAppContext(AppContext.Dashboard) } catch (err) { throw new CannotRemoveAccountError() diff --git a/packages/shared/lib/core/profile/actions/getAccount.ts b/packages/shared/lib/core/profile/actions/getAccount.ts index 7ca092c412d..9e47fdaabc4 100644 --- a/packages/shared/lib/core/profile/actions/getAccount.ts +++ b/packages/shared/lib/core/profile/actions/getAccount.ts @@ -1,13 +1,13 @@ import { get } from 'svelte/store' -import { IAccount, IPersistedAccountData } from '@core/account' -import { api } from '../../api/api' -import { IPersistedProfile } from '../interfaces' +import { api } from '@core/api' +import { IPersistedWalletData } from '@core/wallet/interfaces' +import { IPersistedProfile, IWallet } from '../interfaces' import {activeProfile } from '../stores' // TODO(2.0): Fix all usages of this method, before numeric index, now string -export async function getAccount(id: string): Promise { +export async function getWallet(walletId: string): Promise { const profile: IPersistedProfile = get(activeProfile) - const persistedWallet: IPersistedAccountData = profile?.accountPersistedData[id] - const wallet = await api.getAccount(id, persistedWallet.walletOptions) + const persistedWallet: IPersistedWalletData = profile?.accountPersistedData[walletId] + const wallet = await api.getAccount(walletId, persistedWallet.walletOptions) return wallet } diff --git a/packages/shared/lib/core/profile/actions/getAccounts.ts b/packages/shared/lib/core/profile/actions/getAccounts.ts index 6f6bc63dea6..8b2a7f93f68 100644 --- a/packages/shared/lib/core/profile/actions/getAccounts.ts +++ b/packages/shared/lib/core/profile/actions/getAccounts.ts @@ -1,13 +1,13 @@ -import { IAccount } from '@core/account' import { api } from '@core/api' import { activeProfile } from '@core/profile/stores' import { get } from 'svelte/store' +import { IWallet } from '../interfaces/wallet.interface' // TODO(2.0): Fix all usages of this method // TODO(2.0): Finalize when new profile is ready -export async function getAccounts(): Promise { +export async function getAccounts(): Promise { const profile = get(activeProfile) - let wallets: IAccount[] = [] + let wallets: IWallet[] = [] if (profile.accountPersistedData) { wallets = await Promise.all(Object.entries(profile.accountPersistedData) .map(([id, data]) => api.getAccount(id, data.walletOptions))) diff --git a/packages/shared/lib/core/profile/actions/index.ts b/packages/shared/lib/core/profile/actions/index.ts index 945afc3d231..da3437e5ef9 100644 --- a/packages/shared/lib/core/profile/actions/index.ts +++ b/packages/shared/lib/core/profile/actions/index.ts @@ -1,9 +1,9 @@ -export * from './createAccount' +export * from './createWallet' export * from './getAccount' export * from './getAccounts' export * from './recoverAccounts' export * from './clearProfileFromMemory' -export * from './deleteAccount' +export * from './deleteWallet' export * from './active-accounts' export * from './active-profile' diff --git a/packages/shared/lib/core/profile/interfaces/index.ts b/packages/shared/lib/core/profile/interfaces/index.ts index c34e63fbb87..93755be5c23 100644 --- a/packages/shared/lib/core/profile/interfaces/index.ts +++ b/packages/shared/lib/core/profile/interfaces/index.ts @@ -5,3 +5,4 @@ export * from './profile-settings.interface' export * from './profile.interface' export * from './chrysalis-persisted-profile.interface' export * from './recover-account-payload.interface' +export * from './wallet.interface' diff --git a/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts b/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts index 40adc1571eb..63ff1070067 100644 --- a/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts @@ -1,8 +1,8 @@ -import { IPersistedAccountData } from '@core/account' import { ClientOptions, IPersistedNetwork } from '@core/network' import { INft } from '@core/nfts' import { StrongholdVersion } from '@core/stronghold/enums' import { SecretManagerType } from '@iota/sdk/out/types' +import { IPersistedWalletData } from '@core/wallet/interfaces' import { ProfileType } from '../enums' import { IProfileSettings } from './profile-settings.interface' @@ -13,12 +13,12 @@ export interface IPersistedProfile { network: IPersistedNetwork lastStrongholdBackupTime: Date settings: IProfileSettings - accountPersistedData: { - [accountId: string]: IPersistedAccountData + accountPersistedData: { // TODO(2.0) Shouldn't we rename this field? + [accountId: string]: IPersistedWalletData } isDeveloperProfile: boolean hasVisitedDashboard?: boolean - lastUsedAccountIndex?: number + lastUsedWalletId?: string // Todo(2.0) Fix all usages of lastUsedAccountIndex clientOptions: ClientOptions secretManagerOptions: SecretManagerType, forceAssetRefresh: boolean diff --git a/packages/shared/lib/core/profile/interfaces/profile.interface.ts b/packages/shared/lib/core/profile/interfaces/profile.interface.ts index ec6369fb169..804186f4728 100644 --- a/packages/shared/lib/core/profile/interfaces/profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/profile.interface.ts @@ -2,7 +2,7 @@ import { Writable } from 'svelte/store' import { IPersistedProfile } from './persisted-profile.interface' export interface IProfile extends IPersistedProfile { - hasLoadedAccounts: Writable + hasLoadedAccounts: Writable // TODO(2.0) Shouldn't we rename this field? isStrongholdLocked: Writable shouldOpenProfileModal: Writable internalTransfersInProgress: Writable<{ diff --git a/packages/shared/lib/core/profile/interfaces/wallet.interface.ts b/packages/shared/lib/core/profile/interfaces/wallet.interface.ts new file mode 100644 index 00000000000..779c53ed436 --- /dev/null +++ b/packages/shared/lib/core/profile/interfaces/wallet.interface.ts @@ -0,0 +1,6 @@ +import { Wallet } from '@iota/sdk' + +// TODO(2.0): rename to IWallet & check all functions in this interface to make sure they still exist +export interface IWallet extends Wallet { + id: string +} \ No newline at end of file diff --git a/packages/shared/lib/core/profile/stores/active-accounts.store.ts b/packages/shared/lib/core/profile/stores/active-accounts.store.ts deleted file mode 100644 index 2aa6b0993b5..00000000000 --- a/packages/shared/lib/core/profile/stores/active-accounts.store.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { IAccountState } from '@core/account' -import { derived, Readable, writable } from 'svelte/store' -import { activeProfile } from './active-profile.store' - -export const activeAccounts = writable([]) - -export function removeAccountFromActiveAccounts(index: number): void { - activeAccounts?.update((state) => state.filter((account) => account.index !== index)) -} - -export function addAccountToActiveAccounts(account: IAccountState): void { - activeAccounts?.update((state) => [...state, account]) -} - -export function updateActiveAccount(index: number, partialAccount: Partial): void { - activeAccounts.update((state) => [ - ...state.map((account) => (account.index === index ? { ...account, ...partialAccount } : account)), - ]) -} - -export const nonHiddenActiveAccounts: Readable = derived([activeAccounts], ([$activeAccounts]) => { - if (!$activeAccounts) { - return [] - } - const unsortedNonHiddenAccounts = $activeAccounts?.filter((account) => !account?.hidden) - return unsortedNonHiddenAccounts.sort((a, b) => a.index - b.index) -}) - -export const visibleActiveAccounts: Readable = derived( - [activeAccounts, activeProfile], - ([$activeAccounts, $activeProfile]) => { - if (!$activeAccounts || !$activeProfile) { - return [] - } - const unsortedVisibleAccounts = - $activeProfile?.showHiddenAccounts ?? false - ? $activeAccounts - : $activeAccounts?.filter((account) => !account?.hidden) - return unsortedVisibleAccounts.sort((a, b) => a.index - b.index) - } -) diff --git a/packages/shared/lib/core/profile/stores/active-profile.store.ts b/packages/shared/lib/core/profile/stores/active-profile.store.ts index fb6b3720540..4629b695962 100644 --- a/packages/shared/lib/core/profile/stores/active-profile.store.ts +++ b/packages/shared/lib/core/profile/stores/active-profile.store.ts @@ -1,6 +1,5 @@ import { get, writable } from 'svelte/store' - -import type { IPersistedAccountData } from '@core/account/interfaces' +import { IPersistedWalletData } from '@core/wallet/interfaces' import { INITIAL_ACTIVE_PROFILE } from '../constants' import type { IProfile, IProfileSettings } from '../interfaces' @@ -22,34 +21,34 @@ export function updateActiveProfileSettings(payload: Partial): })) } -export function addAccountPersistedDataToActiveProfile( - accountIndex: number, - accountPersistedData: IPersistedAccountData +export function addWalletPersistedDataToActiveProfile( + walletId: string, + walletPersistedData: IPersistedWalletData ): void { activeProfile?.update((state) => { if (!state?.accountPersistedData) { state.accountPersistedData = {} } - state.accountPersistedData[accountIndex] = accountPersistedData + state.accountPersistedData[walletId] = walletPersistedData return state }) } -export function getActiveProfilePersistedAccountData(accountIndex: number): IPersistedAccountData | undefined { - return get(activeProfile)?.accountPersistedData?.[accountIndex] +export function getActiveProfilePersistedWalletData(walletId: string): IPersistedWalletData | undefined { + return get(activeProfile)?.accountPersistedData?.[walletId] } -export function updateAccountPersistedDataOnActiveProfile( - accountIndex: number, - partialAccountPersistedData: Partial +export function updateWalletPersistedDataOnActiveProfile( + walletId: string, + partialWalletPersistedData: Partial ): void { activeProfile?.update((state) => { if (!state?.accountPersistedData) { state.accountPersistedData = {} } - state.accountPersistedData[accountIndex] = { - ...state?.accountPersistedData?.[accountIndex], - ...partialAccountPersistedData, + state.accountPersistedData[walletId] = { + ...state?.accountPersistedData?.[walletId], + ...partialWalletPersistedData, } return state }) diff --git a/packages/shared/lib/core/profile/stores/active-wallets.store.ts b/packages/shared/lib/core/profile/stores/active-wallets.store.ts new file mode 100644 index 00000000000..76dcb6482cb --- /dev/null +++ b/packages/shared/lib/core/profile/stores/active-wallets.store.ts @@ -0,0 +1,41 @@ +import { derived, Readable, writable } from 'svelte/store' +import { IWalletState } from '../../wallet' +import { activeProfile } from './active-profile.store' + +export const activeWallets = writable([]) + +export function removewalletFromactiveWallets(walletId: string): void { + activeWallets?.update((state) => state.filter((wallet) => wallet.id !== walletId)) +} + +export function addwalletToactiveWallets(wallet: IWalletState): void { + activeWallets?.update((state) => [...state, wallet]) +} + +export function updateActiveWallet(walletId: string, partialwallet: Partial): void { + activeWallets.update((state) => [ + ...state.map((wallet) => (wallet.id === walletId ? { ...wallet, ...partialwallet } as IWalletState: wallet)), + ]) +} + +export const nonHiddenActiveWallets: Readable = derived([activeWallets], ([$activeWallets]) => { + if (!$activeWallets) { + return [] + } + const unsortedNonHiddenwallets = $activeWallets?.filter((wallet) => !wallet?.hidden) + return unsortedNonHiddenwallets // TODO(2.0): Sort them: .sort((a, b) => a.index - b.index) +}) + +export const visibleActiveWallets: Readable = derived( + [activeWallets, activeProfile], + ([$activeWallets, $activeProfile]) => { + if (!$activeWallets || !$activeProfile) { + return [] + } + const unsortedVisiblewallets = + $activeProfile?.showHiddenAccounts ?? false + ? $activeWallets + : $activeWallets?.filter((wallet) => !wallet?.hidden) + return unsortedVisiblewallets // TODO(2.0): Sort them: .sort((a, b) => a.index - b.index) + } +) diff --git a/packages/shared/lib/core/profile/stores/index.ts b/packages/shared/lib/core/profile/stores/index.ts index 01b4dd1bcaa..9d5438cb996 100644 --- a/packages/shared/lib/core/profile/stores/index.ts +++ b/packages/shared/lib/core/profile/stores/index.ts @@ -1,6 +1,6 @@ export * from './active-profile-id.store' export * from './active-profile.store' -export * from './active-accounts.store' +export * from './active-wallets.store' export * from './current-profile-version.store' export * from './is-software-profile.store' export * from './is-destroying-manager.store' diff --git a/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts b/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts index 9088cc6dd9e..f0f89406b3f 100644 --- a/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts +++ b/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts @@ -1,4 +1,4 @@ -import { syncBalance } from '@core/account/actions/syncBalance' +import { syncBalance } from 'shared/lib/core/wallet/actions/syncBalance' import { updateNftInAllAccountNfts } from '@core/nfts' import { ActivityAsyncStatus, ActivityDirection, ActivityType } from '@core/wallet/enums' import { allAccountActivities } from '../../stores' diff --git a/packages/shared/lib/core/account/actions/buildAccountState.ts b/packages/shared/lib/core/wallet/actions/buildWalletState.ts similarity index 56% rename from packages/shared/lib/core/account/actions/buildAccountState.ts rename to packages/shared/lib/core/wallet/actions/buildWalletState.ts index d6e3c73c702..67e275c5203 100644 --- a/packages/shared/lib/core/account/actions/buildAccountState.ts +++ b/packages/shared/lib/core/wallet/actions/buildWalletState.ts @@ -1,14 +1,15 @@ import { Balance } from '@iota/sdk/out/types' +import { IPersistedWalletData } from '../interfaces/persisted-account-data.interface'; +import { IWalletState } from '../interfaces/account-state.interface'; +import { IWallet } from '@core/profile/interfaces'; +import { getDepositAddress } from '../utils/getDepositAddress'; +import { getAddressesWithOutputs } from './getAddressesWithOutputs'; -import { getDepositAddress } from '@core/account/utils' - -import { IAccount, IAccountState, IPersistedAccountData } from '../interfaces' -import { getAddressesWithOutputs } from './getAddressesWithOutputs' - -export async function buildAccountState( - account: IAccount, - accountPersistedData: IPersistedAccountData -): Promise { +// TODO(2.0): Fix usages of buildAccountState +export async function buildWalletState( + wallet: IWallet, + walletPersistedData: IPersistedWalletData +): Promise { let balances: Balance = { baseCoin: { total: BigInt(0), @@ -16,7 +17,7 @@ export async function buildAccountState( votingPower: '0', }, requiredStorageDeposit: { - alias: BigInt(0), + account: BigInt(0), basic: BigInt(0), foundry: BigInt(0), nft: BigInt(0), @@ -25,24 +26,23 @@ export async function buildAccountState( nfts: [], foundries: [], potentiallyLockedOutputs: {}, - aliases: [], + accounts: [], } - const accountIndex = 0; // TODO(2.0): CHANGE THIS + let depositAddress = '' let votingPower = '' try { - balances = await account.getBalance() - depositAddress = await getDepositAddress(account) + balances = await wallet.getBalance() + depositAddress = await getDepositAddress(wallet) votingPower = balances.baseCoin.votingPower } catch (err) { console.error(err) } - const addressesWithOutputs = await getAddressesWithOutputs(account) + const addressesWithOutputs = await getAddressesWithOutputs(wallet) return { - index: accountIndex, - ...account, - ...accountPersistedData, + ...wallet, + ...walletPersistedData, depositAddress, balances, hasVotingPowerTransactionInProgress: false, @@ -51,5 +51,5 @@ export async function buildAccountState( isTransferring: false, votingPower, addressesWithOutputs, - } as IAccountState + } as IWalletState } diff --git a/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts b/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts new file mode 100644 index 00000000000..30697d112e1 --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts @@ -0,0 +1,23 @@ +import { localize } from '@core/i18n' +import { getRandomWalletColor } from '@core/wallet/utils' +import { IWallet } from '@core/profile/interfaces'; +import { IWalletState } from '../interfaces/account-state.interface'; +import { IPersistedWalletData } from '../interfaces/persisted-account-data.interface'; +import { buildWalletState } from './buildWalletState' + +export async function buildWalletStateAndPersistedData( + wallet: IWallet, + name?: string, + color?: string +): Promise<[IWalletState, IPersistedWalletData]> { + + const persistedWalletData: IPersistedWalletData = { + name: name || `${localize('general.account')}`, + color: color || getRandomWalletColor(), + hidden: false, + shouldRevote: false, + walletOptions: {} + } + const accountState = await buildWalletState(wallet, persistedWalletData) + return [accountState, persistedWalletData] +} diff --git a/packages/shared/lib/core/wallet/actions/createNewWallet.ts b/packages/shared/lib/core/wallet/actions/createNewWallet.ts new file mode 100644 index 00000000000..6b5ddfcb504 --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/createNewWallet.ts @@ -0,0 +1,33 @@ +import { localize } from '@core/i18n' +import { activeAccounts, addWalletPersistedDataToActiveProfile, addAccountToActiveAccounts, createWallet } from '@core/profile' +import { addEmptyAccountActivitiesToAllAccountActivities } from '@core/wallet/stores' +import { get } from 'svelte/store' + +import { DEFAULT_SYNC_OPTIONS } from '../../account/constants' +import { IWalletState } from '../../account/interfaces' + +import { buildWalletStateAndPersistedData } from './buildWalletStateAndPersistedData' + +export async function createNewWallet(name?: string, color?: string): Promise { + // 1. Get the wallet name + const walletName = name || `${localize('general.account')} ${(get(activeAccounts)?.length ?? 0) + 1}`; + + // 2. Create the wallet instance + const wallet = await createWallet() + + // 3. Sync the wallet with the Node + // TODO(2.0): test & fix sync when we have iota2.0 nodes + //await account.sync(DEFAULT_SYNC_OPTIONS) + + // 4. Create a wrapper over the wallet instance and the persisted data + const [walletState, accountPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName, color) + + // TODO(2.0) Fix + // addAccountToActiveAccounts(walletState) + addWalletPersistedDataToActiveProfile(walletState.id, accountPersistedData) + // TODO(2.0) Fix + // addEmptyAccountActivitiesToAllAccountActivities(walletState.id) + + + return walletState +} diff --git a/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts index fd22c62bb85..da74ffe0c22 100644 --- a/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts @@ -1,7 +1,7 @@ import { Event, NewOutputWalletEvent, OutputType, WalletEventType } from '@iota/sdk/out/types' import { getAddressesWithOutputs } from '@core/account' -import { syncBalance } from '@core/account/actions/syncBalance' +import { syncBalance } from 'shared/lib/core/wallet/actions/syncBalance' import { addNftsToDownloadQueue, addOrUpdateNftInAllAccountNfts, buildNftFromNftOutput } from '@core/nfts' import { checkAndRemoveProfilePicture } from '@core/profile/actions' import { activeAccounts, updateActiveAccount } from '@core/profile/stores' @@ -16,10 +16,8 @@ import { addActivitiesToAccountActivitiesInAllAccountActivities, allAccountActivities, } from '@core/wallet/stores/all-account-activities.store' -import { getBech32AddressFromAddressTypes } from '@core/wallet/utils/getBech32AddressFromAddressTypes' -import { preprocessGroupedOutputs } from '@core/wallet/utils/outputs/preprocessGroupedOutputs' import { get } from 'svelte/store' -import { validateWalletApiEvent } from '../../../profile-manager/utils' +import { validateWalletApiEvent, getBech32AddressFromAddressTypes, preprocessGroupedOutputs} from '@core/wallet/utils' export function handleNewOutputEvent(error: Error, rawEvent: Event): void { const { accountIndex, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.NewOutput) @@ -29,6 +27,7 @@ export function handleNewOutputEvent(error: Error, rawEvent: Event): void { } } +// TODO(2.0) Use wallet instead of accounts and fix all usages export async function handleNewOutputEventInternal(accountIndex: number, payload: NewOutputWalletEvent): Promise { const account = get(activeAccounts)?.find((account) => account.index === accountIndex) const outputData = payload.output diff --git a/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts index 556424d9c3a..331ca2ad534 100644 --- a/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts @@ -1,29 +1,30 @@ +// TODO(2.0) Fix all of events code, blocked by https://github.com/iotaledger/iota-sdk/issues/1708 + import { Event, SpentOutputWalletEvent, WalletEventType } from '@iota/sdk/out/types' -import { syncBalance } from '@core/account/actions/syncBalance' +import { syncBalance } from 'shared/lib/core/wallet/actions/syncBalance' import { getNftByIdFromAllAccountNfts, updateNftInAllAccountNfts } from '@core/nfts' -import { activeAccounts, updateActiveAccount } from '@core/profile/stores' -import { ActivityAsyncStatus, ActivityType } from '@core/wallet' +import { ActivityAsyncStatus, ActivityType, validateWalletApiEvent } from '@core/wallet' import { allAccountActivities, updateAsyncDataByTransactionId } from '@core/wallet/stores/all-account-activities.store' import { get } from 'svelte/store' -import { validateWalletApiEvent } from '../../../profile-manager/utils' -import { getAddressesWithOutputs } from '@core/account' +import { activeWallets } from 'shared/lib/core/profile' export async function handleSpentOutputEvent(error: Error, rawEvent: Event): Promise { - const { accountIndex, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.SpentOutput) + const { walletId, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.SpentOutput) const type = payload.type if (type === WalletEventType.SpentOutput) { - await handleSpentOutputEventInternal(accountIndex, payload as SpentOutputWalletEvent) + await handleSpentOutputEventInternal(walletId, payload as SpentOutputWalletEvent) } } +// TODO(2.0) Fix all usages export async function handleSpentOutputEventInternal( - accountIndex: number, + walletId: string, payload: SpentOutputWalletEvent ): Promise { - const account = get(activeAccounts)?.find((account) => account.index === accountIndex) + const account = get(activeWallets)?.find((wallet) => wallet.id === walletId) const output = payload.output - await syncBalance(accountIndex) + await syncBalance(walletId) if (account) { const addressesWithOutputs = await getAddressesWithOutputs(account) updateActiveAccount(account.index, { addressesWithOutputs }) diff --git a/packages/shared/lib/core/account/actions/findBalances.ts b/packages/shared/lib/core/wallet/actions/findBalances.ts similarity index 98% rename from packages/shared/lib/core/account/actions/findBalances.ts rename to packages/shared/lib/core/wallet/actions/findBalances.ts index 5bcbc3281fd..35b21c8094c 100644 --- a/packages/shared/lib/core/account/actions/findBalances.ts +++ b/packages/shared/lib/core/wallet/actions/findBalances.ts @@ -1,4 +1,6 @@ -import { DEFAULT_SYNC_OPTIONS, SearchAlgorithmType } from '@core/account' +// TODO(2.0) Fix all of this after having implemented the recover wallets + +import { DEFAULT_SYNC_OPTIONS, SearchAlgorithmType } from '@core/wallet' import { updateLedgerNanoStatus } from '@core/ledger' import { BALANCE_FINDER_ACCOUNT_RECOVERY_CONFIGURATION, diff --git a/packages/shared/lib/core/account/actions/getAddressesWithOutputs.ts b/packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts similarity index 61% rename from packages/shared/lib/core/account/actions/getAddressesWithOutputs.ts rename to packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts index 1bf4dc8b265..731ea9cb7ff 100644 --- a/packages/shared/lib/core/account/actions/getAddressesWithOutputs.ts +++ b/packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts @@ -1,9 +1,11 @@ -import { AddressWithOutputs, IAccount, IAccountState } from '../interfaces' -import { getBech32AddressFromAddressTypes } from '@core/wallet' +import { AddressWithOutputs, getBech32AddressFromAddressTypes, IWalletState } from '@core/wallet' +import { IWallet } from '@core/profile/interfaces' +import { Address } from '@iota/sdk/out/types' -export async function getAddressesWithOutputs(account: IAccount | IAccountState): Promise { +// TODO(2.0) Fix all usages +export async function getAddressesWithOutputs(account: IWallet | IWalletState): Promise { let addressesWithOutputs: AddressWithOutputs[] = [] - const addresses = await account.addresses() + const addresses: Address[] = [] // await account.accounts const outputs = await account.outputs() const outputMapped: AddressWithOutputs[] = outputs.reduce((acc: AddressWithOutputs[], output) => { @@ -18,9 +20,9 @@ export async function getAddressesWithOutputs(account: IAccount | IAccountState) }, []) addressesWithOutputs = addresses.map((address) => { - const existingAddress = outputMapped.find((a) => a.address === address.address) + const existingAddress = outputMapped.find((a) => a.address === address.toString()) if (!existingAddress) { - return { address: address.address, outputs: [] } + return { address: address.toString(), outputs: [] } } return existingAddress }) diff --git a/packages/shared/lib/core/wallet/actions/getBalance.ts b/packages/shared/lib/core/wallet/actions/getBalance.ts new file mode 100644 index 00000000000..98c24fcbf53 --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/getBalance.ts @@ -0,0 +1,7 @@ +import { Balance } from '@iota/sdk/out/types' +import { getWallet } from '@core/profile/actions' + +// TODO(2.0) Fix all usages +export async function getBalance(walletId: string): Promise { + return (await getWallet(walletId))?.getBalance() +} diff --git a/packages/shared/lib/core/wallet/actions/getParticipationOverview.ts b/packages/shared/lib/core/wallet/actions/getParticipationOverview.ts new file mode 100644 index 00000000000..7aeeea578eb --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/getParticipationOverview.ts @@ -0,0 +1,7 @@ +import type { ParticipationOverview } from '@iota/sdk/out/types' +import { getWallet } from '@core/profile/actions' + +// TODO(2.0) Fix all usages +export async function getParticipationOverview(walletId: string, eventId?: string): Promise { + return (await getWallet(walletId))?.getParticipationOverview(eventId ? [eventId] : undefined) +} diff --git a/packages/shared/lib/core/wallet/actions/getVotingPower.ts b/packages/shared/lib/core/wallet/actions/getVotingPower.ts new file mode 100644 index 00000000000..451b004deba --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/getVotingPower.ts @@ -0,0 +1,7 @@ +import { getBalance } from "./getBalance" + +// TODO(2.0) Fix all usages +export async function getVotingPower(walletId: string): Promise { + const balance = await getBalance(walletId) + return balance.baseCoin.votingPower +} diff --git a/packages/shared/lib/core/wallet/actions/index.ts b/packages/shared/lib/core/wallet/actions/index.ts index 0987abd6cb0..f5cb4c2f3e3 100644 --- a/packages/shared/lib/core/wallet/actions/index.ts +++ b/packages/shared/lib/core/wallet/actions/index.ts @@ -15,5 +15,11 @@ export * from './getOrRequestAssetFromPersistedAssets' export * from './activities' export * from './subscribeToWalletApiEvents' export * from './unsubscribeFromWalletApiEvents' - export * from './events-handlers' +export * from './buildWalletState' +export * from './buildWalletStateAndPersistedData' +export * from './createNewWallet' +export * from './loadWallet' +export * from './resetSelectedWalletId' +export * from './setSelectedWallet' +export * from './findBalances' diff --git a/packages/shared/lib/core/wallet/actions/loadWallet.ts b/packages/shared/lib/core/wallet/actions/loadWallet.ts new file mode 100644 index 00000000000..e903d760dfe --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/loadWallet.ts @@ -0,0 +1,24 @@ +import { addWalletPersistedDataToActiveProfile, getActiveProfilePersistedWalletData, IWallet } from '@core/profile' +import { DEFAULT_SYNC_OPTIONS } from '../constants' +import { IWalletState } from '../interfaces' +import { buildWalletStateAndPersistedData } from './buildWalletStateAndPersistedData' +import { buildWalletState } from './buildWalletState' + +// TODO(2.0) Fix all usages (it was called loadAccount before) +export async function loadWallet(wallet: IWallet): Promise { + // Temporary sync on load until we enable background sync and event listeners + const walletId = wallet.id + await wallet.sync({ ...DEFAULT_SYNC_OPTIONS }) + const walletPersistedData = getActiveProfilePersistedWalletData(walletId) + + let accountState: IWalletState + if (walletPersistedData) { + accountState = await buildWalletState(wallet, walletPersistedData) + } else { + const [newAccountState, accountPersistedData] = await buildWalletStateAndPersistedData(wallet) + addWalletPersistedDataToActiveProfile(walletId, accountPersistedData) + accountState = newAccountState + } + + return accountState +} diff --git a/packages/shared/lib/core/account/api/prepareOutput.ts b/packages/shared/lib/core/wallet/actions/prepareOutput.ts similarity index 52% rename from packages/shared/lib/core/account/api/prepareOutput.ts rename to packages/shared/lib/core/wallet/actions/prepareOutput.ts index 6c535d7c6d6..4bda095ecc4 100644 --- a/packages/shared/lib/core/account/api/prepareOutput.ts +++ b/packages/shared/lib/core/wallet/actions/prepareOutput.ts @@ -1,10 +1,11 @@ -import { getAccount } from '@core/profile-manager' import { Output, OutputParams, TransactionOptions } from '@iota/sdk/out/types' +import { getWallet } from '@core/profile' +// TODO(2.0) Fix all usages export async function prepareOutput( - accountIndex: number, + walletId: string, params: OutputParams, transactionOptions?: TransactionOptions ): Promise { - return (await getAccount(accountIndex))?.prepareOutput(params, transactionOptions) as Promise + return (await getWallet(walletId))?.prepareOutput(params, transactionOptions) as Promise } diff --git a/packages/shared/lib/core/wallet/actions/resetSelectedWalletId.ts b/packages/shared/lib/core/wallet/actions/resetSelectedWalletId.ts new file mode 100644 index 00000000000..3a04d6a0ada --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/resetSelectedWalletId.ts @@ -0,0 +1,5 @@ +import { selectedWalletId } from "../stores/selected-wallet-id.store"; + +export function resetSelectedWalletId(): void { + selectedWalletId.set(null) +} diff --git a/packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts b/packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts new file mode 100644 index 00000000000..cebac0c5a24 --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts @@ -0,0 +1,20 @@ +import { get } from 'svelte/store' +import { nonHiddenActiveWallets } from '@core/profile/stores' +import { selectedWallet } from '../stores/selected-wallet.store' +import { setSelectedWallet } from './setSelectedWallet' + +// TODO(2.0) Fix all usages +export function setNextSelectedWallet(): void { + const wallet = get(selectedWallet) + const otherWallets = get(nonHiddenActiveWallets) + if (otherWallets.length > 0) { + if (wallet?.hidden) { + const walletPosition = otherWallets.findIndex(w => w.id === wallet.id); + const nextSelectedWalletId = + otherWallets[walletPosition + 1]?.id ?? otherWallets[otherWallets?.length - 1]?.id + setSelectedWallet(nextSelectedWalletId) + } + } else { + throw new Error('No wallets to select from') + } +} diff --git a/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts b/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts new file mode 100644 index 00000000000..75558bf6a35 --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts @@ -0,0 +1,22 @@ +import { get } from 'svelte/store' +import { activeWallets, updateActiveProfile } from '@core/profile/stores' +import { resetSendOptionIndex } from '@core/wallet/stores' + +import { clearFilters } from '@core/utils' +import { resetNftDownloadQueue } from '@core/nfts' +import { selectedWalletId } from '../stores/selected-wallet-id.store' + +// TODO(2.0) Fix all usages +export function setSelectedWallet(walletId: string): void { + resetNftDownloadQueue(true) + + const account = get(activeWallets)?.find((_account) => _account.id === walletId) + if (account) { + selectedWalletId.set(walletId) + updateActiveProfile({ lastUsedWalletId: walletId }) + clearFilters() + resetSendOptionIndex() + } else { + throw new Error(`Wallet with ID ${walletId} cannot be found!`) + } +} diff --git a/packages/shared/lib/core/wallet/actions/syncBalance.ts b/packages/shared/lib/core/wallet/actions/syncBalance.ts new file mode 100644 index 00000000000..a2d59519f9b --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/syncBalance.ts @@ -0,0 +1,15 @@ +import { getBalance } from './getBalance' +import { get } from 'svelte/store' +import { selectedWalletId } from '../stores/selected-wallet-id.store' +import { updateSelectedWallet } from '../stores/selected-wallet.store' +import { updateActiveWallet } from '@core/profile/stores' + +export async function syncBalance(walletId: string): Promise { + const balances = await getBalance(walletId) + if (get(selectedWalletId) === walletId) { + updateSelectedWallet({ balances }) + } else { + updateActiveWallet(walletId, { balances }) + } + return +} diff --git a/packages/shared/lib/core/wallet/actions/syncVotingPower.ts b/packages/shared/lib/core/wallet/actions/syncVotingPower.ts new file mode 100644 index 00000000000..01e1c9cf341 --- /dev/null +++ b/packages/shared/lib/core/wallet/actions/syncVotingPower.ts @@ -0,0 +1,15 @@ +import { get } from 'svelte/store' +import { updateActiveWallet } from '@core/profile/stores' +import { selectedWalletId } from '../stores' +import { updateSelectedWallet } from '../stores/selected-wallet.store' +import { getVotingPower } from './getVotingPower' + +export async function syncVotingPower(walletId = get(selectedWalletId)): Promise { + const votingPower = await getVotingPower(walletId) + if (get(selectedWalletId) === walletId) { + updateSelectedWallet({ votingPower }) + } else { + updateActiveWallet(walletId, { votingPower }) + } + return +} diff --git a/packages/shared/lib/core/account/actions/tryCreateAdditionalAccount.ts b/packages/shared/lib/core/wallet/actions/tryCreateAdditionalWalet.ts similarity index 66% rename from packages/shared/lib/core/account/actions/tryCreateAdditionalAccount.ts rename to packages/shared/lib/core/wallet/actions/tryCreateAdditionalWalet.ts index 191f50279e9..0b6a9aee59a 100644 --- a/packages/shared/lib/core/account/actions/tryCreateAdditionalAccount.ts +++ b/packages/shared/lib/core/wallet/actions/tryCreateAdditionalWalet.ts @@ -6,22 +6,23 @@ import { Platform } from '@core/app/classes' import { localize } from '@core/i18n' import { displayNotificationForLedgerProfile } from '@core/ledger/actions' import { isActiveLedgerProfile } from '@core/profile/stores' +import { createNewWallet } from './createNewWallet' +import { setSelectedWallet } from './setSelectedWallet' +import { IError } from '@core/error/interfaces' -import { createNewAccount } from './createNewAccount' -import { setSelectedAccount } from './setSelectedAccount' - -export async function tryCreateAdditionalAccount(alias: string, color: string): Promise { +// TODO(2.0) Fix all usages +export async function tryCreateAdditionalWallet(alias: string, color: string): Promise { try { - const account = await createNewAccount(alias, color) - setSelectedAccount(account?.index) + const wallet = await createNewWallet(alias, color) + setSelectedWallet(wallet.id) if (Platform.isFeatureFlagEnabled('governance')) { - void registerProposalsFromNodes([account]) + void registerProposalsFromNodes([wallet]) } return Promise.resolve() } catch (err) { - const errorMessage = err?.error || err + const errorMessage = (err as IError)?.error || err as string if (err) { console.error(errorMessage) if (get(isActiveLedgerProfile)) { diff --git a/packages/shared/lib/core/account/constants/default-sync-options.constant.ts b/packages/shared/lib/core/wallet/constants/default-sync-options.constant.ts similarity index 63% rename from packages/shared/lib/core/account/constants/default-sync-options.constant.ts rename to packages/shared/lib/core/wallet/constants/default-sync-options.constant.ts index f96cba73d38..716736ad37d 100644 --- a/packages/shared/lib/core/account/constants/default-sync-options.constant.ts +++ b/packages/shared/lib/core/wallet/constants/default-sync-options.constant.ts @@ -3,17 +3,11 @@ import type { SyncOptions } from '@iota/sdk/out/types' export const DEFAULT_SYNC_OPTIONS: SyncOptions = { account: { basicOutputs: true, - aliasOutputs: true, + accountOutputs: true, nftOutputs: true, }, - alias: { - aliasOutputs: false, - basicOutputs: false, - nftOutputs: false, - foundryOutputs: true, - }, nft: { - aliasOutputs: false, + accountOutputs: false, basicOutputs: false, nftOutputs: false, }, diff --git a/packages/shared/lib/core/wallet/constants/index.ts b/packages/shared/lib/core/wallet/constants/index.ts index 62a8f42449e..213785bb629 100644 --- a/packages/shared/lib/core/wallet/constants/index.ts +++ b/packages/shared/lib/core/wallet/constants/index.ts @@ -11,3 +11,5 @@ export * from './max-supported-decimals.constants' export * from './max-supported-erc20-decimals.constant' export * from './official-token-ids.constant' export * from './reserved-tag-keywords.constant' +export * from './max-wallet-name-length.constant' +export * from './default-sync-options.constant' \ No newline at end of file diff --git a/packages/shared/lib/core/wallet/constants/max-wallet-name-length.constant.ts b/packages/shared/lib/core/wallet/constants/max-wallet-name-length.constant.ts new file mode 100644 index 00000000000..91f13781ff0 --- /dev/null +++ b/packages/shared/lib/core/wallet/constants/max-wallet-name-length.constant.ts @@ -0,0 +1 @@ +export const MAX_WALLET_NAME_LENGTH = 20 diff --git a/packages/shared/lib/core/wallet/enums/index.ts b/packages/shared/lib/core/wallet/enums/index.ts index 81b1edee951..ed68b74d096 100644 --- a/packages/shared/lib/core/wallet/enums/index.ts +++ b/packages/shared/lib/core/wallet/enums/index.ts @@ -12,3 +12,5 @@ export * from './return-strategy.enum' export * from './inclusion-state.enum' export * from './irc27-version.enum' export * from './subject.enum' +export * from './wallet-colors.enum' +export * from './search-algorithm.enum' \ No newline at end of file diff --git a/packages/shared/lib/core/account/enums/search-algorithm.enum.ts b/packages/shared/lib/core/wallet/enums/search-algorithm.enum.ts similarity index 100% rename from packages/shared/lib/core/account/enums/search-algorithm.enum.ts rename to packages/shared/lib/core/wallet/enums/search-algorithm.enum.ts diff --git a/packages/shared/lib/core/account/enums/account-colors.enum.ts b/packages/shared/lib/core/wallet/enums/wallet-colors.enum.ts similarity index 95% rename from packages/shared/lib/core/account/enums/account-colors.enum.ts rename to packages/shared/lib/core/wallet/enums/wallet-colors.enum.ts index 30ded4a2889..09702c9d6e9 100644 --- a/packages/shared/lib/core/account/enums/account-colors.enum.ts +++ b/packages/shared/lib/core/wallet/enums/wallet-colors.enum.ts @@ -3,7 +3,7 @@ import resolveConfig from 'tailwindcss/resolveConfig' const configColors = resolveConfig(tailwindConfig).theme.colors -export enum AccountColors { +export enum WalletColors { Blue = configColors['blue']['500'], LightBlue = configColors['lightblue']['500'], Purple = configColors['purple']['500'], diff --git a/packages/shared/lib/core/wallet/errors/cannot-remove-account.error.ts b/packages/shared/lib/core/wallet/errors/cannot-remove-account.error.ts index 9aeeafe6bcd..a83754420bb 100644 --- a/packages/shared/lib/core/wallet/errors/cannot-remove-account.error.ts +++ b/packages/shared/lib/core/wallet/errors/cannot-remove-account.error.ts @@ -1,6 +1,7 @@ import { BaseError } from '@core/error' import { localize } from '@core/i18n' +// TODO(2.0) Rename to CannotRemoveWalletError export class CannotRemoveAccountError extends BaseError { constructor() { super({ message: localize('error.account.cannotRemove'), showNotification: true }) diff --git a/packages/shared/lib/core/wallet/errors/index.ts b/packages/shared/lib/core/wallet/errors/index.ts index a1c0a68b5ef..731ec85d6cb 100644 --- a/packages/shared/lib/core/wallet/errors/index.ts +++ b/packages/shared/lib/core/wallet/errors/index.ts @@ -4,3 +4,4 @@ export * from './missing-transaction-progress-event-payload.error' export * from './remove-not-last-account.error' export * from './wallet-api-event.error' export * from './wallet-api-event-validation.error' +export * from './unable-to-get-bound-wallet.error' diff --git a/packages/shared/lib/core/account/errors/unable-to-get-bound-account.error.ts b/packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts similarity index 78% rename from packages/shared/lib/core/account/errors/unable-to-get-bound-account.error.ts rename to packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts index e1cefd3b88b..3dde0748804 100644 --- a/packages/shared/lib/core/account/errors/unable-to-get-bound-account.error.ts +++ b/packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts @@ -1,6 +1,6 @@ import { BaseError, DEFAULT_APP_ERROR_PARAMETERS } from '@core/error' -export class UnableToGetBoundAccountError extends BaseError { +export class UnableToGetBoundWalletError extends BaseError { constructor() { super({ message: 'error.account.cannotGetBoundAccount', diff --git a/packages/shared/lib/core/account/interfaces/account-state.interface.ts b/packages/shared/lib/core/wallet/interfaces/account-state.interface.ts similarity index 55% rename from packages/shared/lib/core/account/interfaces/account-state.interface.ts rename to packages/shared/lib/core/wallet/interfaces/account-state.interface.ts index 9cd630a4cf4..20daa921b2c 100644 --- a/packages/shared/lib/core/account/interfaces/account-state.interface.ts +++ b/packages/shared/lib/core/wallet/interfaces/account-state.interface.ts @@ -1,9 +1,10 @@ import { Balance } from '@iota/sdk/out/types' -import { AddressWithOutputs, IAccount } from './' -import { IPersistedAccountData } from './persisted-account-data.interface' +import { IWallet } from '@core/profile/interfaces' +import { AddressWithOutputs } from './address-with-outputs.interface' +import { IPersistedWalletData } from './persisted-account-data.interface' -export interface IAccountState extends IAccount, IPersistedAccountData { - index: number +export interface IWalletState extends IWallet, IPersistedWalletData { + id: string depositAddress: string balances: Balance isTransferring: boolean diff --git a/packages/shared/lib/core/account/interfaces/address-with-outputs.interface.ts b/packages/shared/lib/core/wallet/interfaces/address-with-outputs.interface.ts similarity index 100% rename from packages/shared/lib/core/account/interfaces/address-with-outputs.interface.ts rename to packages/shared/lib/core/wallet/interfaces/address-with-outputs.interface.ts diff --git a/packages/shared/lib/core/wallet/interfaces/index.ts b/packages/shared/lib/core/wallet/interfaces/index.ts index e90d58356d9..ca1070a5996 100644 --- a/packages/shared/lib/core/wallet/interfaces/index.ts +++ b/packages/shared/lib/core/wallet/interfaces/index.ts @@ -19,3 +19,6 @@ export * from './processed-transaction.interface' export * from './wrapped-output.interface' export * from './wallet-api-event-payload-wrapper.interface' export * from './wallet-api-event-subscription-configuration.interface' +export * from './account-state.interface' +export * from './address-with-outputs.interface' +export * from './persisted-account-data.interface' diff --git a/packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts b/packages/shared/lib/core/wallet/interfaces/persisted-account-data.interface.ts similarity index 85% rename from packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts rename to packages/shared/lib/core/wallet/interfaces/persisted-account-data.interface.ts index 23b24dda206..f69b2b5ecb3 100644 --- a/packages/shared/lib/core/account/interfaces/persisted-account-data.interface.ts +++ b/packages/shared/lib/core/wallet/interfaces/persisted-account-data.interface.ts @@ -1,6 +1,6 @@ import { ParticipationEventId, WalletOptions } from '@iota/sdk/out/types' -export interface IPersistedAccountData { +export interface IPersistedWalletData { name: string color: string hidden: boolean diff --git a/packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts b/packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts index feedab8d0db..fa52cab8478 100644 --- a/packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts +++ b/packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts @@ -8,7 +8,7 @@ import { } from '@iota/sdk/out/types' export interface IWalletApiEventPayloadWrapper { - accountIndex: number + walletId: string payload: IWalletApiEventPayload } diff --git a/packages/shared/lib/core/wallet/stores/index.ts b/packages/shared/lib/core/wallet/stores/index.ts index d3a3364bb83..8caa2e8a5f3 100644 --- a/packages/shared/lib/core/wallet/stores/index.ts +++ b/packages/shared/lib/core/wallet/stores/index.ts @@ -8,3 +8,4 @@ export * from './persisted-assets.store' export * from './selected-account-activities.store' export * from './selected-account-assets.store' export * from './selected-send-option.store' +export * from './selected-wallet-id.store' \ No newline at end of file diff --git a/packages/shared/lib/core/wallet/stores/selected-account-activities.store.ts b/packages/shared/lib/core/wallet/stores/selected-account-activities.store.ts index 9eaa72bfc58..4309bf5b62e 100644 --- a/packages/shared/lib/core/wallet/stores/selected-account-activities.store.ts +++ b/packages/shared/lib/core/wallet/stores/selected-account-activities.store.ts @@ -1,7 +1,7 @@ import { derived, Readable, writable, Writable } from 'svelte/store' import { isValidIrc30Token } from '@core/token' -import { selectedAccount } from '../../account/stores/selected-account.store' +import { selectedAccount } from './selected-wallet.store' import { Activity } from '../types/activity.type' import { ActivityType, SubjectType } from '../enums' import { ActivityFilter } from '../interfaces/activity-filter.interface' diff --git a/packages/shared/lib/core/wallet/stores/selected-wallet-id.store.ts b/packages/shared/lib/core/wallet/stores/selected-wallet-id.store.ts new file mode 100644 index 00000000000..456a51a869d --- /dev/null +++ b/packages/shared/lib/core/wallet/stores/selected-wallet-id.store.ts @@ -0,0 +1,4 @@ +import { writable } from 'svelte/store' + +// TODO(2.0) Fix all usages +export const selectedWalletId = writable(null) diff --git a/packages/shared/lib/core/wallet/stores/selected-wallet.store.ts b/packages/shared/lib/core/wallet/stores/selected-wallet.store.ts new file mode 100644 index 00000000000..fd64047ba05 --- /dev/null +++ b/packages/shared/lib/core/wallet/stores/selected-wallet.store.ts @@ -0,0 +1,19 @@ +import { derived, get, Readable } from 'svelte/store' +import { activeWallets, updateActiveWallet } from '@core/profile' +import { IWalletState } from '../interfaces' +import { selectedWalletId } from './selected-wallet-id.store' + +export const selectedWallet: Readable = derived( + [selectedWalletId, activeWallets], + ([$selectedWalletId, $activeWallets]) => { + return $activeWallets?.find((wallet) => wallet.id === $selectedWalletId) + } +) + +export function getSelectedWallet(): IWalletState | undefined { + return get(selectedWallet) +} + +export function updateSelectedWallet(payload: Partial): void { + updateActiveWallet(get(selectedWalletId), payload) +} diff --git a/packages/shared/lib/core/account/utils/getBoundAccount.ts b/packages/shared/lib/core/wallet/utils/getBoundWallet.ts similarity index 54% rename from packages/shared/lib/core/account/utils/getBoundAccount.ts rename to packages/shared/lib/core/wallet/utils/getBoundWallet.ts index 5b27e1d54b0..e56ce6e03b6 100644 --- a/packages/shared/lib/core/account/utils/getBoundAccount.ts +++ b/packages/shared/lib/core/wallet/utils/getBoundWallet.ts @@ -1,29 +1,34 @@ -import { IAccount, UnableToGetBoundAccountError } from '@core/account' -import { createAccount, getAccount, profileManager as _profileManager } from '@core/profile-manager' +import { IError } from '@core/error/interfaces' +import { IWallet } from '@core/profile/interfaces' +import { getWallet } from '@core/profile/actions' +import { UnableToGetBoundWalletError } from '@core/wallet/errors' -export async function getBoundAccount( - accountIndex: number, +// TODO(2.0) Fix all usages +export async function getBoundWallet( + walletId: string, createAccountsIfNotFound: boolean = false, - profileManager = _profileManager -): Promise { +): Promise { try { /** * CAUTION: Do NOT remove the `await` keyword here. * It is needed in the case of handling an AccountNotFound * error by creating more accounts. */ - const account = await getAccount(accountIndex ?? 0, profileManager) - return account + const wallet = await getWallet(walletId) + return wallet } catch (err) { // TODO: Update error type when sdk Error enum has been updated - if (err?.type === 'wallet' && createAccountsIfNotFound) { + if ((err as IError)?.type === 'wallet' && createAccountsIfNotFound) { + // TODO(2.0) Adapt this logic + /* for (let indexToCreateAccount = 0; indexToCreateAccount < accountIndex; indexToCreateAccount++) { const account = await createAccount({}, profileManager) if (account?.getMetadata()?.index === accountIndex) { return account } } - throw new UnableToGetBoundAccountError() + */ + throw new UnableToGetBoundWalletError() } else { throw err } diff --git a/packages/shared/lib/core/wallet/utils/getDepositAddress.ts b/packages/shared/lib/core/wallet/utils/getDepositAddress.ts new file mode 100644 index 00000000000..9d1a92eeed9 --- /dev/null +++ b/packages/shared/lib/core/wallet/utils/getDepositAddress.ts @@ -0,0 +1,6 @@ +import { IWallet } from "@core/profile/interfaces"; + +// TODO(2.0) Fix all usages +export async function getDepositAddress(wallet: IWallet): Promise { + return await wallet.address(); +} diff --git a/packages/shared/lib/core/account/utils/getIconColorFromString.ts b/packages/shared/lib/core/wallet/utils/getIconColorFromString.ts similarity index 100% rename from packages/shared/lib/core/account/utils/getIconColorFromString.ts rename to packages/shared/lib/core/wallet/utils/getIconColorFromString.ts diff --git a/packages/shared/lib/core/wallet/utils/getRandomWalletColor.ts b/packages/shared/lib/core/wallet/utils/getRandomWalletColor.ts new file mode 100644 index 00000000000..534f3bac5f1 --- /dev/null +++ b/packages/shared/lib/core/wallet/utils/getRandomWalletColor.ts @@ -0,0 +1,6 @@ +import { WalletColors } from "../enums" + +export function getRandomWalletColor(): string { + const colors = Object.values(WalletColors).filter((_, i) => !(i % 2)) + return colors[Math.floor(Math.random() * colors.length)].toString() +} diff --git a/packages/shared/lib/core/wallet/utils/index.ts b/packages/shared/lib/core/wallet/utils/index.ts index 6508d99efcb..d2cf74eb20f 100644 --- a/packages/shared/lib/core/wallet/utils/index.ts +++ b/packages/shared/lib/core/wallet/utils/index.ts @@ -26,6 +26,12 @@ export * from './processAndAddToActivities' export * from './validateIrc30Metadata' export * from './validateTokenAmount' export * from './validateWalletApiEvent' +export * from './sumBalanceForWallets' +export * from './sumTotalFromOutputs' +export * from './getDepositAddress' +export * from './getBoundWallet' +export * from './getRandomWalletColor' +export * from './getIconColorFromString' // Folders export * from './generateActivity' diff --git a/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts b/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts new file mode 100644 index 00000000000..6492d3e65c6 --- /dev/null +++ b/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts @@ -0,0 +1,9 @@ +import { IWalletState } from "../interfaces"; + +// TODO(2.0) Fix all usages +export function sumBalanceForWallets(wallets: IWalletState[]): number { + return wallets.reduce( + (total: number, wallet: IWalletState) => (total += Number(wallet.balances.baseCoin.total)), + 0 + ) +} diff --git a/packages/shared/lib/core/account/utils/sumTotalFromOutputs.ts b/packages/shared/lib/core/wallet/utils/sumTotalFromOutputs.ts similarity index 89% rename from packages/shared/lib/core/account/utils/sumTotalFromOutputs.ts rename to packages/shared/lib/core/wallet/utils/sumTotalFromOutputs.ts index 021c8fff081..74871861357 100644 --- a/packages/shared/lib/core/account/utils/sumTotalFromOutputs.ts +++ b/packages/shared/lib/core/wallet/utils/sumTotalFromOutputs.ts @@ -1,5 +1,6 @@ import { OutputData } from '@iota/sdk/out/types' +// TODO(2.0) Fix all usages export function sumTotalFromOutputs(outputs: OutputData[]): number { return outputs?.reduce((total: number, outputData: OutputData) => (total += Number(outputData?.output?.amount)), 0) } diff --git a/packages/shared/lib/core/wallet/utils/syncWalletsInParallel.ts b/packages/shared/lib/core/wallet/utils/syncWalletsInParallel.ts new file mode 100644 index 00000000000..2f7a8f7ac11 --- /dev/null +++ b/packages/shared/lib/core/wallet/utils/syncWalletsInParallel.ts @@ -0,0 +1,6 @@ +import { Balance, SyncOptions } from '@iota/sdk/out/types' +import { IWallet } from '@core/profile/interfaces' + +export async function syncWalletsInParallel(syncOptions: SyncOptions, ...wallets: IWallet[]): Promise { + return Promise.all(wallets.map((wallet) => wallet?.sync(syncOptions))) +} diff --git a/packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts b/packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts new file mode 100644 index 00000000000..723d89ac9c5 --- /dev/null +++ b/packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts @@ -0,0 +1,12 @@ +import { Balance, SyncOptions } from '@iota/sdk/out/types' +import { IWallet } from '@core/profile/interfaces' + +// TODO(2.0) Fix all usages +export async function syncWalletsInSeries(syncOptions: SyncOptions, ...wallets: IWallet[]): Promise { + const walletBalances: Balance[] = [] + for (const wallet of wallets) { + const balance = await wallet?.sync(syncOptions) + walletBalances.push(balance) + } + return walletBalances +} diff --git a/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts b/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts index 6147b01e134..343bc781176 100644 --- a/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts +++ b/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts @@ -14,9 +14,9 @@ export function validateWalletApiEvent( throw new WalletApiEventError(error) } else { /* eslint-disable-next-line prefer-const */ - const { accountIndex, event } = rawEvent + const { walletId, event } = rawEvent - if (Number.isNaN(accountIndex)) { + if (Number.isNaN(walletId)) { throw new WalletApiEventValidationError( localize('error.walletApiEvent.invalidAccountIndex', { values: { eventName: apiEvent } }) ) diff --git a/packages/shared/lib/core/account/utils/validateAccountName.ts b/packages/shared/lib/core/wallet/utils/validateWalletName.ts similarity index 50% rename from packages/shared/lib/core/account/utils/validateAccountName.ts rename to packages/shared/lib/core/wallet/utils/validateWalletName.ts index 337a3031934..a8adbcd5941 100644 --- a/packages/shared/lib/core/account/utils/validateAccountName.ts +++ b/packages/shared/lib/core/wallet/utils/validateWalletName.ts @@ -1,26 +1,27 @@ import { localize } from '@core/i18n' -import { activeAccounts } from '@core/profile' +import { activeWallets } from '@core/profile' import { getTrimmedLength } from '@core/utils' import { get } from 'svelte/store' -import { MAX_ACCOUNT_NAME_LENGTH } from '../constants' +import { MAX_WALLET_NAME_LENGTH } from '../constants' -export function validateAccountName( +// TODO(2.0) Fix all usages +export function validateWalletName( name: string, validateLength = true, validateDuplicate = true ): Promise { - if (validateLength && getTrimmedLength(name) > MAX_ACCOUNT_NAME_LENGTH) { + if (validateLength && getTrimmedLength(name) > MAX_WALLET_NAME_LENGTH) { return Promise.reject( new Error( - localize('error.account.length', { + localize('error.account.length', { // TODO(2.0) Rename error code values: { - length: MAX_ACCOUNT_NAME_LENGTH, + length: MAX_WALLET_NAME_LENGTH, }, }) ) ) } - if (validateDuplicate && get(activeAccounts)?.find((existingAccount) => existingAccount.name === name)) { + if (validateDuplicate && get(activeWallets)?.find((existingWallet) => existingWallet.name === name)) { return Promise.reject(new Error(localize('error.account.duplicate'))) } return Promise.resolve() From ea5c673e03c7c0146736cf4ea290434dcb2337d7 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 29 Nov 2023 09:50:03 +0100 Subject: [PATCH 07/19] move utils from profile manager to profile --- .../utils/buildProfileManagerOptionsFromProfileData.ts | 3 ++- packages/shared/lib/core/profile-manager/utils/index.ts | 2 -- .../utils/getSecretManagerFromProfileType.ts | 3 ++- .../{profile-manager => profile}/utils/getSecretManagerPath.ts | 1 + packages/shared/lib/core/profile/utils/index.ts | 2 ++ 5 files changed, 7 insertions(+), 4 deletions(-) rename packages/shared/lib/core/{profile-manager => profile}/utils/getSecretManagerFromProfileType.ts (91%) rename packages/shared/lib/core/{profile-manager => profile}/utils/getSecretManagerPath.ts (81%) diff --git a/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts b/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts index 12b5308c4b2..c889db41b40 100644 --- a/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts +++ b/packages/shared/lib/core/profile-manager/utils/buildProfileManagerOptionsFromProfileData.ts @@ -3,6 +3,7 @@ import { getSecretManagerFromProfileType } from '@core/profile-manager' import { COIN_TYPE, getDefaultClientOptions } from '@core/network' import { WalletOptions } from '@iota/sdk/out/types' +// TODO(2.0) Fix this and all usages export async function buildProfileManagerOptionsFromProfileData( profileData: Partial ): Promise { @@ -19,7 +20,7 @@ export async function buildProfileManagerOptionsFromProfileData( return { storagePath, bipPath: { - coinType + coinType, }, clientOptions, secretManager, diff --git a/packages/shared/lib/core/profile-manager/utils/index.ts b/packages/shared/lib/core/profile-manager/utils/index.ts index 6641f7a3fe1..6e0f9c5f762 100644 --- a/packages/shared/lib/core/profile-manager/utils/index.ts +++ b/packages/shared/lib/core/profile-manager/utils/index.ts @@ -1,3 +1 @@ export * from './buildProfileManagerOptionsFromProfileData' -export * from './getSecretManagerFromProfileType' -export * from './getSecretManagerPath' diff --git a/packages/shared/lib/core/profile-manager/utils/getSecretManagerFromProfileType.ts b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts similarity index 91% rename from packages/shared/lib/core/profile-manager/utils/getSecretManagerFromProfileType.ts rename to packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts index e2441f5229f..5afc870ebfd 100644 --- a/packages/shared/lib/core/profile-manager/utils/getSecretManagerFromProfileType.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts @@ -3,9 +3,10 @@ import { SecretManagerType } from '@iota/sdk/out/types' import { USE_LEDGER_SIMULATOR } from '@core/ledger' import { ProfileType } from '@core/profile' +// TODO(2.0) Fix all usages export function getSecretManagerFromProfileType(type: ProfileType, storagePath?: string): SecretManagerType { const strongholdSecretManager = { - stronghold: { snapshotPath: `${storagePath}/wallet.stronghold`, password: "mellamobego", }, + stronghold: { snapshotPath: `${storagePath}/wallet.stronghold`, password: 'mellamobego' }, } const ledgerSecretManager = { ledgerNano: USE_LEDGER_SIMULATOR, diff --git a/packages/shared/lib/core/profile-manager/utils/getSecretManagerPath.ts b/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts similarity index 81% rename from packages/shared/lib/core/profile-manager/utils/getSecretManagerPath.ts rename to packages/shared/lib/core/profile/utils/getSecretManagerPath.ts index 6e9a2a5bd0e..dde8c2909e0 100644 --- a/packages/shared/lib/core/profile-manager/utils/getSecretManagerPath.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts @@ -1,3 +1,4 @@ +// TODO(2.0) Fix all usages export function getSecretManagerPath(profileDirectory: string): string { return `${profileDirectory}/wallet.stronghold` } diff --git a/packages/shared/lib/core/profile/utils/index.ts b/packages/shared/lib/core/profile/utils/index.ts index 4284bbd46bc..450cb16ab86 100644 --- a/packages/shared/lib/core/profile/utils/index.ts +++ b/packages/shared/lib/core/profile/utils/index.ts @@ -4,3 +4,5 @@ export * from './isLedgerProfile' export * from './removeProfileFolder' export * from './removeProfileFolder' export * from './validateProfileName' +export * from './getSecretManagerPath' +export * from './getSecretManagerFromProfileType' From 82fc7e8d0bfb53b259a0cf1b3e268914ed68de6c Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 29 Nov 2023 09:52:33 +0100 Subject: [PATCH 08/19] rename every createAccount to createWallet --- .../modals/AccountSwitcherModal.svelte | 6 ++--- .../desktop/components/popups/Popup.svelte | 6 ++--- packages/desktop/electron/preload.js | 6 ++--- .../auxiliary/popup/enums/popup-id.enum.ts | 2 +- .../initialiseFirstShimmerClaimingAccount.ts | 10 ++++---- .../helpers/validateStrongholdCoinType.ts | 4 ++-- .../lib/core/api/interfaces/api.interface.ts | 15 ++++++++++-- .../lib/core/profile/actions/createWallet.ts | 24 +++++++++---------- .../lib/core/wallet/utils/getBoundWallet.ts | 11 ++++----- .../shared/lib/tests/__mocks__/api.mock.ts | 4 ++-- .../tests/__mocks__/profile-manager.mock.ts | 4 ++-- packages/shared/locales/af.json | 2 +- packages/shared/locales/ar.json | 2 +- packages/shared/locales/bg.json | 2 +- packages/shared/locales/ca.json | 2 +- packages/shared/locales/cs.json | 2 +- packages/shared/locales/da.json | 2 +- packages/shared/locales/de.json | 2 +- packages/shared/locales/el.json | 2 +- packages/shared/locales/en.json | 2 +- packages/shared/locales/eo.json | 2 +- packages/shared/locales/es-ES.json | 2 +- packages/shared/locales/es-LA.json | 2 +- packages/shared/locales/et.json | 2 +- packages/shared/locales/fa.json | 2 +- packages/shared/locales/fi.json | 2 +- packages/shared/locales/fr.json | 2 +- packages/shared/locales/he.json | 2 +- packages/shared/locales/hi.json | 2 +- packages/shared/locales/hr.json | 2 +- packages/shared/locales/hu.json | 2 +- packages/shared/locales/id.json | 2 +- packages/shared/locales/it.json | 2 +- packages/shared/locales/ja.json | 2 +- packages/shared/locales/ko.json | 2 +- packages/shared/locales/ku.json | 2 +- packages/shared/locales/lv.json | 2 +- packages/shared/locales/mk.json | 2 +- packages/shared/locales/nl.json | 2 +- packages/shared/locales/no.json | 2 +- packages/shared/locales/pl.json | 2 +- packages/shared/locales/pt-BR.json | 2 +- packages/shared/locales/pt-PT.json | 2 +- packages/shared/locales/ro.json | 2 +- packages/shared/locales/ru.json | 2 +- packages/shared/locales/si.json | 2 +- packages/shared/locales/sk.json | 2 +- packages/shared/locales/sl.json | 2 +- packages/shared/locales/sq.json | 2 +- packages/shared/locales/sr.json | 2 +- packages/shared/locales/sv.json | 2 +- packages/shared/locales/tr.json | 2 +- packages/shared/locales/uk.json | 2 +- packages/shared/locales/ur.json | 2 +- packages/shared/locales/vi.json | 2 +- packages/shared/locales/zh-CN.json | 2 +- packages/shared/locales/zh-TW.json | 2 +- 57 files changed, 96 insertions(+), 88 deletions(-) diff --git a/packages/desktop/components/modals/AccountSwitcherModal.svelte b/packages/desktop/components/modals/AccountSwitcherModal.svelte index 30e3bd27070..4f8e806373a 100644 --- a/packages/desktop/components/modals/AccountSwitcherModal.svelte +++ b/packages/desktop/components/modals/AccountSwitcherModal.svelte @@ -21,9 +21,9 @@ element?.scrollIntoView({ behavior: 'auto' }) } - function onCreateAccountClick(): void { + function oncreateWalletClick(): void { modal?.close() - openPopup({ id: PopupId.CreateAccount }) + openPopup({ id: PopupId.createWallet }) } @@ -45,7 +45,7 @@ - +