From 0e58e1a859695296afdb8f938f6e13099648d1f9 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Thu, 21 Dec 2023 17:17:37 +0100 Subject: [PATCH 01/37] refactor(2.0): Dynamic password --- .../views/shared/EncryptMnemonicView.svelte | 1 - .../actions/completeOnboardingProcess.ts | 24 +++++---- .../actions/verifyAndStoreMnemonic.ts | 5 ++ .../stores/onboarding-secret-manager.store.ts | 50 +++++-------------- .../profile/actions/active-profile/login.ts | 4 -- .../lib/core/profile/actions/createWallet.ts | 4 +- .../utils/getSecretManagerFromProfileType.ts | 2 +- .../secret-manager/actions/storeMnemonic.ts | 5 +- .../wallet/actions/setStrongholdPassword.ts | 12 +++-- 9 files changed, 46 insertions(+), 61 deletions(-) diff --git a/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte b/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte index b4a3d15dce2..7976ddcd313 100644 --- a/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte +++ b/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte @@ -44,7 +44,6 @@ } else { try { busy = true - await setStrongholdPassword(strongholdPassword) updateOnboardingProfile({ strongholdPassword, hasStoredMnemonic: true }) await buildOnboardingSecretManager() await verifyAndStoreMnemonic() diff --git a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts index 90f497619f7..c7b66a2a6c7 100644 --- a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts +++ b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts @@ -27,34 +27,36 @@ export async function completeOnboardingProcess(): Promise { createNewProfileFromOnboardingProfile() } - const onboardingType = get(onboardingProfile)?.onboardingType + const { onboardingType, strongholdPassword } = get(onboardingProfile)! + const shouldRecoverWallets = onboardingType === OnboardingType.Restore || onboardingType === OnboardingType.Claim showBalanceOverviewPopup.set(shouldRecoverWallets) - await createOnboardingWallet() + await initWallet(strongholdPassword) void login({ isFromOnboardingFlow: true, shouldRecoverWallets }) onboardingProfile.set(undefined) } -export async function createOnboardingWallet(name?: string, color?: string): Promise { +export async function initWallet(strongholdPassword?: string): Promise { // 1. Get the wallet name - const walletName = name || `${localize('general.wallet')} ${(get(activeWallets)?.length ?? 0) + 1}` + const walletName = `${localize('general.wallet')} ${(get(activeWallets)?.length ?? 0) + 1}` // 2. Create the wallet instance - const wallet = await createWallet() // TODO(2.0) Not sure about this, I think this should be createWallet instead + const wallet = await createWallet() + + console.log(strongholdPassword) + if(strongholdPassword){ + await wallet.setStrongholdPassword(strongholdPassword) + } // 3. Sync the wallet with the Node - // TODO(2.0): test & fix sync when we have iota2.0 nodes await wallet.sync(DEFAULT_SYNC_OPTIONS) // 4. Create a wrapper over the wallet instance and the persisted data - const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName, color) + const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName) - // TODO(2.0) Fix addWalletToActiveWallets(walletState) - addWalletPersistedDataToOnboardingProfile(walletState.id, walletPersistedData) - addWalletPersistedDataToActiveProfile(walletState.id, walletPersistedData) // TODO(2.0) Not sure about this, - // TODO(2.0) Fix + addWalletPersistedDataToActiveProfile(walletState.id, walletPersistedData) addEmptyWalletActivitiesToAllWalletActivities(walletState.id) return walletState diff --git a/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts b/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts index 85b471cca61..33f627985db 100644 --- a/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts +++ b/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts @@ -9,6 +9,11 @@ export async function verifyAndStoreMnemonic(): Promise { // TODO(2.0) This shouldn't use the onboarding profile always const mnemonic = get(onboardingProfile)?.mnemonic?.join(' ') ?? '' + console.log("verifying...") await verifyMnemonic(mnemonic) + console.log("verified...") + + console.log("storing...") await storeMnemonic(mnemonic) + console.log("stored...") } 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 index 63163dc4059..e753f03eca7 100644 --- a/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts @@ -1,8 +1,6 @@ import { onboardingProfile } from '@contexts/onboarding/stores' import { api } from '@core/api' -import { SecretManager, SecretManagerType } from '@iota/sdk' -import { USE_LEDGER_SIMULATOR } from 'shared/lib/core/ledger' -import { getStorageDirectoryOfProfile, ProfileType } from 'shared/lib/core/profile' +import { SecretManager } from '@iota/sdk' import { get, writable, Writable } from 'svelte/store' export const onboardingProfileSecretManager: Writable = writable(null) @@ -10,15 +8,17 @@ export const onboardingProfileSecretManager: Writable = wr export async function buildOnboardingSecretManager(): Promise { const profile = get(onboardingProfile) if (profile) { - const { id, type, strongholdPassword } = profile - - const storagePath = await getStorageDirectoryOfProfile(id) - const secretManagerOptions = getSecretManagerFromProfileType(type, { - storagePath, - strongholdPassword, - }) - - const secretManager = await api.createSecretManager(secretManagerOptions) + const { strongholdPassword, secretManagerOptions } = profile + console.log(secretManagerOptions, strongholdPassword) + // Create secret manager with persisted options + const secretManager = await api.createSecretManager(secretManagerOptions!) + + console.log(secretManager) + // Load the stronghold password specified in the onboarding if necessary + if(strongholdPassword){ + await secretManager.setStrongholdPassword(strongholdPassword); + console.log("setted strongholdPassword") + } onboardingProfileSecretManager.set(secretManager) } else { @@ -29,29 +29,3 @@ export async function buildOnboardingSecretManager(): Promise { export function isOnboardingSecretManagerInitialized(): boolean { return !!get(onboardingProfileSecretManager) } - -export function getSecretManagerFromProfileType( - type?: ProfileType, - { - storagePath, - strongholdPassword, - }: { - storagePath?: string - strongholdPassword?: string - } = {} -): SecretManagerType { - const strongholdSecretManager = { - stronghold: { snapshotPath: `${storagePath}/wallet.stronghold`, password: strongholdPassword }, - } - const ledgerSecretManager = { - ledgerNano: USE_LEDGER_SIMULATOR, - } - - switch (type) { - case ProfileType.Ledger: - return ledgerSecretManager - case ProfileType.Software: - default: - return strongholdSecretManager - } -} 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 9ade1a856ab..f98e39597e5 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/login.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/login.ts @@ -52,10 +52,6 @@ export async function login(loginOptions?: ILoginOptions): Promise { // Step 1: create profile manager if its doesn't exist incrementLoginProgress() await waitForPreviousManagerToBeDestroyed() - // if (!isOnboardingSecretManagerInitialized()) { - // // TODO(2.0) Not sure about this - // await initialiseOnboardingProfileWithSecretManager(true) - // } // Step 3: load and build all the profile data incrementLoginProgress() diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index b6d8f185495..fccfdc904c7 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -33,12 +33,14 @@ export async function createWallet(activeProfile = get(activeProfileStore)): Pro const storagePath = await getStorageDirectoryOfProfile(id) const walletOptions = getWalletOptions(activeProfile, storagePath) - + console.log("CREATING WALLET", walletOptions); const wallet = await api.createWallet(id, { ...walletOptions, storagePath, }) + console.log("CREATED WALLET"); + // TODO(2.0): Fix selectedWalletId.set(id) return wallet diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts index 555b35a70f4..cec897cb9c4 100644 --- a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts @@ -6,7 +6,7 @@ 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' }, // TODO(2.0) Remove this harcoded password + stronghold: { snapshotPath: `${storagePath}/wallet.stronghold`} } const ledgerSecretManager = { ledgerNano: USE_LEDGER_SIMULATOR, diff --git a/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts b/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts index 8b8abbca551..33ec5588705 100644 --- a/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts +++ b/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts @@ -1,12 +1,13 @@ import { onboardingProfileSecretManager } from 'shared/lib/contexts/onboarding' import { get } from 'svelte/store' -export async function storeMnemonic(mnemonic: string): Promise { +export function storeMnemonic(mnemonic: string): Promise { // TODO(2.0) There are two secret managers, but we might only actually need one to store the mnemonic. const secretManager = get(onboardingProfileSecretManager) if (!secretManager) { - return undefined + return Promise.resolve() } + console.log("...") return secretManager.storeMnemonic(mnemonic) } diff --git a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts index 97611fcec00..bcf751532dd 100644 --- a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts +++ b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts @@ -1,9 +1,15 @@ -import { get } from 'svelte/store' -import { selectedWallet } from '../stores/selected-wallet.store' +import { getSecretManager } from '@core/secret-manager/actions' +import { getSelectedWallet } from '../stores/selected-wallet.store' export async function setStrongholdPassword(password: string): Promise { - const wallet = get(selectedWallet) + // Set in Wallet + const wallet = getSelectedWallet(); // Otherwise error is thrown, if password is still present in memory await wallet?.clearStrongholdPassword() await wallet?.setStrongholdPassword(password) + + // Set in SecretManager + const secretManager = getSecretManager(); + await secretManager.setStrongholdPassword(password); + // await secretManager?.clearStrongholdPassword() // TODO(2.0) } From 2b25b9b9dd70d2dff10dab150782461a63bb7102 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Fri, 22 Dec 2023 13:03:42 +0100 Subject: [PATCH 02/37] refactor(2.0): Remove Profile Manager (wip) --- packages/shared/lib/contexts/onboarding/actions/index.ts | 2 +- ...ile.ts => initialiseOnboardingProfileWithSecretManager.ts} | 0 .../actions/migrateStrongholdFromOnboardingProfile.ts | 4 ++-- .../resetOnboardingProfileWithAlreadyStoredMnemonic.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) rename packages/shared/lib/contexts/onboarding/actions/{initialiseProfileManagerFromOnboardingProfile.ts => initialiseOnboardingProfileWithSecretManager.ts} (100%) diff --git a/packages/shared/lib/contexts/onboarding/actions/index.ts b/packages/shared/lib/contexts/onboarding/actions/index.ts index 6ede0989724..595eed1be3a 100644 --- a/packages/shared/lib/contexts/onboarding/actions/index.ts +++ b/packages/shared/lib/contexts/onboarding/actions/index.ts @@ -16,7 +16,7 @@ export * from './initialiseFirstShimmerClaimingAccount' export * from './initialiseOnboardingFlow' export * from './initialiseOnboardingProfile' export * from './initialisePincodeManager' -export * from './initialiseProfileManagerFromOnboardingProfile' +export * from './initialiseOnboardingProfileWithSecretManager' export * from './migrateStrongholdFromOnboardingProfile' export * from './resetOnboardingProfile' export * from './resetOnboardingProfileWithAlreadyStoredMnemonic' diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseProfileManagerFromOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts similarity index 100% rename from packages/shared/lib/contexts/onboarding/actions/initialiseProfileManagerFromOnboardingProfile.ts rename to packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts diff --git a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts index 7f44dcffe03..f1e11fc49fd 100644 --- a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts @@ -5,7 +5,7 @@ import { StrongholdVersion } from '@core/stronghold/enums' import { copyStrongholdFileToProfileDirectory } from '../helpers' import { onboardingProfile, updateOnboardingProfile } from '../stores' -import { initialiseOnboardingProfileWithSeretManager } from './initialiseProfileManagerFromOnboardingProfile' +import { initialiseOnboardingProfileWithSecretManager } from './initialiseOnboardingProfileWithSecretManager' import { api } from '@core/api' import { clearProfileFromMemory } from '@core/profile' @@ -24,5 +24,5 @@ export async function migrateStrongholdFromOnboardingProfile(password: string): } await clearProfileFromMemory() - await initialiseOnboardingProfileWithSeretManager() + await initialiseOnboardingProfileWithSecretManager() } diff --git a/packages/shared/lib/contexts/onboarding/actions/resetOnboardingProfileWithAlreadyStoredMnemonic.ts b/packages/shared/lib/contexts/onboarding/actions/resetOnboardingProfileWithAlreadyStoredMnemonic.ts index 280e684dcc9..aa4fdf74d8c 100644 --- a/packages/shared/lib/contexts/onboarding/actions/resetOnboardingProfileWithAlreadyStoredMnemonic.ts +++ b/packages/shared/lib/contexts/onboarding/actions/resetOnboardingProfileWithAlreadyStoredMnemonic.ts @@ -3,12 +3,12 @@ import { get } from 'svelte/store' import { onboardingProfile, updateOnboardingProfile } from '../stores' -import { initialiseOnboardingProfileWithSeretManager } from './initialiseProfileManagerFromOnboardingProfile' +import { initialiseOnboardingProfileWithSecretManager } from './initialiseOnboardingProfileWithSecretManager' import { resetOnboardingProfile } from './resetOnboardingProfile' export async function resetOnboardingProfileWithAlreadyStoredMnemonic(): Promise { await resetOnboardingProfile() - await initialiseOnboardingProfileWithSeretManager() + await initialiseOnboardingProfileWithSecretManager() await setStrongholdPassword(get(onboardingProfile)?.strongholdPassword) updateOnboardingProfile({ hasStoredMnemonic: false }) } From 027b69d3fb8723312c658ec5b8d66466a84a3a08 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Fri, 22 Dec 2023 13:35:02 +0100 Subject: [PATCH 03/37] clean up and fix --- .../views/shared/EncryptMnemonicView.svelte | 4 +-- .../actions/completeOnboardingProcess.ts | 23 +++++++++------ .../lib/contexts/onboarding/actions/index.ts | 1 - .../actions/verifyAndStoreMnemonic.ts | 19 ------------- .../onboarding-profile.interface.ts | 2 ++ .../stores/onboarding-secret-manager.store.ts | 28 +++++++++++++------ .../lib/core/profile/actions/createWallet.ts | 26 ++++++++--------- .../lib/core/secret-manager/actions/index.ts | 1 - .../secret-manager/actions/storeMnemonic.ts | 13 --------- 9 files changed, 51 insertions(+), 66 deletions(-) delete mode 100644 packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts delete mode 100644 packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts diff --git a/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte b/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte index 7976ddcd313..56516b957b5 100644 --- a/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte +++ b/packages/desktop/views/onboarding/views/shared/EncryptMnemonicView.svelte @@ -2,12 +2,11 @@ import { AnimationEnum } from '@auxiliary/animation' import { showAppNotification } from '@auxiliary/notification' import { OnboardingLayout } from '@components' - import { buildOnboardingSecretManager, updateOnboardingProfile, verifyAndStoreMnemonic } from '@contexts/onboarding' + import { buildOnboardingSecretManager, updateOnboardingProfile } from '@contexts/onboarding' import { localize } from '@core/i18n' import { MAX_STRONGHOLD_PASSWORD_LENGTH } from '@core/profile' import { Subrouter } from '@core/router' import { PASSWORD_REASON_MAP } from '@core/stronghold' - import { setStrongholdPassword } from '@core/wallet/actions' import { Animation, Button, HTMLButtonType, PasswordInput, Text, TextType } from '@ui' import zxcvbn from 'zxcvbn' @@ -46,7 +45,6 @@ busy = true updateOnboardingProfile({ strongholdPassword, hasStoredMnemonic: true }) await buildOnboardingSecretManager() - await verifyAndStoreMnemonic() router.next() } catch (err) { console.error(err) diff --git a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts index c7b66a2a6c7..0a93f54697a 100644 --- a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts +++ b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts @@ -4,11 +4,12 @@ import { addWalletPersistedDataToActiveProfile, addWalletToActiveWallets, createWallet, + IPersistedProfile, login, } from '@core/profile' import { get } from 'svelte/store' import { OnboardingType } from '../enums' -import { addWalletPersistedDataToOnboardingProfile, onboardingProfile } from '../stores' +import { onboardingProfile } from '../stores' import { createNewProfileFromOnboardingProfile } from './createNewProfileFromOnboardingProfile' import { showBalanceOverviewPopup } from '@contexts/dashboard/stores' import { @@ -18,6 +19,7 @@ import { } from '@core/wallet' import { DEFAULT_SYNC_OPTIONS } from '@core/wallet/constants' import { localize } from '@core/i18n' +import { IOnboardingProfile } from '../interfaces' export async function completeOnboardingProcess(): Promise { // if we already have an active profile @@ -27,32 +29,37 @@ export async function completeOnboardingProcess(): Promise { createNewProfileFromOnboardingProfile() } - const { onboardingType, strongholdPassword } = get(onboardingProfile)! + const profile = get(onboardingProfile)!; + const { onboardingType, strongholdPassword } = profile const shouldRecoverWallets = onboardingType === OnboardingType.Restore || onboardingType === OnboardingType.Claim showBalanceOverviewPopup.set(shouldRecoverWallets) - await initWallet(strongholdPassword) + await initWallet(profile, strongholdPassword) void login({ isFromOnboardingFlow: true, shouldRecoverWallets }) onboardingProfile.set(undefined) } -export async function initWallet(strongholdPassword?: string): Promise { +export async function initWallet(profile: IOnboardingProfile, strongholdPassword?: string): Promise { // 1. Get the wallet name const walletName = `${localize('general.wallet')} ${(get(activeWallets)?.length ?? 0) + 1}` // 2. Create the wallet instance - const wallet = await createWallet() + const wallet = await createWallet({ + address: profile.address, + profile: profile as IPersistedProfile + }) - console.log(strongholdPassword) + // 3. Load the stronghold password if necessary if(strongholdPassword){ await wallet.setStrongholdPassword(strongholdPassword) } - // 3. Sync the wallet with the Node + // 4. Sync the wallet with the Node await wallet.sync(DEFAULT_SYNC_OPTIONS) - // 4. Create a wrapper over the wallet instance and the persisted data + + // 5. Create a wrapper over the wallet instance and the persisted data const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName) addWalletToActiveWallets(walletState) diff --git a/packages/shared/lib/contexts/onboarding/actions/index.ts b/packages/shared/lib/contexts/onboarding/actions/index.ts index 6ede0989724..17a599d60a4 100644 --- a/packages/shared/lib/contexts/onboarding/actions/index.ts +++ b/packages/shared/lib/contexts/onboarding/actions/index.ts @@ -26,4 +26,3 @@ export * from './restoreBackupFromStrongholdFile' export * from './setProfileRecoveryTypeFromFilename' export * from './subscribeToWalletApiEventsForShimmerClaiming' export * from './syncShimmerClaimingAccount' -export * from './verifyAndStoreMnemonic' diff --git a/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts b/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts deleted file mode 100644 index 33f627985db..00000000000 --- a/packages/shared/lib/contexts/onboarding/actions/verifyAndStoreMnemonic.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { storeMnemonic, verifyMnemonic } from '@core/secret-manager' -import { get } from 'svelte/store' -import { onboardingProfile } from '../stores' - -/** - * Verifies, stores, then clears the mnemonic used in the onboarding flow. - */ -export async function verifyAndStoreMnemonic(): Promise { - // TODO(2.0) This shouldn't use the onboarding profile always - const mnemonic = get(onboardingProfile)?.mnemonic?.join(' ') ?? '' - - console.log("verifying...") - await verifyMnemonic(mnemonic) - console.log("verified...") - - console.log("storing...") - await storeMnemonic(mnemonic) - console.log("stored...") -} 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 21114cb2a84..3406199ae69 100644 --- a/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts +++ b/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts @@ -28,4 +28,6 @@ export interface IOnboardingProfile extends Omit, 'id shimmerClaimingAccounts?: IShimmerClaimingWallet[] hasInitialisedProfileManager?: boolean + + address: string } 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 index e753f03eca7..8f5f0c72125 100644 --- a/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts @@ -1,6 +1,7 @@ -import { onboardingProfile } from '@contexts/onboarding/stores' +import { onboardingProfile, updateOnboardingProfile } from '@contexts/onboarding/stores' import { api } from '@core/api' import { SecretManager } from '@iota/sdk' +import { verifyMnemonic } from 'shared/lib/core/secret-manager' import { get, writable, Writable } from 'svelte/store' export const onboardingProfileSecretManager: Writable = writable(null) @@ -8,18 +9,29 @@ export const onboardingProfileSecretManager: Writable = wr export async function buildOnboardingSecretManager(): Promise { const profile = get(onboardingProfile) if (profile) { - const { strongholdPassword, secretManagerOptions } = profile - console.log(secretManagerOptions, strongholdPassword) - // Create secret manager with persisted options - const secretManager = await api.createSecretManager(secretManagerOptions!) + const { strongholdPassword, secretManagerOptions, mnemonic } = profile + const mnemonicStringified = mnemonic?.join(' ') ?? '' - console.log(secretManager) - // Load the stronghold password specified in the onboarding if necessary + // 1. Create SecretManager + const secretManager = await api.createSecretManager(secretManagerOptions!) + + // 2. Load the stronghold password specified in the onboarding if necessary if(strongholdPassword){ await secretManager.setStrongholdPassword(strongholdPassword); - console.log("setted strongholdPassword") } + + // 3. Verify Mnemonic + await verifyMnemonic(mnemonicStringified); + + // 4. Store Mnemonic + await secretManager.storeMnemonic(mnemonicStringified) + + // 5. Generate address + const address = (await secretManager.generateEd25519Addresses({}))[0]; + updateOnboardingProfile({ + address + }) onboardingProfileSecretManager.set(secretManager) } else { onboardingProfileSecretManager.set(null) diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index fccfdc904c7..5fe14fc4eda 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -1,13 +1,12 @@ import { api } from '@core/api' -import { get } from 'svelte/store' -import { IProfile, IWallet } from '../interfaces' -import { activeProfile as activeProfileStore } from '../stores' +import { IPersistedProfile, IWallet } from '../interfaces' import { getSecretManagerFromProfileType, getStorageDirectoryOfProfile } from '../utils' import { WalletOptions } from '@iota/sdk' import { selectedWalletId } from '../../wallet' -export function getWalletOptions(profile: IProfile, storagePath: string): WalletOptions { - const walletOptions: WalletOptions = { +export function getWalletOptions(profile: IPersistedProfile, storagePath: string, address: string): WalletOptions { + return { + address, clientOptions: profile.clientOptions, storagePath, secretManager: getSecretManagerFromProfileType(profile.type, storagePath), @@ -17,8 +16,6 @@ export function getWalletOptions(profile: IProfile, storagePath: string): Wallet addressIndex: 0, }, } - - return walletOptions } // TODO(2.0): Fix and finish this method @@ -28,19 +25,22 @@ export function getWalletOptions(profile: IProfile, storagePath: string): Wallet - __wallet1__/ - __wallet2__/ */ -export async function createWallet(activeProfile = get(activeProfileStore)): Promise { - const id = activeProfile.id + +interface CreateWalletOptions { + profile: IPersistedProfile, + address: string +} + +export async function createWallet({ profile, address }: CreateWalletOptions): Promise { + const { id } = profile const storagePath = await getStorageDirectoryOfProfile(id) - const walletOptions = getWalletOptions(activeProfile, storagePath) - console.log("CREATING WALLET", walletOptions); + const walletOptions = getWalletOptions(profile, storagePath, address) const wallet = await api.createWallet(id, { ...walletOptions, storagePath, }) - console.log("CREATED WALLET"); - // TODO(2.0): Fix selectedWalletId.set(id) return wallet diff --git a/packages/shared/lib/core/secret-manager/actions/index.ts b/packages/shared/lib/core/secret-manager/actions/index.ts index 437e113cc79..cf6deef85ad 100644 --- a/packages/shared/lib/core/secret-manager/actions/index.ts +++ b/packages/shared/lib/core/secret-manager/actions/index.ts @@ -2,5 +2,4 @@ export * from './changeStrongholdPassword' export * from './clearStrongholdPassword' export * from './generateEd25519Address' export * from './getLedgerNanoStatus' -export * from './storeMnemonic' export * from './getSecretManager' diff --git a/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts b/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts deleted file mode 100644 index 33ec5588705..00000000000 --- a/packages/shared/lib/core/secret-manager/actions/storeMnemonic.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { onboardingProfileSecretManager } from 'shared/lib/contexts/onboarding' -import { get } from 'svelte/store' - -export function storeMnemonic(mnemonic: string): Promise { - // TODO(2.0) There are two secret managers, but we might only actually need one to store the mnemonic. - const secretManager = get(onboardingProfileSecretManager) - - if (!secretManager) { - return Promise.resolve() - } - console.log("...") - return secretManager.storeMnemonic(mnemonic) -} From 4bf970b537ce9add316b206ec800dd73e5286acc Mon Sep 17 00:00:00 2001 From: marc2332 Date: Fri, 22 Dec 2023 13:41:07 +0100 Subject: [PATCH 04/37] clean up --- .../actions/completeOnboardingProcess.ts | 13 +++++++----- .../stores/onboarding-secret-manager.store.ts | 20 +++++++++++-------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts index 0a93f54697a..a994830270a 100644 --- a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts +++ b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts @@ -29,7 +29,10 @@ export async function completeOnboardingProcess(): Promise { createNewProfileFromOnboardingProfile() } - const profile = get(onboardingProfile)!; + const profile = get(onboardingProfile) + if (!profile) { + return + } const { onboardingType, strongholdPassword } = profile const shouldRecoverWallets = onboardingType === OnboardingType.Restore || onboardingType === OnboardingType.Claim @@ -48,17 +51,17 @@ export async function initWallet(profile: IOnboardingProfile, strongholdPassword // 2. Create the wallet instance const wallet = await createWallet({ address: profile.address, - profile: profile as IPersistedProfile - }) + profile: profile as IPersistedProfile, + }) // 3. Load the stronghold password if necessary - if(strongholdPassword){ + if (strongholdPassword) { await wallet.setStrongholdPassword(strongholdPassword) } // 4. Sync the wallet with the Node await wallet.sync(DEFAULT_SYNC_OPTIONS) - + // 5. Create a wrapper over the wallet instance and the persisted data const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName) 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 index 8f5f0c72125..a68330dc4f2 100644 --- a/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts @@ -12,25 +12,29 @@ export async function buildOnboardingSecretManager(): Promise { const { strongholdPassword, secretManagerOptions, mnemonic } = profile const mnemonicStringified = mnemonic?.join(' ') ?? '' + if (!strongholdPassword || !secretManagerOptions || !mnemonic) { + return + } + // 1. Create SecretManager - const secretManager = await api.createSecretManager(secretManagerOptions!) - + const secretManager = await api.createSecretManager(secretManagerOptions) + // 2. Load the stronghold password specified in the onboarding if necessary - if(strongholdPassword){ - await secretManager.setStrongholdPassword(strongholdPassword); + if (strongholdPassword) { + await secretManager.setStrongholdPassword(strongholdPassword) } - + // 3. Verify Mnemonic - await verifyMnemonic(mnemonicStringified); + await verifyMnemonic(mnemonicStringified) // 4. Store Mnemonic await secretManager.storeMnemonic(mnemonicStringified) // 5. Generate address - const address = (await secretManager.generateEd25519Addresses({}))[0]; + const address = (await secretManager.generateEd25519Addresses({}))[0] updateOnboardingProfile({ - address + address, }) onboardingProfileSecretManager.set(secretManager) } else { From a5a8969c51609e4e19df9d6a4aa7ab2564f3c5ed Mon Sep 17 00:00:00 2001 From: marc2332 Date: Fri, 22 Dec 2023 16:40:47 +0100 Subject: [PATCH 05/37] clean up more code --- .../views/network-setup/views/CustomNetworkView.svelte | 10 +++++----- .../views/ChooseRestoreProfileFlowView.svelte | 10 +++++++--- ...ngProfileManager.ts => cleanupOnboardingProfile.ts} | 3 +-- .../shared/lib/contexts/onboarding/actions/index.ts | 2 +- .../onboarding/actions/initialiseOnboardingProfile.ts | 2 +- 5 files changed, 15 insertions(+), 12 deletions(-) rename packages/shared/lib/contexts/onboarding/actions/{cleanupOnboardingProfileManager.ts => cleanupOnboardingProfile.ts} (72%) diff --git a/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte b/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte index 7b3f36a0a9b..ca735cb4d2d 100644 --- a/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte +++ b/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte @@ -2,8 +2,8 @@ import { showAppNotification } from '@auxiliary/notification' import { OnboardingLayout } from '@components' import { - cleanupOnboardingProfileManager, - initialiseProfileManagerFromOnboardingProfile, + cleanupOnboardingProfile, + initialiseOnboardingProfile, updateOnboardingProfile, } from '@contexts/onboarding' import { localize } from '@core/i18n' @@ -41,7 +41,7 @@ validateClientOptions: false, }) updateOnboardingProfile({ clientOptions: { nodes: [node], primaryNode: node } }) - await initialiseProfileManagerFromOnboardingProfile(true) + await initialiseOnboardingProfile(true) // The API request to check if a node is reachable requires an existing account manager. const nodeInfoResponse = await getNodeInfo(node.url) @@ -55,13 +55,13 @@ const customCoinType = networkId === NetworkId.Custom ? Number(coinType) : undefined const network = buildPersistedNetworkFromNodeInfoResponse(nodeInfoResponse, customCoinType) updateOnboardingProfile({ network }) - await cleanupOnboardingProfileManager() + await cleanupOnboardingProfile() $networkSetupRouter.next() } catch (err) { console.error(err) updateOnboardingProfile({ clientOptions: undefined, network: undefined }) - await cleanupOnboardingProfileManager() + await cleanupOnboardingProfile() if (err?.error?.includes('error sending request for url')) { formError = localize('error.node.unabledToConnect') 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 01ac17563ee..1a1da37d00d 100644 --- a/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte +++ b/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte @@ -1,6 +1,11 @@ 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 1a1da37d00d..424e3ab54c7 100644 --- a/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte +++ b/packages/desktop/views/onboarding/views/restore-profile/views/ChooseRestoreProfileFlowView.svelte @@ -40,11 +40,11 @@ onMount(async () => { // Clean up if user has navigated back to this view - if ($onboardingProfile.hasInitialisedProfileManager) { + if ($onboardingProfile.secretManagerOptions) { await clearProfileFromMemory() await removeProfileFolder($onboardingProfile.id) } - updateOnboardingProfile({ type: undefined, restoreProfileType: undefined, hasInitialisedProfileManager: false }) + updateOnboardingProfile({ type: undefined, restoreProfileType: undefined, secretManagerOptions: undefined }) }) diff --git a/packages/shared/lib/contexts/onboarding/actions/cleanupOnboarding.ts b/packages/shared/lib/contexts/onboarding/actions/cleanupOnboarding.ts index bc55911e4a4..c58d98f1af3 100644 --- a/packages/shared/lib/contexts/onboarding/actions/cleanupOnboarding.ts +++ b/packages/shared/lib/contexts/onboarding/actions/cleanupOnboarding.ts @@ -1,15 +1,15 @@ import { onboardingProfile } from '../stores' import { deleteOnboardingProfile } from './deleteOnboardingProfile' -import { destroyShimmerClaimingProfileManager } from './destroyShimmerClaimingProfileManager' +import { destroyShimmerClaimingWallet } from './destroyShimmerClaimingWallet' export async function cleanupOnboarding(deleteProfile: boolean = false): Promise { onboardingProfile.set(null) - await cleanupExtraProfileManagers() + await cleanupExtraWallets() if (deleteProfile) { await deleteOnboardingProfile() } } -async function cleanupExtraProfileManagers(): Promise { - await destroyShimmerClaimingProfileManager() +async function cleanupExtraWallets(): Promise { + await destroyShimmerClaimingWallet() } diff --git a/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts index 5ab85c66926..4291f378b4b 100644 --- a/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts @@ -4,7 +4,7 @@ import { generateRandomId } from '@core/utils' import { getSecretManagerFromProfileType } from '@core/profile' import { get } from 'svelte/store' import { RestoreProfileType } from '../enums' -import { getTemporaryProfileManagerStorageDirectory } from '../helpers' +import { getTemporaryWalletStorageDirectory } from '../helpers' import { onboardingProfile, shimmerClaimingProfileManager } from '../stores' // TODO(2.0): Fix all shimmer claiming and rename this @@ -14,7 +14,7 @@ export async function createShimmerClaimingProfileManager(): Promise { return } - const storagePath = await getTemporaryProfileManagerStorageDirectory() + const storagePath = await getTemporaryWalletStorageDirectory() const coinType = COIN_TYPE[NetworkId.Iota] const clientOptions = $onboardingProfile?.clientOptions const secretManager = getSecretManagerFromProfileType($onboardingProfile?.type, storagePath) diff --git a/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts similarity index 68% rename from packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts rename to packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts index 3ebf83d9b29..6689a014f28 100644 --- a/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts @@ -2,18 +2,18 @@ import { get } from 'svelte/store' import { Platform } from '@core/app' -import { getTemporaryProfileManagerStorageDirectory } from '../helpers' +import { getTemporaryWalletStorageDirectory } from '../helpers' import { shimmerClaimingProfileManager } from '../stores' import { clearProfileFromMemory } from '@core/profile/actions' // TODO(2.0) Fix this -export async function destroyShimmerClaimingProfileManager(): Promise { +export async function destroyShimmerClaimingWallet(): Promise { const _shimmerClaimingProfileManager = get(shimmerClaimingProfileManager) if (!_shimmerClaimingProfileManager) { return } await clearProfileFromMemory(shimmerClaimingProfileManager) - const profilePath = await getTemporaryProfileManagerStorageDirectory() + const profilePath = await getTemporaryWalletStorageDirectory() await Platform.removeProfileFolder(profilePath) } diff --git a/packages/shared/lib/contexts/onboarding/actions/index.ts b/packages/shared/lib/contexts/onboarding/actions/index.ts index 21b3d22ef6a..641dba26483 100644 --- a/packages/shared/lib/contexts/onboarding/actions/index.ts +++ b/packages/shared/lib/contexts/onboarding/actions/index.ts @@ -8,7 +8,7 @@ export * from './createNewProfileFromOnboardingProfile' export * from './createNewProfileFromOnboardingProfile' export * from './createShimmerClaimingProfileManager' export * from './deleteOnboardingProfile' -export * from './destroyShimmerClaimingProfileManager' +export * from './destroyShimmerClaimingWallet' export * from './findShimmerRewards' export * from './generateMnemonicForOnboardingProfile' export * from './handleTransactionInclusionEventForShimmerClaiming' diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts index ab936461900..fdd4a07790c 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts @@ -1,11 +1,8 @@ import { get } from 'svelte/store' - import { onboardingProfileSecretManager } from '../stores' - import { getSecretManagerFromProfileType, getStorageDirectoryOfProfile, removeProfileFolder } from '@core/profile' import { onboardingProfile, updateOnboardingProfile } from '../stores' -// TODO(2.0) Fix this, profile manager is gone export async function initialiseOnboardingProfileWithSecretManager( checkForExistingSecretManager?: boolean ): Promise { @@ -28,5 +25,5 @@ export async function initialiseOnboardingProfileWithSecretManager( const secretManagerOptions = getSecretManagerFromProfileType(activeOnboardingProfile.type, storagePath) - updateOnboardingProfile({ secretManagerOptions, hasInitialisedProfileManager: true }) + updateOnboardingProfile({ secretManagerOptions }) } diff --git a/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts index 71fca4d4f81..12a63374a65 100644 --- a/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts @@ -1,18 +1,14 @@ import { NetworkId } from '@core/network/enums' import { getStorageDirectoryOfProfile } from '@core/profile/utils' import { get } from 'svelte/store' -import { - getTemporaryProfileManagerStorageDirectory, - restoreBackupByCopyingFile, - validateStrongholdCoinType, -} from '../helpers' +import { getTemporaryWalletStorageDirectory, restoreBackupByCopyingFile, validateStrongholdCoinType } from '../helpers' import { onboardingProfile, shimmerClaimingProfileManager } from '../stores' // TODO(2.0) Fix this export async function restoreBackupForShimmerClaimingProfileManager(strongholdPassword: string): Promise { try { const { id, importFilePath, clientOptions } = get(onboardingProfile) - const tempProfileDirectory = await getTemporaryProfileManagerStorageDirectory() + const tempProfileDirectory = await getTemporaryWalletStorageDirectory() await restoreBackupByCopyingFile( importFilePath, tempProfileDirectory, diff --git a/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts b/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts index 1f70fb44bf7..7e501d82525 100644 --- a/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts @@ -1,22 +1,19 @@ import { getStorageDirectoryOfProfile } from '@core/profile' +import { restoreBackup } from '@core/wallet' import { get } from 'svelte/store' import { restoreBackupByCopyingFile } from '../helpers' -import { onboardingProfile } from '../stores' - -// TODO(2.0) Fix this +import { onboardingProfile, onboardingProfileSecretManager } from '../stores' export async function restoreBackupFromStrongholdFile(strongholdPassword: string): Promise { - const { id, importFilePath, clientOptions, network } = get(onboardingProfile) - try { - await restoreBackup(importFilePath, strongholdPassword, network.protocol.bech32Hrp) - } catch (err) { - const storageDirectory = await getStorageDirectoryOfProfile(id) - await restoreBackupByCopyingFile( - importFilePath, - storageDirectory, - strongholdPassword, - clientOptions, - profileManager - ) + const profile = get(onboardingProfile) + if (profile) { + const { id, importFilePath, network } = profile + try { + await restoreBackup(importFilePath, strongholdPassword, network.protocol.bech32Hrp) + } catch (err) { + const storageDirectory = await getStorageDirectoryOfProfile(id) + const secretManager = get(onboardingProfileSecretManager) + await restoreBackupByCopyingFile(importFilePath, storageDirectory, strongholdPassword, secretManager) + } } } diff --git a/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts b/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts index b20b412dd07..8d405a33509 100644 --- a/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts +++ b/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts @@ -1 +1 @@ -export const TEMPORARY_PROFILE_MANAGER_DIRECTORY_NAME = 'temp' +export const TEMPORARY_WALLET_DIRECTORY_NAME = 'temp' diff --git a/packages/shared/lib/contexts/onboarding/errors/index.ts b/packages/shared/lib/contexts/onboarding/errors/index.ts index 039f8c64d70..29d24b40542 100644 --- a/packages/shared/lib/contexts/onboarding/errors/index.ts +++ b/packages/shared/lib/contexts/onboarding/errors/index.ts @@ -5,4 +5,4 @@ export * from './shimmer-rewards.errors' export * from './stronghold-backup.errors' export * from './stronghold-migration-required.error' export * from './unable-to-copy-stronghold-backup-file.error' -export * from './unable-to-restore-backup-for-profile-manager.error' +export * from './unable-to-restore-backup-for-wallet.error' diff --git a/packages/shared/lib/contexts/onboarding/errors/unable-to-restore-backup-for-profile-manager.error.ts b/packages/shared/lib/contexts/onboarding/errors/unable-to-restore-backup-for-wallet.error.ts similarity index 53% rename from packages/shared/lib/contexts/onboarding/errors/unable-to-restore-backup-for-profile-manager.error.ts rename to packages/shared/lib/contexts/onboarding/errors/unable-to-restore-backup-for-wallet.error.ts index 0112f117290..212e7da18d7 100644 --- a/packages/shared/lib/contexts/onboarding/errors/unable-to-restore-backup-for-profile-manager.error.ts +++ b/packages/shared/lib/contexts/onboarding/errors/unable-to-restore-backup-for-wallet.error.ts @@ -1,10 +1,10 @@ import { BaseError, DEFAULT_APP_ERROR_PARAMETERS } from '@core/error' -export class UnableToRestoreBackupForProfileManagerError extends BaseError { +export class UnableToRestoreBackupForWalletError extends BaseError { constructor() { super({ ...DEFAULT_APP_ERROR_PARAMETERS, - message: 'error.backup.unableToRestoreForProfileManager', + message: 'error.backup.unableToRestoreForWallet', }) } } diff --git a/packages/shared/lib/contexts/onboarding/helpers/getTemporaryProfileManagerStorageDirectory.ts b/packages/shared/lib/contexts/onboarding/helpers/getTemporaryProfileManagerStorageDirectory.ts deleted file mode 100644 index 3030c640e7a..00000000000 --- a/packages/shared/lib/contexts/onboarding/helpers/getTemporaryProfileManagerStorageDirectory.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { getStorageDirectoryOfProfiles } from '@core/profile' - -import { TEMPORARY_PROFILE_MANAGER_DIRECTORY_NAME } from '../constants' - -export async function getTemporaryProfileManagerStorageDirectory(): Promise { - const storageDir = await getStorageDirectoryOfProfiles() - return `${storageDir}/${TEMPORARY_PROFILE_MANAGER_DIRECTORY_NAME}` -} diff --git a/packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts b/packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts new file mode 100644 index 00000000000..a594e3d2f2b --- /dev/null +++ b/packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts @@ -0,0 +1,7 @@ +import { getStorageDirectoryOfProfiles } from '@core/profile' +import { TEMPORARY_WALLET_DIRECTORY_NAME } from '../constants' + +export async function getTemporaryWalletStorageDirectory(): Promise { + const storageDir = await getStorageDirectoryOfProfiles() + return `${storageDir}/${TEMPORARY_WALLET_DIRECTORY_NAME}` +} diff --git a/packages/shared/lib/contexts/onboarding/helpers/index.ts b/packages/shared/lib/contexts/onboarding/helpers/index.ts index 8bb90181be3..49a273d318c 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/index.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/index.ts @@ -3,7 +3,7 @@ export * from './convertOnboardingProfileToPersistedProfile' export * from './copyStrongholdFileToProfileDirectory' export * from './deriveShimmerClaimingWalletState' export * from './getSortedRenamedBoundAccounts' -export * from './getTemporaryProfileManagerStorageDirectory' +export * from './getTemporaryWalletStorageDirectory' export * from './prepareShimmerClaimingAccount' export * from './restoreBackupByCopyingFile' export * from './validateStrongholdCoinType' diff --git a/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts b/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts index 7734eb5563e..dc1ac93bd65 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts @@ -1,31 +1,27 @@ -import { get, Writable } from 'svelte/store' - -import { IClientOptions } from '@iota/sdk/out/types' - import { ClientError, CLIENT_ERROR_REGEXES } from '@core/error' - import { copyStrongholdFileToProfileDirectory } from '../helpers' -import { StrongholdMigrationRequiredError, UnableToRestoreBackupForProfileManagerError } from '../errors' +import { StrongholdMigrationRequiredError, UnableToRestoreBackupForWalletError } from '../errors' +import { SecretManager } from '@iota/sdk' -// TODO(2.0) Fix this, profile manager is gone export async function restoreBackupByCopyingFile( importFilePath: string, storageDirectory: string, strongholdPassword: string, - clientOptions: IClientOptions, - manager: Writable + secretManager: SecretManager ): Promise { try { await copyStrongholdFileToProfileDirectory(storageDirectory, importFilePath) - await get(manager)?.setStrongholdPassword(strongholdPassword) - await get(manager)?.setClientOptions(clientOptions) + await secretManager.setStrongholdPassword(strongholdPassword) + // TODO(2.0) The secret manager doesn't need the client options, so this is fine to not do anymore + // But, we should make sure 100% of it anyway + // await secretManager.setClientOptions(clientOptions) } catch (err) { if (CLIENT_ERROR_REGEXES[ClientError.MigrationRequired].test(err?.error)) { throw new StrongholdMigrationRequiredError() } else if (CLIENT_ERROR_REGEXES[ClientError.InvalidStrongholdPassword].test(err?.error)) { throw err } else { - throw new UnableToRestoreBackupForProfileManagerError() + throw new UnableToRestoreBackupForWalletError() } } } 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 3406199ae69..29c46c9d3d3 100644 --- a/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts +++ b/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts @@ -27,7 +27,5 @@ export interface IOnboardingProfile extends Omit, 'id // Shimmer claiming data shimmerClaimingAccounts?: IShimmerClaimingWallet[] - hasInitialisedProfileManager?: boolean - address: string } 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 f98e39597e5..69750a36a6c 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/login.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/login.ts @@ -9,21 +9,16 @@ import { pollNetworkStatus } from '@core/network/actions' import { loadNftsForActiveProfile } from '@core/nfts' import { routerManager } from '@core/router/stores' import { SECONDS_PER_MINUTE } from '@core/utils' -import { sleep } from '@core/utils/os' import { - createNewWallet, generateAndStoreActivitiesForAllWallets, isStrongholdUnlocked, refreshWalletAssetsForActiveProfile, setSelectedWallet, } from '@core/wallet/actions' import { get } from 'svelte/store' -import { - CHECK_PREVIOUS_MANAGER_IS_DESTROYED_INTERVAL, - CHECK_PREVIOUS_MANAGER_IS_DESTROYED_MAX_COUNT, -} from '../../constants' +import { CHECK_PREVIOUS_WALLETS_ARE_DESTROYED_TIMEOUT } from '../../constants' import { ProfileType } from '../../enums' -import { ILoginOptions, IWallet } from '../../interfaces' +import { ILoginOptions } from '../../interfaces' import { activeProfile, activeWallets, @@ -39,7 +34,6 @@ import { logout } from './logout' import { subscribeToWalletApiEventsForActiveProfile } from './subscribeToWalletApiEventsForActiveProfile' import { checkAndUpdateActiveProfileNetwork } from './checkAndUpdateActiveProfileNetwork' import { checkAndRemoveProfilePicture } from './checkAndRemoveProfilePicture' -import { checkActiveProfileAuth, getWallets } from '@core/profile' import { setStrongholdPasswordClearInterval, startBackgroundSync } from '@core/wallet/actions' // TODO(2.0) Remove usage of profile manager @@ -47,76 +41,28 @@ export async function login(loginOptions?: ILoginOptions): Promise { const loginRouter = get(routerManager).getRouterForAppContext(AppContext.Login) try { const _activeProfile = get(activeProfile) - const { loggedIn, lastActiveAt, id, isStrongholdLocked, type } = _activeProfile + const { loggedIn, lastActiveAt, id, isStrongholdLocked, type, lastUsedWalletId } = _activeProfile if (id) { - // Step 1: create profile manager if its doesn't exist - incrementLoginProgress() - await waitForPreviousManagerToBeDestroyed() - - // Step 3: load and build all the profile data + // Step 1: Wait for wallets to be destroyed incrementLoginProgress() - let wallets: IWallet[] = [] - - if (loginOptions?.isFromOnboardingFlow && loginOptions?.shouldRecoverWallets) { - /* - const { initialAccountRange, addressGapLimit } = DEFAULT_ACCOUNT_RECOVERY_CONFIGURATION[type] - const recoverAccountsPayload: RecoverAccountsPayload = { - accountStartIndex: 0, - accountGapLimit: initialAccountRange, - addressGapLimit, - syncOptions: DEFAULT_SYNC_OPTIONS, - } - accounts = await recoverAccounts(recoverAccountsPayload) - */ - } else { - wallets = await getWallets() - } - /** - * NOTE: In the case no wallets with funds were recovered, we must - * create one for the new profile. - */ - if (wallets?.length === 0) { - const onUnlocked = new Promise((resolve) => { - const onSuccess = () => { - resolve(true) - return Promise.resolve() - } - const onCancel = () => resolve(false) - const config = { stronghold: false, ledger: false } - checkActiveProfileAuth(onSuccess, config, onCancel) - }) - const success = await onUnlocked - if (success) { - await createNewWallet() - } else { - resetLoginProgress() - return loginRouter.previous() - } - } + await waitForWalletsToBeDestroyed() - // Step 4: load wallets + // Step 2: Build wallets incrementLoginProgress() await loadWallets() - const initialSelectedWalletId = get(activeWallets)?.[0]?.id - - // TODO(2.0): is needed lastUsedWalletId? - // if ( - // initialSelectedWalletId && - // get(activeWallets)?.find((wallet) => wallet.id === initialSelectedWalletId) - // ) { - // initialSelectedWalletId = lastUsedWalletId - // } - // console.log("initialSelectedWalletId", initialSelectedWalletId); - + let initialSelectedWalletId = get(activeWallets)?.[0]?.id + if (lastUsedWalletId && get(activeWallets)?.find((wallet) => wallet.id === initialSelectedWalletId)) { + initialSelectedWalletId = lastUsedWalletId + } setSelectedWallet(initialSelectedWalletId) - // Step 2: get node info to check we have a synced node + // Step 3: get node info to check we have a synced node incrementLoginProgress() await checkAndUpdateActiveProfileNetwork() void pollNetworkStatus() - // Step 5: load assets + // Step 4: load assets incrementLoginProgress() await refreshWalletAssetsForActiveProfile( _activeProfile.forceAssetRefresh, @@ -126,12 +72,12 @@ export async function login(loginOptions?: ILoginOptions): Promise { await loadNftsForActiveProfile() checkAndRemoveProfilePicture() - // Step 6: generate and store activities for all wallets + // Step 5: generate and store activities for all wallets incrementLoginProgress() await generateAndStoreActivitiesForAllWallets() if (type === ProfileType.Software) { - // Step 7: set initial stronghold status + // Step 6: set initial stronghold status incrementLoginProgress() const strongholdUnlocked = await isStrongholdUnlocked() isStrongholdLocked.set(!strongholdUnlocked) @@ -146,12 +92,12 @@ export async function login(loginOptions?: ILoginOptions): Promise { incrementLoginProgress(2) } - // Step 8: start background sync + // Step 7: start background sync incrementLoginProgress() subscribeToWalletApiEventsForActiveProfile() await startBackgroundSync({ syncIncomingTransactions: true }) - // Step 9: finish login + // Step 8: finish login incrementLoginProgress() if (isLedgerProfile(type)) { pollLedgerNanoStatus() @@ -183,12 +129,21 @@ export async function login(loginOptions?: ILoginOptions): Promise { } } -async function waitForPreviousManagerToBeDestroyed(): Promise { - for (let count = 0; count < CHECK_PREVIOUS_MANAGER_IS_DESTROYED_MAX_COUNT; count++) { - if (!get(isDestroyingWallets)) { - return Promise.resolve() - } - await sleep(CHECK_PREVIOUS_MANAGER_IS_DESTROYED_INTERVAL) - } - return Promise.reject() +async function waitForWalletsToBeDestroyed(): Promise { + return new Promise((res, rej) => { + if (!get(isDestroyingWallets)) return res() + + const unsub = isDestroyingWallets.subscribe((destroyed) => { + if (!destroyed) { + res() + unsub() + clearTimeout(timeout) + } + }) + + const timeout = setTimeout(() => { + rej() + unsub() + }, CHECK_PREVIOUS_WALLETS_ARE_DESTROYED_TIMEOUT) + }) } diff --git a/packages/shared/lib/core/profile/constants/check-previous-manager-is-destroyed.constants.ts b/packages/shared/lib/core/profile/constants/check-previous-manager-is-destroyed.constants.ts deleted file mode 100644 index d7efdbeda22..00000000000 --- a/packages/shared/lib/core/profile/constants/check-previous-manager-is-destroyed.constants.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const CHECK_PREVIOUS_MANAGER_IS_DESTROYED_INTERVAL = 100 -export const CHECK_PREVIOUS_MANAGER_IS_DESTROYED_MAX_COUNT = 150 diff --git a/packages/shared/lib/core/profile/constants/check-previous-wallets-are-destroyed.constants.ts b/packages/shared/lib/core/profile/constants/check-previous-wallets-are-destroyed.constants.ts new file mode 100644 index 00000000000..dead4d792fb --- /dev/null +++ b/packages/shared/lib/core/profile/constants/check-previous-wallets-are-destroyed.constants.ts @@ -0,0 +1 @@ +export const CHECK_PREVIOUS_WALLETS_ARE_DESTROYED_TIMEOUT = 1500 // 15 seconds diff --git a/packages/shared/lib/core/profile/constants/index.ts b/packages/shared/lib/core/profile/constants/index.ts index 0e33dcb597c..469e58aa61d 100644 --- a/packages/shared/lib/core/profile/constants/index.ts +++ b/packages/shared/lib/core/profile/constants/index.ts @@ -1,4 +1,4 @@ -export * from './check-previous-manager-is-destroyed.constants' +export * from './check-previous-wallets-are-destroyed.constants' export * from './default-account-recovery-configuration.constant' export * from './balance-finder-account-recovery-configuration.constant' export * from './default-persisted-profile-object.constant' diff --git a/packages/shared/lib/core/profile/constants/login-steps.constant.ts b/packages/shared/lib/core/profile/constants/login-steps.constant.ts index ee895597dbe..f9948774b14 100644 --- a/packages/shared/lib/core/profile/constants/login-steps.constant.ts +++ b/packages/shared/lib/core/profile/constants/login-steps.constant.ts @@ -1,11 +1,10 @@ export const LOGIN_STEPS = { - 1: 'buildProfileManager', + 1: 'prepareWallet', 2: 'updateNodeInfo', - 3: 'recoverAccounts', - 4: 'loadAccounts', - 5: 'loadAssets', - 6: 'loadActivities', - 7: 'setStrongholdStatus', - 8: 'startBackgroundSync', - 9: 'loggingIn', + 3: 'buildWallets', + 4: 'loadAssets', + 5: 'loadActivities', + 6: 'setStrongholdStatus', + 7: 'startBackgroundSync', + 8: 'loggingIn', } diff --git a/packages/shared/lib/core/wallet/actions/backup.ts b/packages/shared/lib/core/wallet/actions/backup.ts index 154222727d9..7fece240faf 100644 --- a/packages/shared/lib/core/wallet/actions/backup.ts +++ b/packages/shared/lib/core/wallet/actions/backup.ts @@ -1,7 +1,6 @@ -import { get } from 'svelte/store' -import { profileManager } from '../stores' +import { getSelectedWallet } from '../stores' export async function backup(dest: string, password: string): Promise { - const manager = get(profileManager) - await manager.backup(dest, password) + const wallet = getSelectedWallet() + await wallet.backup(dest, password) } diff --git a/packages/shared/lib/core/wallet/actions/restoreBackup.ts b/packages/shared/lib/core/wallet/actions/restoreBackup.ts index d1a2287a4dc..6864562a9d2 100644 --- a/packages/shared/lib/core/wallet/actions/restoreBackup.ts +++ b/packages/shared/lib/core/wallet/actions/restoreBackup.ts @@ -1,12 +1,11 @@ -import { get } from 'svelte/store' -import { profileManager } from '../stores' +import { getSelectedWallet } from '../stores' -// If IGNORE_IF_COIN_TYPE_MISMATCH is provided wallet.rs won't restore the client options. -// If IGNORE_IF_COIN_TYPE_MISMATCH == true, wallet.rs won't restore the client options, coin type +// If IGNORE_IF_COIN_TYPE_MISMATCH is provided, the SDK won't restore the client options. +// If IGNORE_IF_COIN_TYPE_MISMATCH == true, the SDK won't restore the client options, coin type // and accounts IF the cointype doesn't match const IGNORE_IF_COIN_TYPE_MISMATCH = true export async function restoreBackup(importFilePath: string, password: string, bech32Hrp: string): Promise { - const manager = get(profileManager) - await manager.restoreBackup(importFilePath, password, IGNORE_IF_COIN_TYPE_MISMATCH, bech32Hrp) + const wallet = getSelectedWallet() + await wallet.restoreBackup(importFilePath, password, IGNORE_IF_COIN_TYPE_MISMATCH, bech32Hrp) } diff --git a/packages/shared/locales/en.json b/packages/shared/locales/en.json index c8530fcc911..eba1207134d 100644 --- a/packages/shared/locales/en.json +++ b/packages/shared/locales/en.json @@ -440,8 +440,7 @@ "loginSteps": { "buildProfileManager": "Initialising profile manager", "updateNodeInfo": "Checking node health", - "recoverAccounts": "Generating accounts", - "loadAccounts": "Syncing accounts", + "buildWallets": "Building wallets", "loadAssets": "Loading native assets" , "loadActivities": "Building activity history", "setStrongholdStatus": "Securing stronghold", @@ -2008,7 +2007,7 @@ "phraseUnrecognizedWord": "Unrecognized word \"{word}\" in your recovery phrase", "phraseCaseWord": "The word \"{word}\" should be lower case", "unableToCopyFile": "Unable to copy Stronghold backup file", - "unableToRestoreForProfileManager": "Unable to restore Stronghold backup for profile manager" + "unableToRestoreForWallet": "Unable to restore Stronghold backup for wallet" }, "ledger": { "appNotOpen": "You must open the {network} app on your Ledger device.", From cc59db72105b8794a0f221bc829dc19da683dbf0 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 10 Jan 2024 09:47:33 +0100 Subject: [PATCH 08/37] clean up more code --- packages/desktop/App.svelte | 4 ++-- packages/desktop/components/TitleBar.svelte | 4 ++-- .../MintNativeTokenButton.svelte | 2 +- .../desktop/views/dashboard/Dashboard.svelte | 2 +- .../views/advanced/HiddenAccounts.svelte | 2 +- .../actions/active-profile/loadWallets.ts | 8 +++---- .../profile/actions/active-profile/logout.ts | 4 ++-- .../initial-active-profile.constant.ts | 2 +- .../profile/interfaces/profile.interface.ts | 2 +- .../core/wallet/actions/buildWalletState.ts | 23 +++++++++---------- .../lib/core/wallet/actions/loadWallet.ts | 2 -- 11 files changed, 26 insertions(+), 29 deletions(-) diff --git a/packages/desktop/App.svelte b/packages/desktop/App.svelte index 521611d8da0..9ae7f2e9520 100644 --- a/packages/desktop/App.svelte +++ b/packages/desktop/App.svelte @@ -45,7 +45,7 @@ appStage.set(AppStage[process.env.STAGE.toUpperCase()] ?? AppStage.ALPHA) - const { loggedIn, hasLoadedAccounts } = $activeProfile + const { loggedIn, hasLoadedWallets } = $activeProfile $: if ($activeProfile && !$loggedIn) { closePopup(true) @@ -69,7 +69,7 @@ document.dir = $localeDirection } - $: isDashboardVisible = $appRoute === AppRoute.Dashboard && $hasLoadedAccounts && $popupState.id !== 'busy' + $: isDashboardVisible = $appRoute === AppRoute.Dashboard && $hasLoadedWallets && $popupState.id !== 'busy' $: $nftDownloadQueue, downloadNextNftInQueue() diff --git a/packages/desktop/components/TitleBar.svelte b/packages/desktop/components/TitleBar.svelte index f69854b5a76..ec4cac46d43 100644 --- a/packages/desktop/components/TitleBar.svelte +++ b/packages/desktop/components/TitleBar.svelte @@ -8,11 +8,11 @@ import { Icon as IconEnum } from '@auxiliary/icon' import { popupState } from '@auxiliary/popup' - const { hasLoadedAccounts } = $activeProfile + const { hasLoadedWallets } = $activeProfile let isMaximized = false - $: isDashboardVisible = $appRoute === AppRoute.Dashboard && $hasLoadedAccounts && $popupState.id !== 'busy' + $: isDashboardVisible = $appRoute === AppRoute.Dashboard && $hasLoadedWallets && $popupState.id !== 'busy' $: isWindows = $platform === PlatformOption.Windows async function onResize(): Promise { diff --git a/packages/desktop/components/buttons/popup-buttons/MintNativeTokenButton.svelte b/packages/desktop/components/buttons/popup-buttons/MintNativeTokenButton.svelte index cd34a528133..441dfd3044b 100644 --- a/packages/desktop/components/buttons/popup-buttons/MintNativeTokenButton.svelte +++ b/packages/desktop/components/buttons/popup-buttons/MintNativeTokenButton.svelte @@ -8,7 +8,7 @@ import { closePopup, openPopup, PopupId } from '@auxiliary/popup' import { TextHintVariant } from 'shared/components/enums' - // TODO(2.0) Should this be checking if it has accounts? + // TODO(2.0) This should check if it has account outputs now. $: hasAccounts = $selectedWallet.balances?.accounts.length > 0 function onMintNativeTokenClick(): void { diff --git a/packages/desktop/views/dashboard/Dashboard.svelte b/packages/desktop/views/dashboard/Dashboard.svelte index a35a55e7850..19771861f34 100644 --- a/packages/desktop/views/dashboard/Dashboard.svelte +++ b/packages/desktop/views/dashboard/Dashboard.svelte @@ -61,7 +61,7 @@ } function handleDeepLinkRequest(data: string): void { - if ($activeProfile?.hasLoadedAccounts) { + if ($activeProfile?.hasLoadedWallets) { handleDeepLink(data) } } diff --git a/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte b/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte index 867610774ae..ce386e4fb99 100644 --- a/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte +++ b/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte @@ -7,7 +7,7 @@ let showHiddenAccounts = $activeProfile?.showHiddenAccounts $: updateActiveProfile({ showHiddenAccounts: showHiddenAccounts }) - $: if ($activeProfile?.hasLoadedAccounts && !showHiddenAccounts) { + $: if ($activeProfile?.hasLoadedWallets && !showHiddenAccounts) { setNextSelectedWallet() } diff --git a/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts b/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts index 5994c0ccc35..c140f834ffc 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts @@ -4,15 +4,15 @@ import { activeWallets, activeProfile } from '../../stores' import { getWallets } from '../getWallets' export async function loadWallets(): Promise { - const { hasLoadedAccounts } = get(activeProfile) + const { hasLoadedWallets } = get(activeProfile) const walletResponse = await getWallets() if (walletResponse.length === 0) { - hasLoadedAccounts.set(true) + hasLoadedWallets.set(true) return } if (walletResponse) { const loadedWallets = await Promise.all(walletResponse?.map((accountResponse) => loadWallet(accountResponse))) - activeWallets.set(loadedWallets) // TODO(2.0) We can't sort this like this: sort((a, b) => a.getMetadata().index - b.getMetadata().index) - hasLoadedAccounts.set(true) + activeWallets.set(loadedWallets) + hasLoadedWallets.set(true) } } 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 2db49891b54..fd56aabb908 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/logout.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/logout.ts @@ -41,11 +41,11 @@ export async function logout(clearActiveProfile = true, _lockStronghold = true): } function cleanupProfileState(clearActiveProfile: boolean): void { - const { lastActiveAt, loggedIn, hasLoadedAccounts } = get(activeProfile) + const { lastActiveAt, loggedIn, hasLoadedWallets } = get(activeProfile) loggedIn.set(false) lastActiveAt.set(new Date()) - hasLoadedAccounts.set(false) + hasLoadedWallets.set(false) resetSelectedWalletId() void stopDownloadingNftMediaFromQueue() diff --git a/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts b/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts index 0eba0e79954..29fcb2d3064 100644 --- a/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts +++ b/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts @@ -2,7 +2,7 @@ import { writable } from 'svelte/store' import { IProfile } from '../interfaces' export const INITIAL_ACTIVE_PROFILE: Partial = { - hasLoadedAccounts: writable(false), + hasLoadedWallets: writable(false), isStrongholdLocked: writable(true), shouldOpenProfileModal: writable(false), loggedIn: writable(false), diff --git a/packages/shared/lib/core/profile/interfaces/profile.interface.ts b/packages/shared/lib/core/profile/interfaces/profile.interface.ts index 804186f4728..d2842936271 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 // TODO(2.0) Shouldn't we rename this field? + hasLoadedWallets: Writable isStrongholdLocked: Writable shouldOpenProfileModal: Writable internalTransfersInProgress: Writable<{ diff --git a/packages/shared/lib/core/wallet/actions/buildWalletState.ts b/packages/shared/lib/core/wallet/actions/buildWalletState.ts index bbb764f8025..a4bc04f2c88 100644 --- a/packages/shared/lib/core/wallet/actions/buildWalletState.ts +++ b/packages/shared/lib/core/wallet/actions/buildWalletState.ts @@ -3,13 +3,13 @@ import { IPersistedWalletData } from '../interfaces/persisted-wallet-data.interf import { IWalletState } from '../interfaces/wallet-state.interface' import { IWallet } from '@core/profile/interfaces' import { getAddressesWithOutputs } from './getAddressesWithOutputs' +import { getDepositAddress } from '../utils' -// TODO(2.0): Fix usages of buildAccountState export async function buildWalletState( wallet: IWallet, walletPersistedData: IPersistedWalletData ): Promise { - const balances: Balance = { + let balances: Balance = { baseCoin: { total: BigInt(0), available: BigInt(0), @@ -30,17 +30,16 @@ export async function buildWalletState( delegations: [], } - const depositAddress = '' - const votingPower = '' + let depositAddress = '' + let votingPower = '' - // TODO(2.0) Fix - // try { - // balances = await wallet.getBalance() - // depositAddress = await getDepositAddress(wallet) - // votingPower = balances.baseCoin.votingPower - // } catch (err) { - // console.error(err) - // } + try { + balances = await wallet.getBalance() + depositAddress = await getDepositAddress(wallet) + votingPower = balances.baseCoin.votingPower + } catch (err) { + console.error(err) + } const addressesWithOutputs = await getAddressesWithOutputs(wallet) return { diff --git a/packages/shared/lib/core/wallet/actions/loadWallet.ts b/packages/shared/lib/core/wallet/actions/loadWallet.ts index 542d6b1f21a..efd628079c8 100644 --- a/packages/shared/lib/core/wallet/actions/loadWallet.ts +++ b/packages/shared/lib/core/wallet/actions/loadWallet.ts @@ -4,11 +4,9 @@ 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 - // TODO(2.0): test & fix sync when we have iota2.0 nodes await wallet.sync({ ...DEFAULT_SYNC_OPTIONS }) const walletPersistedData = getActiveProfilePersistedWalletData(walletId) From 30802034cd08c8105fd8dda16e8449de1d13a819 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 10 Jan 2024 09:51:42 +0100 Subject: [PATCH 09/37] fmt --- packages/shared/lib/core/profile/actions/createWallet.ts | 4 ++-- .../core/profile/utils/getSecretManagerFromProfileType.ts | 2 +- .../shared/lib/core/wallet/actions/setStrongholdPassword.ts | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index 5fe14fc4eda..da26f4c33b7 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -5,7 +5,7 @@ import { WalletOptions } from '@iota/sdk' import { selectedWalletId } from '../../wallet' export function getWalletOptions(profile: IPersistedProfile, storagePath: string, address: string): WalletOptions { - return { + return { address, clientOptions: profile.clientOptions, storagePath, @@ -27,7 +27,7 @@ export function getWalletOptions(profile: IPersistedProfile, storagePath: string */ interface CreateWalletOptions { - profile: IPersistedProfile, + profile: IPersistedProfile address: string } diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts index cec897cb9c4..a728e0addfd 100644 --- a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts @@ -6,7 +6,7 @@ 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`} + stronghold: { snapshotPath: `${storagePath}/wallet.stronghold` }, } const ledgerSecretManager = { ledgerNano: USE_LEDGER_SIMULATOR, diff --git a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts index bcf751532dd..966c6fb466a 100644 --- a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts +++ b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts @@ -3,13 +3,13 @@ import { getSelectedWallet } from '../stores/selected-wallet.store' export async function setStrongholdPassword(password: string): Promise { // Set in Wallet - const wallet = getSelectedWallet(); + const wallet = getSelectedWallet() // Otherwise error is thrown, if password is still present in memory await wallet?.clearStrongholdPassword() await wallet?.setStrongholdPassword(password) // Set in SecretManager - const secretManager = getSecretManager(); - await secretManager.setStrongholdPassword(password); + const secretManager = getSecretManager() + await secretManager.setStrongholdPassword(password) // await secretManager?.clearStrongholdPassword() // TODO(2.0) } From cff2fa6afabfb757eb2e63247b1ace8be6d9178a Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 10 Jan 2024 20:04:52 +0100 Subject: [PATCH 10/37] more cleanup --- packages/desktop/electron/lib/nftDownloadHandlers.js | 6 +++--- .../helpers/convertOnboardingProfileToPersistedProfile.ts | 2 +- .../lib/core/app/actions/registerNftDownloadEvents.ts | 4 ++-- .../lib/core/app/interfaces/nft-download-state.interface.ts | 2 +- .../shared/lib/core/app/interfaces/platform.interface.ts | 2 +- .../profile/actions/active-profile/resetActiveProfile.ts | 4 ++-- .../profile/actions/active-profile/saveActiveProfile.ts | 3 ++- .../interfaces/chrysalis-persisted-profile.interface.ts | 2 +- .../core/profile/interfaces/persisted-profile.interface.ts | 2 +- 9 files changed, 14 insertions(+), 13 deletions(-) diff --git a/packages/desktop/electron/lib/nftDownloadHandlers.js b/packages/desktop/electron/lib/nftDownloadHandlers.js index 4c735beef55..73c32d33479 100644 --- a/packages/desktop/electron/lib/nftDownloadHandlers.js +++ b/packages/desktop/electron/lib/nftDownloadHandlers.js @@ -8,7 +8,7 @@ const downloadItems = {} export function initNftDownloadHandlers() { ipcMain.removeHandler('nft-download') - ipcMain.handle('nft-download', async (event, url, destination, nftId, accountIndex) => { + ipcMain.handle('nft-download', async (event, url, destination, nftId, walletId) => { const userPath = app.getPath('userData') const directory = app.isPackaged ? userPath : __dirname @@ -20,11 +20,11 @@ export function initNftDownloadHandlers() { showProgressBar: true, onCompleted: () => { delete downloadItems[nftId] - getOrInitWindow('main').webContents.send('nft-download-done', { nftId, accountIndex }) + getOrInitWindow('main').webContents.send('nft-download-done', { nftId, walletId }) }, onCancel: () => { delete downloadItems[nftId] - getOrInitWindow('main').webContents.send('nft-download-interrupted', { nftId, accountIndex }) + getOrInitWindow('main').webContents.send('nft-download-interrupted', { nftId, walletId }) }, onStarted: (item) => (downloadItems[nftId] = item), }) diff --git a/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts b/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts index 7c92b593ee2..72150efd8cb 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts @@ -23,7 +23,7 @@ export function convertOnboardingProfileToPersistedProfile( ...(onboardingProfile?.isDeveloperProfile && { isDeveloperProfile: onboardingProfile.isDeveloperProfile }), ...(onboardingProfile?.hasVisitedDashboard && { hasVisitedDashboard: onboardingProfile.hasVisitedDashboard }), ...(onboardingProfile?.lastUsedWalletId && { - lastUsedAccountIndex: onboardingProfile.lastUsedWalletId, + lastUsedWalletId: onboardingProfile.lastUsedWalletId, }), ...(onboardingProfile?.clientOptions && { clientOptions: onboardingProfile.clientOptions }), } diff --git a/packages/shared/lib/core/app/actions/registerNftDownloadEvents.ts b/packages/shared/lib/core/app/actions/registerNftDownloadEvents.ts index 4e337338435..97beecaa62a 100644 --- a/packages/shared/lib/core/app/actions/registerNftDownloadEvents.ts +++ b/packages/shared/lib/core/app/actions/registerNftDownloadEvents.ts @@ -5,8 +5,8 @@ import { Platform } from '../classes' * Registers all event handlers for nft downloads. */ export function registerNftDownloadEvents(): void { - Platform.onEvent('nft-download-done', ({ nftId, accountIndex }) => { - updateNftInAllWalletNfts(accountIndex, nftId, { downloadMetadata: { isLoaded: true } }) + Platform.onEvent('nft-download-done', ({ nftId, walletId }) => { + updateNftInAllWalletNfts(walletId, nftId, { downloadMetadata: { isLoaded: true } }) downloadingNftId.set(undefined) removeNftFromDownloadQueue(nftId) }) diff --git a/packages/shared/lib/core/app/interfaces/nft-download-state.interface.ts b/packages/shared/lib/core/app/interfaces/nft-download-state.interface.ts index b0352157a53..b5283264a34 100644 --- a/packages/shared/lib/core/app/interfaces/nft-download-state.interface.ts +++ b/packages/shared/lib/core/app/interfaces/nft-download-state.interface.ts @@ -1,5 +1,5 @@ export type INFTDownloadState = { nftId: string - accountIndex: number + walletId: string state: string } diff --git a/packages/shared/lib/core/app/interfaces/platform.interface.ts b/packages/shared/lib/core/app/interfaces/platform.interface.ts index 7afcb4cd86e..c60a7cf364e 100644 --- a/packages/shared/lib/core/app/interfaces/platform.interface.ts +++ b/packages/shared/lib/core/app/interfaces/platform.interface.ts @@ -30,7 +30,7 @@ export interface IPlatform { openUrl(url: string): void copyFile(sourceFilePath: string, destinationFilePath: string): Promise deleteFile(filePath: string): Promise - downloadNft(url: string, destinationFilePath: string, nftId: string, accountIndex: number): Promise + downloadNft(url: string, destinationFilePath: string, nftId: string, walletId: number): Promise cancelNftDownload(nftId: string): Promise checkIfFileExists(filePath: string): Promise diff --git a/packages/shared/lib/core/profile/actions/active-profile/resetActiveProfile.ts b/packages/shared/lib/core/profile/actions/active-profile/resetActiveProfile.ts index 941af5cb950..e0206f7b4ab 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/resetActiveProfile.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/resetActiveProfile.ts @@ -3,8 +3,8 @@ import { Platform } from '@core/app' import { get } from 'svelte/store' export function resetActiveProfile(): void { - const { lastUsedAccountIndex } = get(activeProfile) - activeProfile.set({ ...INITIAL_ACTIVE_PROFILE, lastUsedAccountIndex }) + const { lastUsedWalletId } = get(activeProfile) + activeProfile.set({ ...INITIAL_ACTIVE_PROFILE, lastUsedWalletId }) activeProfileId.set(null) Platform.updateActiveProfile(null) } diff --git a/packages/shared/lib/core/profile/actions/active-profile/saveActiveProfile.ts b/packages/shared/lib/core/profile/actions/active-profile/saveActiveProfile.ts index 8de951500ed..1efeef06e78 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/saveActiveProfile.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/saveActiveProfile.ts @@ -16,9 +16,10 @@ export function saveActiveProfile(): void { isDeveloperProfile: _activeProfile.isDeveloperProfile, clientOptions: _activeProfile.clientOptions, forceAssetRefresh: _activeProfile.forceAssetRefresh, + secretManagerOptions: _activeProfile.secretManagerOptions, // TODO(2.0) This should be persisted, right? ...(_activeProfile.strongholdVersion && { strongholdVersion: _activeProfile.strongholdVersion }), ...(_activeProfile.hasVisitedDashboard && { hasVisitedDashboard: _activeProfile.hasVisitedDashboard }), - ...(_activeProfile.lastUsedAccountIndex && { lastUsedAccountIndex: _activeProfile.lastUsedAccountIndex }), + ...(_activeProfile.lastUsedWalletId && { lastUsedWalletId: _activeProfile.lastUsedWalletId }), ...(_activeProfile.walletPersistedData && { walletPersistedData: _activeProfile.walletPersistedData }), ...(_activeProfile.pfp && { pfp: _activeProfile.pfp }), } diff --git a/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts b/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts index 59b4aef39e7..a8ba0f29a73 100644 --- a/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts @@ -18,7 +18,7 @@ export interface IChrysalisPersistedProfile { hasVisitedStaking?: boolean lastShimmerPeriodVisitedStaking?: number lastAssemblyPeriodVisitedStaking?: number - lastUsedAccountId?: string + lastUsedAccountId?: string // TODO(2.0) Accounts are gone accounts?: IChrysalisProfileAccount[] stakingRewards?: ChrysalisAccountStakingRewards[] hasFinishedSingleAccountGuide?: boolean 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 6f21543b7e4..449ad80e48b 100644 --- a/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/persisted-profile.interface.ts @@ -20,7 +20,7 @@ export interface IPersistedProfile { hasVisitedDashboard?: boolean lastUsedWalletId?: string // Todo(2.0) Fix all usages of lastUsedAccountIndex clientOptions: ClientOptions - secretManagerOptions: SecretManagerType // TODO(2.0) This sould be gone. + secretManagerOptions: SecretManagerType forceAssetRefresh: boolean strongholdVersion?: StrongholdVersion needsChrysalisToStardustDbMigration?: boolean From 064d8c59e1080ad0ae7f1154cf0f8146fefca8be Mon Sep 17 00:00:00 2001 From: marc2332 Date: Thu, 11 Jan 2024 12:49:12 +0100 Subject: [PATCH 11/37] more cleanup --- .../UpdateStrongholdRouterView.svelte | 2 +- .../views/ChangePasswordView.svelte | 26 ++------------- ...vertOnboardingProfileToPersistedProfile.ts | 3 ++ .../changePasswordAndUnlockStronghold.ts | 9 +++--- .../actions/changeStrongholdPassword.ts | 4 +-- .../actions/clearStrongholdPassword.ts | 6 ++-- .../stores/secret-manager.store.ts | 32 ++++++++----------- 7 files changed, 29 insertions(+), 53 deletions(-) diff --git a/packages/desktop/views/update-stronghold/UpdateStrongholdRouterView.svelte b/packages/desktop/views/update-stronghold/UpdateStrongholdRouterView.svelte index 8b11cec7b44..7015e84c350 100644 --- a/packages/desktop/views/update-stronghold/UpdateStrongholdRouterView.svelte +++ b/packages/desktop/views/update-stronghold/UpdateStrongholdRouterView.svelte @@ -16,7 +16,7 @@ {:else if $updateStrongholdRoute === UpdateStrongholdRoute.ChangePassword} - + {:else if $updateStrongholdRoute === UpdateStrongholdRoute.SaveBackup} diff --git a/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte b/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte index 219111acb3c..8531c08d265 100644 --- a/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte +++ b/packages/desktop/views/update-stronghold/views/ChangePasswordView.svelte @@ -3,22 +3,18 @@ import { OnboardingLayout } from '@components' import { handleError } from '@core/error/handlers' import { localize } from '@core/i18n' - import { MAX_STRONGHOLD_PASSWORD_LENGTH, unlockStronghold } from '@core/profile' - import { activeProfile, updateActiveProfile } from '@core/profile/stores' + import { MAX_STRONGHOLD_PASSWORD_LENGTH, changePasswordAndUnlockStronghold, unlockStronghold } from '@core/profile' import { PASSWORD_REASON_MAP } from '@core/stronghold' import { Animation, Button, PasswordInput, Text, TextHint } from '@ui' import { HTMLButtonType, TextType } from '@ui/enums' - import { onMount } from 'svelte' import zxcvbn from 'zxcvbn' import { updateStrongholdRouter } from '../update-stronghold-router' import { TextHintVariant } from 'shared/components/enums' import { AnimationEnum } from '@auxiliary/animation' import { onboardingProfile, updateOnboardingProfile } from '@contexts/onboarding' - import { changeStrongholdPassword } from '@core/secret-manager' export let oldPassword: string export let newPassword: string - export let isRecovery: boolean let passwordError: string = '' let confirmPassword: string = '' @@ -63,7 +59,7 @@ if (isPasswordValid) { try { isSubmitBusy = true - await changeStrongholdPassword(oldPassword, newPassword) + await changePasswordAndUnlockStronghold(oldPassword, newPassword) if ($onboardingProfile) { updateOnboardingProfile({ strongholdPassword: newPassword }) } @@ -95,24 +91,6 @@ isSkipBusy = false } } - - onMount(async () => { - // TODO(2.0) Profile manager is gone - if (!isRecovery && !$profileManager) { - 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, - coinType, - clientOptions, - secretManager - ) - profileManager.set(manager) - } - }) diff --git a/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts b/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts index 72150efd8cb..1f3c7cdf6dd 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/convertOnboardingProfileToPersistedProfile.ts @@ -26,5 +26,8 @@ export function convertOnboardingProfileToPersistedProfile( lastUsedWalletId: onboardingProfile.lastUsedWalletId, }), ...(onboardingProfile?.clientOptions && { clientOptions: onboardingProfile.clientOptions }), + ...(onboardingProfile?.secretManagerOptions && { + secretManagerOptions: onboardingProfile.secretManagerOptions, + }), } } diff --git a/packages/shared/lib/core/profile/actions/changePasswordAndUnlockStronghold.ts b/packages/shared/lib/core/profile/actions/changePasswordAndUnlockStronghold.ts index 729fd9eefcd..79fb51d1c6a 100644 --- a/packages/shared/lib/core/profile/actions/changePasswordAndUnlockStronghold.ts +++ b/packages/shared/lib/core/profile/actions/changePasswordAndUnlockStronghold.ts @@ -1,11 +1,10 @@ -import { activeProfile, setTimeStrongholdLastUnlocked } from '@core/profile' +import { activeProfile, setTimeStrongholdLastUnlocked, unlockStronghold } from '@core/profile' import { get } from 'svelte/store' -import { clearStrongholdPassword, changeStrongholdPassword } from '@core/secret-manager' +import { changeStrongholdPassword } from '@core/secret-manager' export async function changePasswordAndUnlockStronghold(currentPassword: string, newPassword: string): Promise { - // Otherwise password persists in memory - await clearStrongholdPassword() - await changeStrongholdPassword(currentPassword, newPassword) + await unlockStronghold(currentPassword) + await changeStrongholdPassword(newPassword) const { isStrongholdLocked } = get(activeProfile) isStrongholdLocked.set(false) setTimeStrongholdLastUnlocked() diff --git a/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts b/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts index 53ee15073fb..b1ca6e7a45e 100644 --- a/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts +++ b/packages/shared/lib/core/secret-manager/actions/changeStrongholdPassword.ts @@ -1,7 +1,7 @@ import { get } from 'svelte/store' import { activeProfileSecretManager } from '../stores' -export async function changeStrongholdPassword(currentPassword: string, newPassword: string): Promise { +export async function changeStrongholdPassword(newPassword: string): Promise { const activeProfileSecretManagerInstance = get(activeProfileSecretManager) - await activeProfileSecretManagerInstance.changeStrongholdPassword(currentPassword, newPassword) + await activeProfileSecretManagerInstance?.changeStrongholdPassword(newPassword) } diff --git a/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts b/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts index 257aed16b20..150757654db 100644 --- a/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts +++ b/packages/shared/lib/core/secret-manager/actions/clearStrongholdPassword.ts @@ -1,7 +1,7 @@ import { get } from 'svelte/store' -import { activeProfileSecretManager as activeProfileSecretManagerStore } from '../stores' +import { activeProfileSecretManager } from '../stores' export async function clearStrongholdPassword(): Promise { - const activeProfileSecretManagerInstance = get(activeProfileSecretManagerStore) - await activeProfileSecretManagerInstance?.clearStrongholdPassword() + const secretManager = get(activeProfileSecretManager) + await secretManager?.clearStrongholdPassword() } 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 index 9c2269dbb78..1dff71095f0 100644 --- a/packages/shared/lib/core/secret-manager/stores/secret-manager.store.ts +++ b/packages/shared/lib/core/secret-manager/stores/secret-manager.store.ts @@ -1,22 +1,18 @@ import { api } from '@core/api' -import { activeProfile } from '@core/profile/stores' -import { SecretManager } from '@iota/sdk' -import { Readable, derived } from 'svelte/store' +import { activeProfile } from '@core/profile/stores/active-profile.store' +import { SecretManager, SecretManagerType } from '@iota/sdk' +import { writable } from 'svelte/store' -const activeProfileSecretManagerOptions = derived( - activeProfile, - ($activeProfile) => $activeProfile.secretManagerOptions -) +export const activeProfileSecretManager = writable(null) -export const activeProfileSecretManager: Readable = derived( - activeProfileSecretManagerOptions, - (activeProfileSecretManagerOptions, set) => { - if (activeProfileSecretManagerOptions) { - api.createSecretManager(activeProfileSecretManagerOptions).then((secretManager) => { - set(secretManager) - }) - } else { - set(null) - } +let oldSecretManagerOptions: SecretManagerType | null = null +activeProfile.subscribe((profile) => { + if (profile.secretManagerOptions && oldSecretManagerOptions !== profile.secretManagerOptions) { + api.createSecretManager(profile.secretManagerOptions).then((secretManager) => { + activeProfileSecretManager.set(secretManager) + }) + oldSecretManagerOptions = profile.secretManagerOptions + } else { + activeProfileSecretManager.set(null) } -) +}) From 10105c0ca7f10818871775c063af58fe7a35a383 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Fri, 12 Jan 2024 10:40:18 +0100 Subject: [PATCH 12/37] small tweaks --- packages/desktop/electron/main.js | 4 ++-- packages/desktop/webpack.config.ts | 1 + .../lib/core/network/constants/official-node-urls.constant.ts | 2 +- .../shared/lib/core/wallet/actions/setStrongholdPassword.ts | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/desktop/electron/main.js b/packages/desktop/electron/main.js index 5ff2993a8ec..9571a32ae00 100644 --- a/packages/desktop/electron/main.js +++ b/packages/desktop/electron/main.js @@ -178,7 +178,7 @@ if (app.isPackaged) { * Handles url navigation events */ const handleNavigation = (e, url) => { - if (url === 'http://localhost:8080/') { + if (url === 'http://localhost:3333/') { // if localhost would be opened on the build versions, we need to block it to prevent errors if (app.isPackaged) { e.preventDefault() @@ -244,7 +244,7 @@ function createWindow() { // Enable dev tools only in developer mode windows.main.webContents.openDevTools() - windows.main.loadURL('http://localhost:8080') + windows.main.loadURL('http://localhost:3333') } else { initAutoUpdate() diff --git a/packages/desktop/webpack.config.ts b/packages/desktop/webpack.config.ts index d5df36bc9b6..0bc00377978 100644 --- a/packages/desktop/webpack.config.ts +++ b/packages/desktop/webpack.config.ts @@ -233,6 +233,7 @@ const webpackConfig: Configuration[] = [ warnings: false, }, }, + port: 3333, }, }, { diff --git a/packages/shared/lib/core/network/constants/official-node-urls.constant.ts b/packages/shared/lib/core/network/constants/official-node-urls.constant.ts index f4674b99460..784c31cd33b 100644 --- a/packages/shared/lib/core/network/constants/official-node-urls.constant.ts +++ b/packages/shared/lib/core/network/constants/official-node-urls.constant.ts @@ -4,5 +4,5 @@ export const OFFICIAL_NODE_URLS: Readonly<{ [key in NetworkId]?: string[] }> = { [NetworkId.Iota]: ['https://api.stardust-mainnet.iotaledger.net', 'https://iota-node.tanglebay.com'], [NetworkId.IotaAlphanet]: ['https://api.iota-alphanet.iotaledger.net'], [NetworkId.Shimmer]: ['https://api.shimmer.network', 'https://shimmer-node.tanglebay.com'], - [NetworkId.Testnet]: ['https://api.testnet.shimmer.network'], + [NetworkId.Testnet]: ['http://localhost:8050'], } diff --git a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts index 966c6fb466a..0dd686984c4 100644 --- a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts +++ b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts @@ -10,6 +10,6 @@ export async function setStrongholdPassword(password: string): Promise { // Set in SecretManager const secretManager = getSecretManager() + await secretManager?.clearStrongholdPassword() await secretManager.setStrongholdPassword(password) - // await secretManager?.clearStrongholdPassword() // TODO(2.0) } From 38b7c9be64f4f67adb94e43b2958f9f05b453803 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 15 Jan 2024 18:06:02 +0100 Subject: [PATCH 13/37] more cleanup --- .../desktop/components/AccountActivity.svelte | 4 +-- .../components/popups/AddNodePopup.svelte | 4 +-- .../views/CollectiblesDetailsView.svelte | 4 +-- .../components/ActivityInformation.svelte | 4 +-- .../components/NftActivityDetails.svelte | 4 +-- .../shared/components/inputs/NftInput.svelte | 6 ++-- .../NftActivityTileContent.svelte | 4 +-- .../utils/getParticipationsForProposal.ts | 8 ++--- .../governance/utils/isVotingForProposal.ts | 6 ++-- .../utils/isVotingForSelectedProposal.ts | 4 +-- .../onboarding/actions/claimShimmerRewards.ts | 3 +- .../selected-account-vesting-outputs.store.ts | 31 ++++++++--------- .../core/app/interfaces/platform.interface.ts | 2 +- .../nfts/actions/addNftsToDownloadQueue.ts | 1 - .../nfts/actions/downloadNextNftInQueue.ts | 4 +-- ...Nfts.ts => getNftByIdFromAllWalletNfts.ts} | 2 +- .../shared/lib/core/nfts/actions/index.ts | 2 +- ...scribeToWalletApiEventsForActiveProfile.ts | 8 ++--- .../actions/generateEd25519Address.ts | 8 ++--- .../core/wallet/actions/activities/index.ts | 2 +- ...ts => setAsyncStatusOfWalletActivities.ts} | 2 +- .../core/wallet/actions/buildWalletState.ts | 11 +++--- .../events-handlers/handleNewOutputEvent.ts | 21 ++++++------ .../events-handlers/handleSpentOutputEvent.ts | 25 +++++++------- .../handleTransactionInclusionEvent.ts | 15 ++++---- .../handleTransactionProgressEvent.ts | 17 ++++++---- .../wallet/actions/getAddressesWithOutputs.ts | 32 ----------------- .../shared/lib/core/wallet/actions/index.ts | 1 - .../actions/subscribeToWalletApiEvents.ts | 1 - .../address-with-outputs.interface.ts | 6 ---- .../lib/core/wallet/interfaces/index.ts | 3 -- ...let-api-event-payload-wrapper.interface.ts | 21 ------------ .../interfaces/wallet-state.interface.ts | 5 ++- .../wallet/stores/hidden-activities.store.ts | 2 +- .../types/wallet-api-event-handler.type.ts | 4 +-- .../generateActivitiesFromBasicOutputs.ts | 2 +- .../core/wallet/utils/getDepositAddress.ts | 6 ---- .../shared/lib/core/wallet/utils/index.ts | 1 - .../utils/outputs/preprocessGroupedOutputs.ts | 14 ++++---- .../outputs/preprocessOutgoingTransaction.ts | 2 +- .../getDirectionFromOutgoingTransaction.ts | 14 ++++---- ...NonRemainderBasicOutputsFromTransaction.ts | 11 +++--- .../wallet/utils/validateWalletApiEvent.ts | 34 ++++--------------- packages/shared/locales/en.json | 1 - 44 files changed, 128 insertions(+), 234 deletions(-) rename packages/shared/lib/core/nfts/actions/{getNftByIdFromAllAccountNfts.ts => getNftByIdFromAllWalletNfts.ts} (66%) rename packages/shared/lib/core/wallet/actions/activities/{setAsyncStatusOfAccountActivities.ts => setAsyncStatusOfWalletActivities.ts} (96%) delete mode 100644 packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts delete mode 100644 packages/shared/lib/core/wallet/interfaces/address-with-outputs.interface.ts delete mode 100644 packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts delete mode 100644 packages/shared/lib/core/wallet/utils/getDepositAddress.ts diff --git a/packages/desktop/components/AccountActivity.svelte b/packages/desktop/components/AccountActivity.svelte index 9a55972a7da..7706d91ac7d 100644 --- a/packages/desktop/components/AccountActivity.svelte +++ b/packages/desktop/components/AccountActivity.svelte @@ -6,7 +6,7 @@ activitySearchTerm, queriedActivities, selectedWalletActivities, - setAsyncStatusOfAccountActivities, + setAsyncStatusOfWalletActivities, } from '@core/wallet' import { ActivityTile, Text, TextInput, TogglableButton, FontWeight } from '@ui' import { Filter } from '@components' @@ -21,7 +21,7 @@ $: if (searchActive && inputElement) inputElement.focus() $: searchValue = searchActive ? searchValue.toLowerCase() : '' - $: setAsyncStatusOfAccountActivities($time) + $: setAsyncStatusOfWalletActivities($time) $: if (searchActive && $selectedWalletActivities) { debounce(() => { $activitySearchTerm = searchValue diff --git a/packages/desktop/components/popups/AddNodePopup.svelte b/packages/desktop/components/popups/AddNodePopup.svelte index 3f469271971..223e5d14c95 100644 --- a/packages/desktop/components/popups/AddNodePopup.svelte +++ b/packages/desktop/components/popups/AddNodePopup.svelte @@ -6,7 +6,7 @@ import { closePopup } from '@auxiliary/popup' import { Platform } from '@core/app' import { activeWallets, activeProfile } from '@core/profile' - import { registerProposalsForAccounts } from '@contexts/governance' + import { registerProposalsForWallets } from '@contexts/governance' export let node: INode = structuredClone(EMPTY_NODE) export let isEditingNode: boolean = false @@ -33,7 +33,7 @@ } if (Platform.isFeatureFlagEnabled('governance')) { - await registerProposalsForAccounts({ node }, $activeWallets) + await registerProposalsForWallets({ node }, $activeWallets) } onSuccess() diff --git a/packages/desktop/views/dashboard/collectibles/views/CollectiblesDetailsView.svelte b/packages/desktop/views/dashboard/collectibles/views/CollectiblesDetailsView.svelte index 036581b12f8..48870a8b769 100644 --- a/packages/desktop/views/dashboard/collectibles/views/CollectiblesDetailsView.svelte +++ b/packages/desktop/views/dashboard/collectibles/views/CollectiblesDetailsView.svelte @@ -10,7 +10,7 @@ NftDownloadMetadata, allWalletNfts, convertAndFormatNftMetadata, - getNftByIdFromAllAccountNfts, + getNftByIdFromAllWalletNfts, selectedNftId, } from '@core/nfts' import { getBaseToken } from '@core/profile/actions' @@ -43,7 +43,7 @@ let modal: Modal const explorerUrl = getOfficialExplorerUrl($activeProfile?.network?.id) - const nft: INft = getNftByIdFromAllAccountNfts($selectedWalletId, $selectedNftId) + const nft: INft = getNftByIdFromAllWalletNfts($selectedWalletId, $selectedNftId) const { id, name, issuer, address, metadata, downloadMetadata, storageDeposit } = nft ?? {} const { standard, version, type, uri, description, issuerName, collectionName, attributes, soonaverseAttributes } = diff --git a/packages/shared/components/ActivityInformation.svelte b/packages/shared/components/ActivityInformation.svelte index c79db14e117..87f5a21a53b 100644 --- a/packages/shared/components/ActivityInformation.svelte +++ b/packages/shared/components/ActivityInformation.svelte @@ -13,7 +13,7 @@ } from 'shared/components' import { Tab } from 'shared/components/enums' import { ActivityType, Activity } from '@core/wallet' - import { getNftByIdFromAllAccountNfts } from '@core/nfts' + import { getNftByIdFromAllWalletNfts } from '@core/nfts' import { selectedWalletId } from '@core/wallet' export let activity: Activity @@ -23,7 +23,7 @@ $: { const storedNft = activity?.type === ActivityType.Nft - ? getNftByIdFromAllAccountNfts($selectedWalletId, activity?.nftId) + ? getNftByIdFromAllWalletNfts($selectedWalletId, activity?.nftId) : undefined hasMetadata = !!storedNft?.metadata } diff --git a/packages/shared/components/NftActivityDetails.svelte b/packages/shared/components/NftActivityDetails.svelte index f882232dff3..feb84f99887 100644 --- a/packages/shared/components/NftActivityDetails.svelte +++ b/packages/shared/components/NftActivityDetails.svelte @@ -3,7 +3,7 @@ import { selectedWalletId } from '@core/wallet/stores' import { time } from '@core/app' import { localize } from '@core/i18n' - import { getNftByIdFromAllAccountNfts, ownedNfts, selectedNftId } from '@core/nfts' + import { getNftByIdFromAllWalletNfts, ownedNfts, selectedNftId } from '@core/nfts' import { CollectiblesRoute, collectiblesRouter, DashboardRoute, dashboardRouter } from '@core/router' import { ActivityAsyncStatus, NftActivity } from '@core/wallet' import { getSubjectFromActivity } from '@core/wallet/utils/generateActivity/helper' @@ -22,7 +22,7 @@ export let activity: NftActivity - $: nft = getNftByIdFromAllAccountNfts($selectedWalletId, activity.nftId) + $: nft = getNftByIdFromAllWalletNfts($selectedWalletId, activity.nftId) $: nftIsOwned = $ownedNfts.some((nft) => nft.id === activity.nftId) $: isTimelocked = activity?.asyncData?.timelockDate > $time $: subject = getSubjectFromActivity(activity) diff --git a/packages/shared/components/inputs/NftInput.svelte b/packages/shared/components/inputs/NftInput.svelte index 066be8c650a..15067609178 100644 --- a/packages/shared/components/inputs/NftInput.svelte +++ b/packages/shared/components/inputs/NftInput.svelte @@ -1,7 +1,7 @@ diff --git a/packages/shared/lib/contexts/governance/utils/getParticipationsForProposal.ts b/packages/shared/lib/contexts/governance/utils/getParticipationsForProposal.ts index 6a5115442b2..d4fae484eac 100644 --- a/packages/shared/lib/contexts/governance/utils/getParticipationsForProposal.ts +++ b/packages/shared/lib/contexts/governance/utils/getParticipationsForProposal.ts @@ -1,14 +1,10 @@ import { get } from 'svelte/store' - import type { ParticipationOverview, TrackedParticipationOverview } from '@iota/sdk/out/types' - import { allParticipationOverviews } from '@contexts/governance/stores' import { selectedWalletId } from 'shared/lib/core/wallet' -export function getParticipationsForProposal( - proposalId: string, - walletId = get(selectedWalletId) -): { [outputId: string]: TrackedParticipationOverview } { +export function getParticipationsForProposal(proposalId: string): { [outputId: string]: TrackedParticipationOverview } { + const walletId = get(selectedWalletId) const overview: ParticipationOverview = get(allParticipationOverviews)[walletId] return overview?.participations?.[proposalId] } diff --git a/packages/shared/lib/contexts/governance/utils/isVotingForProposal.ts b/packages/shared/lib/contexts/governance/utils/isVotingForProposal.ts index 8c95e100a8f..90a0dd3639f 100644 --- a/packages/shared/lib/contexts/governance/utils/isVotingForProposal.ts +++ b/packages/shared/lib/contexts/governance/utils/isVotingForProposal.ts @@ -1,10 +1,8 @@ -import { get } from 'svelte/store' import type { TrackedParticipationOverview } from '@iota/sdk/out/types' import { getParticipationsForProposal } from './getParticipationsForProposal' -import { selectedWalletId } from '@core/wallet' -export function isVotingForProposal(proposalId: string, walletId = get(selectedWalletId)): boolean { - const participations = getParticipationsForProposal(proposalId, walletId) ?? {} +export function isVotingForProposal(proposalId: string): boolean { + const participations = getParticipationsForProposal(proposalId) ?? {} const participationOutputs: TrackedParticipationOverview[] = Object.values(participations) return participationOutputs.some((output) => output?.endMilestoneIndex === 0) } diff --git a/packages/shared/lib/contexts/governance/utils/isVotingForSelectedProposal.ts b/packages/shared/lib/contexts/governance/utils/isVotingForSelectedProposal.ts index e4b2fe69a0d..3f43703c71a 100644 --- a/packages/shared/lib/contexts/governance/utils/isVotingForSelectedProposal.ts +++ b/packages/shared/lib/contexts/governance/utils/isVotingForSelectedProposal.ts @@ -3,7 +3,7 @@ import { get } from 'svelte/store' import { selectedProposalId } from '../stores' import { isVotingForProposal } from './isVotingForProposal' -export function isVotingForSelectedProposal(accountIndex?: number): boolean { +export function isVotingForSelectedProposal(): boolean { const proposalId = get(selectedProposalId) - return isVotingForProposal(proposalId, accountIndex) + return isVotingForProposal(proposalId) } diff --git a/packages/shared/lib/contexts/onboarding/actions/claimShimmerRewards.ts b/packages/shared/lib/contexts/onboarding/actions/claimShimmerRewards.ts index ddcd4e08c2b..d0ecf9ff48d 100644 --- a/packages/shared/lib/contexts/onboarding/actions/claimShimmerRewards.ts +++ b/packages/shared/lib/contexts/onboarding/actions/claimShimmerRewards.ts @@ -7,7 +7,6 @@ import { NewTransactionType, NewTokenTransactionDetails, SubjectType, - getDepositAddress, } from '@core/wallet' import { logAndNotifyError } from '@core/error/actions' @@ -64,7 +63,7 @@ async function claimShimmerRewardsForShimmerClaimingAccounts( async function claimShimmerRewardsForShimmerClaimingAccount( shimmerClaimingAccount: IShimmerClaimingWallet ): Promise { - const recipientAddress = await getDepositAddress(shimmerClaimingAccount?.twinAccount) + const recipientAddress = await shimmerClaimingAccount?.twinAccount.address() const rawAmount = shimmerClaimingAccount?.unclaimedRewards const newTransactionDetails: NewTokenTransactionDetails = { diff --git a/packages/shared/lib/contexts/vesting/stores/selected-account-vesting-outputs.store.ts b/packages/shared/lib/contexts/vesting/stores/selected-account-vesting-outputs.store.ts index cb6165d12c4..3e0f604ca8f 100644 --- a/packages/shared/lib/contexts/vesting/stores/selected-account-vesting-outputs.store.ts +++ b/packages/shared/lib/contexts/vesting/stores/selected-account-vesting-outputs.store.ts @@ -3,27 +3,26 @@ import { Readable, derived } from 'svelte/store' import { AddressWithVestingOutputs } from '../interfaces' import { getVestingType, isVestingOutput, mapBasicOutputToVestingOutput, sortVestingOutputs } from '../utils' -// TODO(2.0) Fix this and all usages export const selectedWalletVestingOutputs: Readable = derived( selectedWallet, ($selectedWallet) => { - const addressesWithVestingOutputs = - $selectedWallet?.addressesWithOutputs?.filter((addressWithOutputs) => - addressWithOutputs.outputs?.find(isVestingOutput) - ) ?? [] - return addressesWithVestingOutputs.map((addressWithOutputs) => { - const outputs = addressWithOutputs.outputs - .filter(isVestingOutput) - .map(mapBasicOutputToVestingOutput) - .sort(sortVestingOutputs) - const type = getVestingType(outputs) - const lastOutput = outputs[outputs.length - 1] - return { - address: addressWithOutputs.address, + const vestingOutputs = $selectedWallet?.walletOutputs?.filter(isVestingOutput) ?? [] + const outputs = vestingOutputs + .filter(isVestingOutput) + .map(mapBasicOutputToVestingOutput) + .sort(sortVestingOutputs) + const type = getVestingType(outputs) + const lastOutput = outputs[outputs.length - 1] + const address = $selectedWallet?.depositAddress || '' + + // TODO(2.0) It would be better to not return an array but this way we don't need to refactor more code for now + return [ + { + address, outputs, type, lastOutput, - } - }) + }, + ] } ) diff --git a/packages/shared/lib/core/app/interfaces/platform.interface.ts b/packages/shared/lib/core/app/interfaces/platform.interface.ts index c60a7cf364e..3aa18a63bc7 100644 --- a/packages/shared/lib/core/app/interfaces/platform.interface.ts +++ b/packages/shared/lib/core/app/interfaces/platform.interface.ts @@ -30,7 +30,7 @@ export interface IPlatform { openUrl(url: string): void copyFile(sourceFilePath: string, destinationFilePath: string): Promise deleteFile(filePath: string): Promise - downloadNft(url: string, destinationFilePath: string, nftId: string, walletId: number): Promise + downloadNft(url: string, destinationFilePath: string, nftId: string, walletId: string): Promise cancelNftDownload(nftId: string): Promise checkIfFileExists(filePath: string): Promise diff --git a/packages/shared/lib/core/nfts/actions/addNftsToDownloadQueue.ts b/packages/shared/lib/core/nfts/actions/addNftsToDownloadQueue.ts index 1a458670c07..2f85d798362 100644 --- a/packages/shared/lib/core/nfts/actions/addNftsToDownloadQueue.ts +++ b/packages/shared/lib/core/nfts/actions/addNftsToDownloadQueue.ts @@ -3,7 +3,6 @@ import { INft } from '../interfaces' import { addNftToDownloadQueue } from '../stores' import { checkIfNftShouldBeDownloaded } from '../utils/checkIfNftShouldBeDownloaded' -// TODO(2.0) Use wallets instead of acounts export function addNftsToDownloadQueue(walletId: string, nfts: INft[], forceDownload: boolean = true): void { for (const nft of nfts) { const shouldNotDownloadNft = diff --git a/packages/shared/lib/core/nfts/actions/downloadNextNftInQueue.ts b/packages/shared/lib/core/nfts/actions/downloadNextNftInQueue.ts index e67fa150a36..e75cbc65c1b 100644 --- a/packages/shared/lib/core/nfts/actions/downloadNextNftInQueue.ts +++ b/packages/shared/lib/core/nfts/actions/downloadNextNftInQueue.ts @@ -9,9 +9,9 @@ export async function downloadNextNftInQueue(): Promise { } try { - const { downloadUrl, path, nft, accountIndex } = nextDownload + const { downloadUrl, path, nft, walletId } = nextDownload downloadingNftId.set(nft.id) - await Platform.downloadNft(downloadUrl, path, nft.id, accountIndex) + await Platform.downloadNft(downloadUrl, path, nft.id, walletId) } catch (error) { downloadingNftId.set(undefined) removeNftFromDownloadQueue(get(downloadingNftId)) diff --git a/packages/shared/lib/core/nfts/actions/getNftByIdFromAllAccountNfts.ts b/packages/shared/lib/core/nfts/actions/getNftByIdFromAllWalletNfts.ts similarity index 66% rename from packages/shared/lib/core/nfts/actions/getNftByIdFromAllAccountNfts.ts rename to packages/shared/lib/core/nfts/actions/getNftByIdFromAllWalletNfts.ts index f7a485cb0a2..3cedcbc1919 100644 --- a/packages/shared/lib/core/nfts/actions/getNftByIdFromAllAccountNfts.ts +++ b/packages/shared/lib/core/nfts/actions/getNftByIdFromAllWalletNfts.ts @@ -2,6 +2,6 @@ import { allWalletNfts } from '../stores' import { INft } from '../interfaces' import { get } from 'svelte/store' -export function getNftByIdFromAllAccountNfts(walletId: string, nftId: string): INft | undefined { +export function getNftByIdFromAllWalletNfts(walletId: string, nftId: string): INft | undefined { return get(allWalletNfts)[walletId]?.find((_nft) => _nft.id === nftId) } diff --git a/packages/shared/lib/core/nfts/actions/index.ts b/packages/shared/lib/core/nfts/actions/index.ts index 3ef50d9c896..c66c87fe323 100644 --- a/packages/shared/lib/core/nfts/actions/index.ts +++ b/packages/shared/lib/core/nfts/actions/index.ts @@ -1,7 +1,7 @@ export * from './addNftsToDownloadQueue' export * from './addOrUpdateNftInAllAccountNfts' export * from './downloadNextNftInQueue' -export * from './getNftByIdFromAllAccountNfts' +export * from './getNftByIdFromAllWalletNfts' export * from './interruptNftDownloadAfterTimeout' export * from './loadNftsForActiveProfile' export * from './setWalletNftsInAllWalletNfts' diff --git a/packages/shared/lib/core/profile/actions/active-profile/subscribeToWalletApiEventsForActiveProfile.ts b/packages/shared/lib/core/profile/actions/active-profile/subscribeToWalletApiEventsForActiveProfile.ts index 71672a3e8ff..f2e89702fcb 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/subscribeToWalletApiEventsForActiveProfile.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/subscribeToWalletApiEventsForActiveProfile.ts @@ -12,10 +12,10 @@ import { export function subscribeToWalletApiEventsForActiveProfile(): void { const wallet = getSelectedWallet() const eventMap: WalletApiEventMap = { - [WalletEventType.NewOutput]: handleNewOutputEvent, - [WalletEventType.SpentOutput]: handleSpentOutputEvent, - [WalletEventType.TransactionInclusion]: handleTransactionInclusionEvent, - [WalletEventType.TransactionProgress]: handleTransactionProgressEvent, + [WalletEventType.NewOutput]: handleNewOutputEvent(wallet.id), + [WalletEventType.SpentOutput]: handleSpentOutputEvent(wallet.id), + [WalletEventType.TransactionInclusion]: handleTransactionInclusionEvent(wallet.id), + [WalletEventType.TransactionProgress]: handleTransactionProgressEvent(wallet.id), } subscribeToWalletApiEvents({ eventMap, diff --git a/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts b/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts index cd0faecaba0..1716f4abfdf 100644 --- a/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts +++ b/packages/shared/lib/core/secret-manager/actions/generateEd25519Address.ts @@ -1,20 +1,18 @@ import { GenerateAddressOptions } from '@iota/sdk/out/types' -import { activeSecretManager } from '../stores' import { get } from 'svelte/store' +import { activeProfileSecretManager } from '../stores' -// TODO(2.0): Fix all usages export async function generateEd25519Address( - accountIndex: number, + accountIndex: number, // TODO(2.0) account indexes are gone options: GenerateAddressOptions, bech32Hrp: string ): Promise { - const secretManager = get(activeSecretManager) + const secretManager = get(activeProfileSecretManager) if (!secretManager) { return undefined } - // TODO(2.0) Ledger secret manager doesn't support this return ( await secretManager.generateEd25519Addresses({ accountIndex, diff --git a/packages/shared/lib/core/wallet/actions/activities/index.ts b/packages/shared/lib/core/wallet/actions/activities/index.ts index b3f1619fafb..e84b983df7c 100644 --- a/packages/shared/lib/core/wallet/actions/activities/index.ts +++ b/packages/shared/lib/core/wallet/actions/activities/index.ts @@ -5,5 +5,5 @@ export * from './hideActivitiesForHiddenAssets' export * from './preprocessOutputsForWallet' export * from './preprocessTransactionsForWallet' export * from './loadAssetsForAllWallets' -export * from './setAsyncStatusOfAccountActivities' +export * from './setAsyncStatusOfWalletActivities' export * from './updateClaimingTransactionInclusion' diff --git a/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts b/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfWalletActivities.ts similarity index 96% rename from packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts rename to packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfWalletActivities.ts index e60a9520ad6..78e0dc12dd0 100644 --- a/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfAccountActivities.ts +++ b/packages/shared/lib/core/wallet/actions/activities/setAsyncStatusOfWalletActivities.ts @@ -5,7 +5,7 @@ import { allWalletActivities } from '../../stores' import { refreshWalletAssetsForActiveProfile } from '../refreshWalletAssetsForActiveProfile' import { getAsyncStatus } from '@core/wallet/utils/generateActivity/helper' -export function setAsyncStatusOfAccountActivities(time: Date): void { +export function setAsyncStatusOfWalletActivities(time: Date): void { const balancesToUpdate: string[] = [] allWalletActivities.update((state) => { Object.entries(state).forEach(([walletId, walletActivies]) => { diff --git a/packages/shared/lib/core/wallet/actions/buildWalletState.ts b/packages/shared/lib/core/wallet/actions/buildWalletState.ts index a4bc04f2c88..ea1ed05eb98 100644 --- a/packages/shared/lib/core/wallet/actions/buildWalletState.ts +++ b/packages/shared/lib/core/wallet/actions/buildWalletState.ts @@ -1,9 +1,7 @@ -import { Balance } from '@iota/sdk/out/types' +import { Balance, OutputData } from '@iota/sdk/out/types' import { IPersistedWalletData } from '../interfaces/persisted-wallet-data.interface' import { IWalletState } from '../interfaces/wallet-state.interface' import { IWallet } from '@core/profile/interfaces' -import { getAddressesWithOutputs } from './getAddressesWithOutputs' -import { getDepositAddress } from '../utils' export async function buildWalletState( wallet: IWallet, @@ -32,15 +30,16 @@ export async function buildWalletState( let depositAddress = '' let votingPower = '' + let walletOutputs: OutputData[] = [] try { balances = await wallet.getBalance() - depositAddress = await getDepositAddress(wallet) + depositAddress = await wallet.address() votingPower = balances.baseCoin.votingPower + walletOutputs = await wallet.outputs() } catch (err) { console.error(err) } - const addressesWithOutputs = await getAddressesWithOutputs(wallet) return { ...wallet, @@ -52,6 +51,6 @@ export async function buildWalletState( hasConsolidatingOutputsTransactionInProgress: false, isTransferring: false, votingPower, - addressesWithOutputs, + walletOutputs, } as IWalletState } 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 b0a915954fb..0df70146a16 100644 --- a/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleNewOutputEvent.ts @@ -1,4 +1,4 @@ -import { Event, NewOutputWalletEvent, OutputType, WalletEventType } from '@iota/sdk/out/types' +import { NewOutputWalletEvent, OutputType, WalletEvent, WalletEventType } from '@iota/sdk/out/types' import { addNftsToDownloadQueue, addOrUpdateNftInAllAccountNfts, buildNftFromNftOutput } from '@core/nfts' import { checkAndRemoveProfilePicture } from '@core/profile/actions' @@ -9,21 +9,22 @@ import { generateActivities, getOrRequestAssetFromPersistedAssets, allWalletActivities, - getAddressesWithOutputs, syncBalance, validateWalletApiEvent, getBech32AddressFromAddressTypes, preprocessGroupedOutputs, addActivitiesToWalletActivitiesInAllWalletActivities, + WalletApiEventHandler, } from '@core/wallet' import { get } from 'svelte/store' import { activeWallets, updateActiveWallet } from '@core/profile' -export function handleNewOutputEvent(error: Error, rawEvent: Event): void { - const { walletId, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.NewOutput) - const type = payload.type - if (type === WalletEventType.NewOutput) { - void handleNewOutputEventInternal(walletId, payload as NewOutputWalletEvent) +export function handleNewOutputEvent(walletId: string): WalletApiEventHandler { + return (error: Error, rawEvent: WalletEvent) => { + validateWalletApiEvent(error, rawEvent, WalletEventType.NewOutput) + if (rawEvent.type === WalletEventType.NewOutput) { + void handleNewOutputEventInternal(walletId, rawEvent as NewOutputWalletEvent) + } } } @@ -44,10 +45,10 @@ export async function handleNewOutputEventInternal(walletId: string, payload: Ne if ((wallet?.depositAddress === address && !outputData?.remainder) || isNewAliasOutput) { await syncBalance(wallet.id) - const addressesWithOutputs = await getAddressesWithOutputs(wallet) - updateActiveWallet(wallet.id, { addressesWithOutputs }) + const walletOutputs = await wallet.outputs() + updateActiveWallet(wallet.id, { walletOutputs }) - const processedOutput = preprocessGroupedOutputs([outputData], payload?.transactionInputs ?? [], account) + const processedOutput = preprocessGroupedOutputs([outputData], payload?.transactionInputs ?? [], wallet) const activities = await generateActivities(processedOutput, wallet) for (const activity of activities) { 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 5c1529eed1c..e2e554806c1 100644 --- a/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleSpentOutputEvent.ts @@ -1,8 +1,6 @@ -// TODO(2.0) Fix all of events code, blocked by https://github.com/iotaledger/iota-sdk/issues/1708 +import { SpentOutputWalletEvent, WalletEvent, WalletEventType } from '@iota/sdk/out/types' -import { Event, SpentOutputWalletEvent, WalletEventType } from '@iota/sdk/out/types' - -import { getNftByIdFromAllAccountNfts, updateNftInAllWalletNfts } from '@core/nfts' +import { getNftByIdFromAllWalletNfts, updateNftInAllWalletNfts } from '@core/nfts' import { syncBalance, ActivityAsyncStatus, @@ -10,15 +8,17 @@ import { validateWalletApiEvent, updateAsyncDataByTransactionId, allWalletActivities, + WalletApiEventHandler, } from '@core/wallet' import { get } from 'svelte/store' import { activeWallets, updateActiveWallet } from '@core/profile' -export async function handleSpentOutputEvent(error: Error, rawEvent: Event): Promise { - const { walletId, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.SpentOutput) - const type = payload.type - if (type === WalletEventType.SpentOutput) { - await handleSpentOutputEventInternal(walletId, payload as SpentOutputWalletEvent) +export function handleSpentOutputEvent(walletId: string): WalletApiEventHandler { + return async (error: Error, rawEvent: WalletEvent) => { + validateWalletApiEvent(error, rawEvent, WalletEventType.SpentOutput) + if (rawEvent.type === WalletEventType.SpentOutput) { + await handleSpentOutputEventInternal(walletId, rawEvent as SpentOutputWalletEvent) + } } } @@ -28,9 +28,8 @@ export async function handleSpentOutputEventInternal(walletId: string, payload: const output = payload.output await syncBalance(walletId) if (wallet) { - // TODO(2.0) Fix getAddressesWithOutputs is missing - const addressesWithOutputs = await getAddressesWithOutputs(wallet) - updateActiveWallet(walletId, { addressesWithOutputs }) + const walletOutputs = await wallet.outputs() + updateActiveWallet(walletId, { walletOutputs }) } const outputId = output?.outputId const activity = get(allWalletActivities)?.[walletId]?.find((_activity) => _activity.outputId === outputId) @@ -43,7 +42,7 @@ export async function handleSpentOutputEventInternal(walletId: string, payload: } if (activity?.type === ActivityType.Nft) { - const previousOutputId = getNftByIdFromAllAccountNfts(walletId, activity.nftId)?.latestOutputId + const previousOutputId = getNftByIdFromAllWalletNfts(walletId, activity.nftId)?.latestOutputId const previousOutput = await wallet.getOutput(previousOutputId) if (output.metadata.milestoneTimestampBooked > previousOutput.metadata.milestoneTimestampBooked) { updateNftInAllWalletNfts(walletId, activity.nftId, { isSpendable: false }) diff --git a/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts index 96fb69ed7b3..12731d67125 100644 --- a/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionInclusionEvent.ts @@ -1,5 +1,5 @@ import { closePopup, openPopup, PopupId } from '@auxiliary/popup' -import { Event, TransactionInclusionWalletEvent, WalletEventType } from '@iota/sdk/out/types' +import { TransactionInclusionWalletEvent, WalletEvent, WalletEventType } from '@iota/sdk/out/types' import { updateParticipationOverview } from '@contexts/governance/stores' import { isWalletVoting } from 'shared/lib/contexts/governance/utils/isWalletVoting' @@ -16,15 +16,18 @@ import { ActivityType, GovernanceActivity, InclusionState, + WalletApiEventHandler, } from '@core/wallet' import { get } from 'svelte/store' import { activeWallets, updateActiveWallet } from 'shared/lib/core/profile' -export function handleTransactionInclusionEvent(error: Error, rawEvent: Event): void { - const { walletId, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.TransactionInclusion) - const type = payload?.type - if (type === WalletEventType.TransactionInclusion) { - handleTransactionInclusionEventInternal(walletId, payload as TransactionInclusionWalletEvent) +export function handleTransactionInclusionEvent(walletId: string): WalletApiEventHandler { + return (error: Error, rawEvent: WalletEvent) => { + validateWalletApiEvent(error, rawEvent, WalletEventType.TransactionInclusion) + const type = rawEvent?.type + if (type === WalletEventType.TransactionInclusion) { + handleTransactionInclusionEventInternal(walletId, rawEvent as TransactionInclusionWalletEvent) + } } } diff --git a/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts index 5f3a45954ad..70748760665 100644 --- a/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts +++ b/packages/shared/lib/core/wallet/actions/events-handlers/handleTransactionProgressEvent.ts @@ -1,11 +1,11 @@ import { get } from 'svelte/store' import { - Event, TransactionProgressWalletEvent, PreparedTransactionSigningHashProgress, WalletEventType, TransactionProgressType, TransactionProgress, + WalletEvent, } from '@iota/sdk/out/types' import { ledgerNanoStatus } from '@core/ledger' @@ -16,13 +16,16 @@ import { deconstructLedgerVerificationProps } from '@core/ledger/helpers' import { validateWalletApiEvent } from '../../utils' import { selectedWalletId } from '../../stores' import { MissingTransactionProgressEventPayloadError } from '../../errors' +import { WalletApiEventHandler } from '../../types' -export function handleTransactionProgressEvent(error: Error, rawEvent: Event): void { - const { walletId, payload } = validateWalletApiEvent(error, rawEvent, WalletEventType.TransactionProgress) - const type = payload.type - if (type === WalletEventType.TransactionProgress) { - const progress = (payload as TransactionProgressWalletEvent).progress - handleTransactionProgressEventInternal(walletId, progress) +export function handleTransactionProgressEvent(walletId: string): WalletApiEventHandler { + return (error: Error, rawEvent: WalletEvent) => { + validateWalletApiEvent(error, rawEvent, WalletEventType.TransactionProgress) + const type = rawEvent.type + if (type === WalletEventType.TransactionProgress) { + const progress = (rawEvent as TransactionProgressWalletEvent).progress + handleTransactionProgressEventInternal(walletId, progress) + } } } diff --git a/packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts b/packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts deleted file mode 100644 index e048abeb141..00000000000 --- a/packages/shared/lib/core/wallet/actions/getAddressesWithOutputs.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { AddressWithOutputs } from '@core/wallet' - -// TODO(2.0) Fix all usages -export function getAddressesWithOutputs(/* wallet: IWallet | IWalletState*/): Promise { - const addressesWithOutputs: AddressWithOutputs[] = [] - // TODO (2.0): fix - return Promise.resolve(addressesWithOutputs) - - /* - const addresses: Address[] = [] // await account.accounts - const outputs = await wallet.outputs() - - const outputMapped: AddressWithOutputs[] = outputs.reduce((acc: AddressWithOutputs[], output) => { - const address = getBech32AddressFromAddressTypes(output.address) - const existingAddress = acc.find((a) => a.address === address) - if (!existingAddress) { - acc.push({ address, outputs: [output] }) - } else { - existingAddress.outputs.push(output) - } - return acc - }, []) - - addressesWithOutputs = addresses.map((address) => { - const existingAddress = outputMapped.find((a) => a.address === address.toString()) - if (!existingAddress) { - return { address: address.toString(), outputs: [] } - } - return existingAddress - }) - return addressesWithOutputs*/ -} diff --git a/packages/shared/lib/core/wallet/actions/index.ts b/packages/shared/lib/core/wallet/actions/index.ts index 1cad1843848..9dd2599bab2 100644 --- a/packages/shared/lib/core/wallet/actions/index.ts +++ b/packages/shared/lib/core/wallet/actions/index.ts @@ -30,7 +30,6 @@ export * from './getNodeInfo' export * from './setStrongholdPasswordClearInterval' export * from './startBackgroundSync' export * from './getParticipationOverview' -export * from './getAddressesWithOutputs' export * from './syncBalance' export * from './syncVotingPower' export * from './tryCreateAdditionalWallet' diff --git a/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts b/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts index a38f034870a..3d870564d52 100644 --- a/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts +++ b/packages/shared/lib/core/wallet/actions/subscribeToWalletApiEvents.ts @@ -1,7 +1,6 @@ import { IWalletApiEventSubscriptionConfiguration } from '../interfaces' import { getSelectedWallet } from '../stores' -// TODO(2.0): Fix all of usages of this export function subscribeToWalletApiEvents(configuration: IWalletApiEventSubscriptionConfiguration): void { const { eventMap, wallet } = configuration diff --git a/packages/shared/lib/core/wallet/interfaces/address-with-outputs.interface.ts b/packages/shared/lib/core/wallet/interfaces/address-with-outputs.interface.ts deleted file mode 100644 index 1e92eae8b0b..00000000000 --- a/packages/shared/lib/core/wallet/interfaces/address-with-outputs.interface.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { OutputData } from '@iota/sdk/out/types' - -export interface AddressWithOutputs { - address: string - outputs: OutputData[] -} diff --git a/packages/shared/lib/core/wallet/interfaces/index.ts b/packages/shared/lib/core/wallet/interfaces/index.ts index 772e40458d7..f570ea03b40 100644 --- a/packages/shared/lib/core/wallet/interfaces/index.ts +++ b/packages/shared/lib/core/wallet/interfaces/index.ts @@ -17,9 +17,6 @@ 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' export * from './wallet-state.interface' -export * from './address-with-outputs.interface' export * from './persisted-wallet-data.interface' -export * from './address-with-outputs.interface' 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 deleted file mode 100644 index fa52cab8478..00000000000 --- a/packages/shared/lib/core/wallet/interfaces/wallet-api-event-payload-wrapper.interface.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { - ConsolidationRequiredWalletEvent, - LedgerAddressGenerationWalletEvent, - NewOutputWalletEvent, - SpentOutputWalletEvent, - TransactionInclusionWalletEvent, - TransactionProgressWalletEvent, -} from '@iota/sdk/out/types' - -export interface IWalletApiEventPayloadWrapper { - walletId: string - payload: IWalletApiEventPayload -} - -export type IWalletApiEventPayload = - | ConsolidationRequiredWalletEvent - | LedgerAddressGenerationWalletEvent - | NewOutputWalletEvent - | SpentOutputWalletEvent - | TransactionInclusionWalletEvent - | TransactionProgressWalletEvent diff --git a/packages/shared/lib/core/wallet/interfaces/wallet-state.interface.ts b/packages/shared/lib/core/wallet/interfaces/wallet-state.interface.ts index 72d5f977636..59ebea40e49 100644 --- a/packages/shared/lib/core/wallet/interfaces/wallet-state.interface.ts +++ b/packages/shared/lib/core/wallet/interfaces/wallet-state.interface.ts @@ -1,6 +1,5 @@ -import { Balance } from '@iota/sdk/out/types' +import { Balance, OutputData } from '@iota/sdk/out/types' import { IWallet } from '@core/profile/interfaces' -import { AddressWithOutputs } from './address-with-outputs.interface' import { IPersistedWalletData } from './persisted-wallet-data.interface' export interface IWalletState extends IWallet, IPersistedWalletData { @@ -12,5 +11,5 @@ export interface IWalletState extends IWallet, IPersistedWalletData { hasVotingTransactionInProgress: boolean hasConsolidatingOutputsTransactionInProgress: boolean votingPower: string - addressesWithOutputs: AddressWithOutputs[] + walletOutputs: OutputData[] } diff --git a/packages/shared/lib/core/wallet/stores/hidden-activities.store.ts b/packages/shared/lib/core/wallet/stores/hidden-activities.store.ts index baf33d3efa1..28a5cd50368 100644 --- a/packages/shared/lib/core/wallet/stores/hidden-activities.store.ts +++ b/packages/shared/lib/core/wallet/stores/hidden-activities.store.ts @@ -12,7 +12,7 @@ export function isActivityHiddenForWalletId(walletId: string, activityId: string return activities ? activities.includes(activityId) : false } -export function removeActivityFromHiddenActivities(walletId: number, activityId: string): void { +export function removeActivityFromHiddenActivities(walletId: string, activityId: string): void { const activities = get(hiddenActivities)?.[get(activeProfileId)]?.[walletId] if (activities) { hiddenActivities.update((state) => { diff --git a/packages/shared/lib/core/wallet/types/wallet-api-event-handler.type.ts b/packages/shared/lib/core/wallet/types/wallet-api-event-handler.type.ts index 79ae46bd2ee..6255986c0ee 100644 --- a/packages/shared/lib/core/wallet/types/wallet-api-event-handler.type.ts +++ b/packages/shared/lib/core/wallet/types/wallet-api-event-handler.type.ts @@ -1,3 +1,3 @@ -import { Event } from '@iota/sdk/out/types' +import { WalletEvent } from '@iota/sdk/out/types' -export type WalletApiEventHandler = (error: Error, rawEvent: Event) => void | Promise +export type WalletApiEventHandler = (error: Error, rawEvent: WalletEvent) => void | Promise diff --git a/packages/shared/lib/core/wallet/utils/generateActivity/generateActivitiesFromBasicOutputs.ts b/packages/shared/lib/core/wallet/utils/generateActivity/generateActivitiesFromBasicOutputs.ts index f53b81b773f..9ac07e5e2a4 100644 --- a/packages/shared/lib/core/wallet/utils/generateActivity/generateActivitiesFromBasicOutputs.ts +++ b/packages/shared/lib/core/wallet/utils/generateActivity/generateActivitiesFromBasicOutputs.ts @@ -22,7 +22,7 @@ export async function generateActivitiesFromBasicOutputs( const basicOutputs = getNonRemainderBasicOutputsFromTransaction( processedTransaction.outputs, - account.addressesWithOutputs, + account.depositAddress, processedTransaction.direction ) const burnedNftInputs = getBurnedNftInputs(processedTransaction) diff --git a/packages/shared/lib/core/wallet/utils/getDepositAddress.ts b/packages/shared/lib/core/wallet/utils/getDepositAddress.ts deleted file mode 100644 index 098131ea251..00000000000 --- a/packages/shared/lib/core/wallet/utils/getDepositAddress.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { IWallet } from '@core/profile/interfaces' - -// TODO(2.0) Fix all usages -export function getDepositAddress(wallet: IWallet): Promise { - return wallet.address() -} diff --git a/packages/shared/lib/core/wallet/utils/index.ts b/packages/shared/lib/core/wallet/utils/index.ts index b8d9882fbad..498a8212a52 100644 --- a/packages/shared/lib/core/wallet/utils/index.ts +++ b/packages/shared/lib/core/wallet/utils/index.ts @@ -28,7 +28,6 @@ export * from './validateTokenAmount' export * from './validateWalletApiEvent' export * from './sumBalanceForWallets' export * from './sumTotalFromOutputs' -export * from './getDepositAddress' export * from './getBoundWallet' export * from './getRandomWalletColor' export * from './getIconColorFromString' diff --git a/packages/shared/lib/core/wallet/utils/outputs/preprocessGroupedOutputs.ts b/packages/shared/lib/core/wallet/utils/outputs/preprocessGroupedOutputs.ts index 2866f8e2f07..8cfc13c8e0f 100644 --- a/packages/shared/lib/core/wallet/utils/outputs/preprocessGroupedOutputs.ts +++ b/packages/shared/lib/core/wallet/utils/outputs/preprocessGroupedOutputs.ts @@ -1,6 +1,6 @@ import { CommonOutput, OutputData, OutputResponse, OutputType, UTXOInput } from '@iota/sdk/out/types' import { MILLISECONDS_PER_SECOND } from '@core/utils/constants' -import { AddressWithOutputs, IWalletState } from '@core/wallet/interfaces' +import { IWalletState } from '@core/wallet/interfaces' import { InclusionState, ActivityDirection } from '../../enums' import { IProcessedTransaction, IWrappedOutput } from '../../interfaces' import { getRecipientAddressFromOutput } from './getRecipientAddressFromOutput' @@ -11,7 +11,7 @@ import { getOutputIdFromTransactionIdAndIndex } from './getOutputIdFromTransacti export function preprocessGroupedOutputs( outputDatas: OutputData[], transactionInputs: OutputResponse[], - account: IWalletState + wallet: IWalletState ): IProcessedTransaction { const transactionMetadata = outputDatas[0]?.metadata const wrappedInputs = convertTransactionOutputResponsesToWrappedOutputs( @@ -19,10 +19,11 @@ export function preprocessGroupedOutputs( transactionInputs ) const utxoInputs = getUtxoInputsFromWrappedInputs(wrappedInputs) - const direction = getDirectionForOutputs(outputDatas, wrappedInputs, account.addressesWithOutputs) + const direction = getDirectionForOutputs(outputDatas, wrappedInputs, wallet.depositAddress) const wrappedOutputs = outputDatas.map((outputData) => ({ outputId: outputData.outputId, remainder: outputData.remainder, + // TODO(2.0) Treasure variant is gone output: outputData.output.type !== OutputType.Treasury ? outputData.output : undefined, })) @@ -41,7 +42,7 @@ export function preprocessGroupedOutputs( function getDirectionForOutputs( outputs: OutputData[], wrappedInputs: IWrappedOutput[], - accountAddressesWithOutputs: AddressWithOutputs[] + depositAddress: string ): ActivityDirection { const nonRemainderOutputs = outputs.filter((output) => !output.remainder) if (nonRemainderOutputs.length === 0) { @@ -49,11 +50,10 @@ function getDirectionForOutputs( } const output = nonRemainderOutputs[0].output.type !== OutputType.Treasury ? nonRemainderOutputs[0].output : undefined - const accountAddresses = accountAddressesWithOutputs.map((addressWithOutputs) => addressWithOutputs.address) const recipientAddress = output ? getRecipientAddressFromOutput(output as CommonOutput) : undefined const senderAddress = wrappedInputs ? getSenderAddressFromInputs(wrappedInputs) : '' - const isRecipientOneOfAccountAddresses = accountAddresses.includes(recipientAddress) - const isSenderOneOfAccountAddresses = accountAddresses.includes(senderAddress) + const isRecipientOneOfAccountAddresses = depositAddress === recipientAddress + const isSenderOneOfAccountAddresses = depositAddress === senderAddress const isSelfTransaction = isRecipientOneOfAccountAddresses && isSenderOneOfAccountAddresses if (isSelfTransaction) { diff --git a/packages/shared/lib/core/wallet/utils/outputs/preprocessOutgoingTransaction.ts b/packages/shared/lib/core/wallet/utils/outputs/preprocessOutgoingTransaction.ts index ee88a230cbe..16ed07f82b9 100644 --- a/packages/shared/lib/core/wallet/utils/outputs/preprocessOutgoingTransaction.ts +++ b/packages/shared/lib/core/wallet/utils/outputs/preprocessOutgoingTransaction.ts @@ -16,7 +16,7 @@ export async function preprocessOutgoingTransaction( regularTransactionEssence.outputs ) - const direction = getDirectionFromOutgoingTransaction(outputs, account.addressesWithOutputs) + const direction = getDirectionFromOutgoingTransaction(outputs, account.depositAddress) const utxoInputs = regularTransactionEssence.inputs.map((i) => i as UTXOInput) const inputIds = await Promise.all( utxoInputs.map((input) => { diff --git a/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts b/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts index d8941504c65..74a71a83cc1 100644 --- a/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts +++ b/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts @@ -1,20 +1,18 @@ -import { AddressWithOutputs, IWrappedOutput } from '../../interfaces' +import { IWrappedOutput } from '../../interfaces' import { getRecipientAddressFromOutput } from '../outputs/getRecipientAddressFromOutput' import { ActivityDirection } from '@core/wallet/enums' import { CommonOutput } from '@iota/sdk/out/types' -// TODO(2.0) Fix all usages export function getDirectionFromOutgoingTransaction( wrappedOutputs: IWrappedOutput[], - accountAddressesWithOutputs: AddressWithOutputs[] + walletDepositAddress: string ): ActivityDirection { - const accountAddresses = accountAddressesWithOutputs.map((addressWithOutputs) => addressWithOutputs.address) - // Check if any output is not destined for the account - const containsNonAccountRecipient = wrappedOutputs.some((outputData) => { + // Check if any output is not destined for the wallet + const containsNonWalletRecipient = wrappedOutputs.some((outputData) => { const outputRecipient = getRecipientAddressFromOutput(outputData.output as CommonOutput) - return !accountAddresses.includes(outputRecipient) + return walletDepositAddress !== outputRecipient }) // If there is any output not destined for the account, it's an outgoing transaction. - return containsNonAccountRecipient ? ActivityDirection.Outgoing : ActivityDirection.SelfTransaction + return containsNonWalletRecipient ? ActivityDirection.Outgoing : ActivityDirection.SelfTransaction } diff --git a/packages/shared/lib/core/wallet/utils/transactions/getNonRemainderBasicOutputsFromTransaction.ts b/packages/shared/lib/core/wallet/utils/transactions/getNonRemainderBasicOutputsFromTransaction.ts index a4f3006aac3..31ae0147492 100644 --- a/packages/shared/lib/core/wallet/utils/transactions/getNonRemainderBasicOutputsFromTransaction.ts +++ b/packages/shared/lib/core/wallet/utils/transactions/getNonRemainderBasicOutputsFromTransaction.ts @@ -1,23 +1,20 @@ import { getRecipientAddressFromOutput } from '..' -import { AddressWithOutputs, IWrappedOutput } from '@core/wallet/interfaces' +import { IWrappedOutput } from '@core/wallet/interfaces' import { ActivityDirection } from '@core/wallet/enums' import { CommonOutput } from '@iota/sdk/out/types' -// TODO(2.0) Fix all usages export function getNonRemainderBasicOutputsFromTransaction( wrappedOutputs: IWrappedOutput[], - accountAddressesWithOutputs: AddressWithOutputs[], + walletDepositAddress: string, direction: ActivityDirection ): IWrappedOutput[] { - const accountAddresses = accountAddressesWithOutputs.map((addressWithOutputs) => addressWithOutputs.address) - return wrappedOutputs.filter((outputData) => { const recipientAddress = getRecipientAddressFromOutput(outputData.output as CommonOutput) if (direction === ActivityDirection.Incoming || direction === ActivityDirection.SelfTransaction) { - return !outputData.remainder && accountAddresses.includes(recipientAddress) + return !outputData.remainder && walletDepositAddress === recipientAddress } else { - return !accountAddresses.includes(recipientAddress) + return walletDepositAddress !== recipientAddress } }) } diff --git a/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts b/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts index 343bc781176..70137d9aaa9 100644 --- a/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts +++ b/packages/shared/lib/core/wallet/utils/validateWalletApiEvent.ts @@ -1,37 +1,15 @@ import { localize } from '@core/i18n' -import { Event, WalletEventType } from '@iota/sdk/out/types' +import { WalletEvent, WalletEventType } from '@iota/sdk/out/types' import { WalletApiEventError, WalletApiEventValidationError } from '../errors' -import { IWalletApiEventPayloadWrapper } from '../interfaces' -export function validateWalletApiEvent( - error: Error, - rawEvent: Event, - apiEvent: WalletEventType -): IWalletApiEventPayloadWrapper { +export function validateWalletApiEvent(error: Error, rawEvent: WalletEvent, apiEvent: WalletEventType): void { if (error) { throw new WalletApiEventError(error) - } else { - /* eslint-disable-next-line prefer-const */ - const { walletId, event } = rawEvent - - if (Number.isNaN(walletId)) { - throw new WalletApiEventValidationError( - localize('error.walletApiEvent.invalidAccountIndex', { values: { eventName: apiEvent } }) - ) - } - - const payload = event.type === apiEvent ? event : undefined - if (!payload) { - throw new WalletApiEventValidationError( - localize('error.walletApiEvent.invalidPayload', { values: { eventName: apiEvent } }) - ) - } - - return { - accountIndex, - payload, - } + } else if (rawEvent?.type !== apiEvent) { + throw new WalletApiEventValidationError( + localize('error.walletApiEvent.invalidPayload', { values: { eventName: apiEvent } }) + ) } } diff --git a/packages/shared/locales/en.json b/packages/shared/locales/en.json index eba1207134d..b31fccb5db8 100644 --- a/packages/shared/locales/en.json +++ b/packages/shared/locales/en.json @@ -2046,7 +2046,6 @@ "missingAccount": "Unable to find Shimmer claiming account" }, "walletApiEvent": { - "invalidAccountIndex": "Invalid account index for {eventName} event", "invalidPayload": "Invalid payload for {eventName} event" }, "aliasMinting": { From 071bffcfc396ddd157884539007be793411f079b Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 15 Jan 2024 18:33:09 +0100 Subject: [PATCH 14/37] format --- packages/shared/lib/core/profile/actions/createWallet.ts | 4 ++-- .../core/profile/utils/getSecretManagerFromProfileType.ts | 2 +- .../shared/lib/core/wallet/actions/setStrongholdPassword.ts | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index 5fe14fc4eda..da26f4c33b7 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -5,7 +5,7 @@ import { WalletOptions } from '@iota/sdk' import { selectedWalletId } from '../../wallet' export function getWalletOptions(profile: IPersistedProfile, storagePath: string, address: string): WalletOptions { - return { + return { address, clientOptions: profile.clientOptions, storagePath, @@ -27,7 +27,7 @@ export function getWalletOptions(profile: IPersistedProfile, storagePath: string */ interface CreateWalletOptions { - profile: IPersistedProfile, + profile: IPersistedProfile address: string } diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts index cec897cb9c4..a728e0addfd 100644 --- a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts @@ -6,7 +6,7 @@ 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`} + stronghold: { snapshotPath: `${storagePath}/wallet.stronghold` }, } const ledgerSecretManager = { ledgerNano: USE_LEDGER_SIMULATOR, diff --git a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts index bcf751532dd..966c6fb466a 100644 --- a/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts +++ b/packages/shared/lib/core/wallet/actions/setStrongholdPassword.ts @@ -3,13 +3,13 @@ import { getSelectedWallet } from '../stores/selected-wallet.store' export async function setStrongholdPassword(password: string): Promise { // Set in Wallet - const wallet = getSelectedWallet(); + const wallet = getSelectedWallet() // Otherwise error is thrown, if password is still present in memory await wallet?.clearStrongholdPassword() await wallet?.setStrongholdPassword(password) // Set in SecretManager - const secretManager = getSecretManager(); - await secretManager.setStrongholdPassword(password); + const secretManager = getSecretManager() + await secretManager.setStrongholdPassword(password) // await secretManager?.clearStrongholdPassword() // TODO(2.0) } From 67eba8c64f7d4a3a9c6d0b0d028840a91da0bc9d Mon Sep 17 00:00:00 2001 From: marc2332 Date: Tue, 16 Jan 2024 12:53:08 +0100 Subject: [PATCH 15/37] update --- .../actions/completeOnboardingProcess.ts | 14 +++--------- .../onboarding-profile.interface.ts | 2 -- .../stores/onboarding-secret-manager.store.ts | 8 +------ .../lib/core/profile/actions/createWallet.ts | 22 ++++++------------- .../utils/getSecretManagerFromProfileType.ts | 8 +++++-- 5 files changed, 17 insertions(+), 37 deletions(-) diff --git a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts index a994830270a..8564649bbab 100644 --- a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts +++ b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts @@ -49,20 +49,12 @@ export async function initWallet(profile: IOnboardingProfile, strongholdPassword const walletName = `${localize('general.wallet')} ${(get(activeWallets)?.length ?? 0) + 1}` // 2. Create the wallet instance - const wallet = await createWallet({ - address: profile.address, - profile: profile as IPersistedProfile, - }) + const wallet = await createWallet(profile as IPersistedProfile, strongholdPassword) - // 3. Load the stronghold password if necessary - if (strongholdPassword) { - await wallet.setStrongholdPassword(strongholdPassword) - } - - // 4. Sync the wallet with the Node + // 3. Sync the wallet with the Node await wallet.sync(DEFAULT_SYNC_OPTIONS) - // 5. Create a wrapper over the wallet instance and the persisted data + // 4. Create a wrapper over the wallet instance and the persisted data const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName) addWalletToActiveWallets(walletState) 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 3406199ae69..21114cb2a84 100644 --- a/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts +++ b/packages/shared/lib/contexts/onboarding/interfaces/onboarding-profile.interface.ts @@ -28,6 +28,4 @@ export interface IOnboardingProfile extends Omit, 'id shimmerClaimingAccounts?: IShimmerClaimingWallet[] hasInitialisedProfileManager?: boolean - - address: string } 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 index a68330dc4f2..030a954323a 100644 --- a/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-secret-manager.store.ts @@ -1,4 +1,4 @@ -import { onboardingProfile, updateOnboardingProfile } from '@contexts/onboarding/stores' +import { onboardingProfile } from '@contexts/onboarding/stores' import { api } from '@core/api' import { SecretManager } from '@iota/sdk' import { verifyMnemonic } from 'shared/lib/core/secret-manager' @@ -30,12 +30,6 @@ export async function buildOnboardingSecretManager(): Promise { // 4. Store Mnemonic await secretManager.storeMnemonic(mnemonicStringified) - // 5. Generate address - const address = (await secretManager.generateEd25519Addresses({}))[0] - - updateOnboardingProfile({ - address, - }) onboardingProfileSecretManager.set(secretManager) } else { onboardingProfileSecretManager.set(null) diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index da26f4c33b7..216b381d7ec 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -4,12 +4,11 @@ import { getSecretManagerFromProfileType, getStorageDirectoryOfProfile } from '. import { WalletOptions } from '@iota/sdk' import { selectedWalletId } from '../../wallet' -export function getWalletOptions(profile: IPersistedProfile, storagePath: string, address: string): WalletOptions { +export function getWalletOptions(profile: IPersistedProfile, storagePath: string, password?: string): WalletOptions { return { - address, clientOptions: profile.clientOptions, storagePath, - secretManager: getSecretManagerFromProfileType(profile.type, storagePath), + secretManager: getSecretManagerFromProfileType(profile.type, storagePath, password), bipPath: { coinType: profile.network.coinType, account: 0, @@ -26,22 +25,15 @@ export function getWalletOptions(profile: IPersistedProfile, storagePath: string - __wallet2__/ */ -interface CreateWalletOptions { - profile: IPersistedProfile - address: string -} - -export async function createWallet({ profile, address }: CreateWalletOptions): Promise { - const { id } = profile - const storagePath = await getStorageDirectoryOfProfile(id) +export async function createWallet(profile: IPersistedProfile, password?: string): Promise { + const storagePath = await getStorageDirectoryOfProfile(profile.id) - const walletOptions = getWalletOptions(profile, storagePath, address) - const wallet = await api.createWallet(id, { + const walletOptions = getWalletOptions(profile, storagePath, password) + const wallet = await api.createWallet(profile.id, { ...walletOptions, storagePath, }) - // TODO(2.0): Fix - selectedWalletId.set(id) + selectedWalletId.set(profile.id) return wallet } diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts index a728e0addfd..c9c47370b57 100644 --- a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts @@ -4,9 +4,13 @@ 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 { +export function getSecretManagerFromProfileType( + type?: ProfileType, + storagePath?: string, + password?: string +): SecretManagerType { const strongholdSecretManager = { - stronghold: { snapshotPath: `${storagePath}/wallet.stronghold` }, + stronghold: { snapshotPath: `${storagePath}/wallet.stronghold`, password }, } const ledgerSecretManager = { ledgerNano: USE_LEDGER_SIMULATOR, From f8ba63f21a2d3ee4ef5ad562ed186056e93a625a Mon Sep 17 00:00:00 2001 From: marc2332 Date: Tue, 16 Jan 2024 13:30:37 +0100 Subject: [PATCH 16/37] clean up --- .../onboarding/stores/onboarding-profile.store.ts | 15 +-------------- .../lib/core/profile/actions/createWallet.ts | 2 ++ 2 files changed, 3 insertions(+), 14 deletions(-) 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 d22b27f5fec..747af7dee17 100644 --- a/packages/shared/lib/contexts/onboarding/stores/onboarding-profile.store.ts +++ b/packages/shared/lib/contexts/onboarding/stores/onboarding-profile.store.ts @@ -3,7 +3,7 @@ import { derived, get, Readable, writable } from 'svelte/store' import { isLedgerProfile } from '@core/profile' import { IOnboardingProfile, IShimmerClaimingWallet } from '../interfaces' -import { IBaseToken, IPersistedWalletData } from '@core/wallet/interfaces' +import { IBaseToken } from '@core/wallet/interfaces' import { IPersistedNetwork } from '@core/network' export const onboardingProfile = writable(null) @@ -40,16 +40,3 @@ export function updateShimmerClaimingAccount(shimmerClaimingAccount: IShimmerCla export function getOnboardingBaseToken(): IBaseToken { return get(onboardingProfile)?.network?.baseToken } - -export function addWalletPersistedDataToOnboardingProfile( - walletId: string, - walletPersistedData: IPersistedWalletData -): void { - onboardingProfile?.update((state) => { - if (!state?.walletPersistedData) { - state.walletPersistedData = {} - } - state.walletPersistedData[walletId] = walletPersistedData - return state - }) -} diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index 216b381d7ec..edfa49a60c4 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -29,6 +29,8 @@ export async function createWallet(profile: IPersistedProfile, password?: string const storagePath = await getStorageDirectoryOfProfile(profile.id) const walletOptions = getWalletOptions(profile, storagePath, password) + // TODO(2.0) It is weird to use the profile ID as the wallet ID, + // we should probably have one for wallet and another one for the profile const wallet = await api.createWallet(profile.id, { ...walletOptions, storagePath, From f5acc833e34d8e267dea2fe5810884a35e7b59ec Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 17 Jan 2024 10:14:27 +0100 Subject: [PATCH 17/37] https://api.testnet.shimmer.network --- packages/desktop/views/dashboard/wallet/Wallet.svelte | 2 +- .../lib/core/network/constants/official-node-urls.constant.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/desktop/views/dashboard/wallet/Wallet.svelte b/packages/desktop/views/dashboard/wallet/Wallet.svelte index 089879751f9..a72501b7f5d 100644 --- a/packages/desktop/views/dashboard/wallet/Wallet.svelte +++ b/packages/desktop/views/dashboard/wallet/Wallet.svelte @@ -2,7 +2,7 @@ import { selectedWallet } from '@core/wallet' import { ImplicitAccountCreationView, WalletView } from './views' - $: hasAccount = $selectedWallet.accountOutputs.length !== 0 + $: hasAccount = true // $selectedWallet.accountOutputs.length !== 0 {#if $selectedWallet} diff --git a/packages/shared/lib/core/network/constants/official-node-urls.constant.ts b/packages/shared/lib/core/network/constants/official-node-urls.constant.ts index 784c31cd33b..f4674b99460 100644 --- a/packages/shared/lib/core/network/constants/official-node-urls.constant.ts +++ b/packages/shared/lib/core/network/constants/official-node-urls.constant.ts @@ -4,5 +4,5 @@ export const OFFICIAL_NODE_URLS: Readonly<{ [key in NetworkId]?: string[] }> = { [NetworkId.Iota]: ['https://api.stardust-mainnet.iotaledger.net', 'https://iota-node.tanglebay.com'], [NetworkId.IotaAlphanet]: ['https://api.iota-alphanet.iotaledger.net'], [NetworkId.Shimmer]: ['https://api.shimmer.network', 'https://shimmer-node.tanglebay.com'], - [NetworkId.Testnet]: ['http://localhost:8050'], + [NetworkId.Testnet]: ['https://api.testnet.shimmer.network'], } From 84b875f64e8b2bd523d4d25173c3f77940796cdd Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 17 Jan 2024 10:31:01 +0100 Subject: [PATCH 18/37] revert Wallet.svelte --- packages/desktop/views/dashboard/wallet/Wallet.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/desktop/views/dashboard/wallet/Wallet.svelte b/packages/desktop/views/dashboard/wallet/Wallet.svelte index a72501b7f5d..089879751f9 100644 --- a/packages/desktop/views/dashboard/wallet/Wallet.svelte +++ b/packages/desktop/views/dashboard/wallet/Wallet.svelte @@ -2,7 +2,7 @@ import { selectedWallet } from '@core/wallet' import { ImplicitAccountCreationView, WalletView } from './views' - $: hasAccount = true // $selectedWallet.accountOutputs.length !== 0 + $: hasAccount = $selectedWallet.accountOutputs.length !== 0 {#if $selectedWallet} From 71e06b973f5d95fe88c428ed5b54451fa95b16c3 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 17 Jan 2024 10:32:45 +0100 Subject: [PATCH 19/37] clean up --- .../activities/linkTransactionsWithClaimingTransactions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/shared/lib/core/wallet/actions/activities/linkTransactionsWithClaimingTransactions.ts b/packages/shared/lib/core/wallet/actions/activities/linkTransactionsWithClaimingTransactions.ts index 49c8629a007..d55edcb912e 100644 --- a/packages/shared/lib/core/wallet/actions/activities/linkTransactionsWithClaimingTransactions.ts +++ b/packages/shared/lib/core/wallet/actions/activities/linkTransactionsWithClaimingTransactions.ts @@ -19,7 +19,7 @@ export function linkTransactionsWithClaimingTransactions( const resultingTransactions = [] const transactionsIncludedAsClaimingTransactions = [] - const claimedAccountActivities = get(claimedActivities)?.[get(activeProfileId)]?.[wallet.id] + const claimedWalletActivities = get(claimedActivities)?.[get(activeProfileId)]?.[wallet.id] const sortedTransactions = transactions.sort((t1, t2) => (t1.time > t2.time ? 1 : -1)) const incomingAsyncTransactions: IProcessedTransaction[] = [] for (const transaction of sortedTransactions) { @@ -33,7 +33,7 @@ export function linkTransactionsWithClaimingTransactions( continue } else if (isIncomingAsyncTransaction) { // If we have the corresponding claiming transaction cached in local storage, we get that data and update the async transaction - const claimedActivity = claimedAccountActivities?.[transaction?.transactionId] + const claimedActivity = claimedWalletActivities?.[transaction?.transactionId] if (claimedActivity && claimedActivity.claimingTransactionId === transaction?.transactionId) { const claimingData = { claimedDate: new Date(claimedActivity.claimedTimestamp), From 4cf63270ecbb186d51b55404df4e9aa7d4fc9cdf Mon Sep 17 00:00:00 2001 From: marc2332 Date: Thu, 18 Jan 2024 15:15:52 +0100 Subject: [PATCH 20/37] remove account debris --- ...tActivity.svelte => WalletActivity.svelte} | 0 ...untSummary.svelte => WalletSummary.svelte} | 8 ++--- ...tton.svelte => WalletActionsButton.svelte} | 4 +-- .../components/buttons/menu-buttons/index.js | 2 +- .../RefreshTokenMetadataButton.svelte | 4 +-- packages/desktop/components/index.js | 4 +-- .../components/modals/VestingModal.svelte | 4 +-- .../modals/WalletActionsMenu.svelte | 26 +++++++------- .../modals/WalletSwitcherModal.svelte | 12 +++---- .../components/popups/AddProposalPopup.svelte | 2 +- .../popups/BalanceBreakdownPopup.svelte | 14 ++++---- .../popups/BalanceFinderPopup.svelte | 24 ++++++------- .../popups/CreateWalletPopup.svelte | 34 +++++++++---------- ...tPopup.svelte => DeleteWalletPopup.svelte} | 14 ++++---- .../popups/ManageWalletPopup.svelte | 14 ++++---- .../desktop/components/popups/Popup.svelte | 4 +-- .../popups/VestingRewardsFinderPopup.svelte | 8 ++--- .../popups/WalletSwitcherPopup.svelte | 4 +-- .../popups/send/SendConfirmationPopup.svelte | 2 +- .../desktop/features/settings.features.ts | 2 +- packages/desktop/features/wallet.features.ts | 2 +- .../views/advanced/HiddenAccounts.svelte | 17 ---------- .../views/advanced/HiddenWallets.svelte | 17 ++++++++++ .../advanced/advanced-settings.constant.js | 4 +-- .../settings/views/advanced/index.js | 2 +- .../dashboard/wallet/views/WalletView.svelte | 8 ++--- .../views/CustomNetworkView.svelte | 2 +- .../components/inputs/RecipientInput.svelte | 12 +++---- ...elte => ToggleHiddenWalletMenuItem.svelte} | 12 +++---- .../shared/components/menu-items/index.js | 2 +- .../NftActivityTileContent.svelte | 2 +- .../icon/constants/settings-icon-svg.ts | 2 +- .../auxiliary/popup/enums/popup-id.enum.ts | 2 +- .../actions/registerProposalsFromNodes.ts | 13 +++---- packages/shared/lib/core/nfts/utils/index.ts | 2 +- .../core/nfts/utils/isNftOwnedByAnyAccount.ts | 12 ------- .../core/nfts/utils/isNftOwnedByAnyWallet.ts | 12 +++++++ .../checkAndRemoveProfilePicture.ts | 4 +-- .../findActiveWalletWithAddress.ts | 0 .../getWalletColorById.ts | 0 .../index.ts | 0 .../updateActiveWalletPersistedData.ts | 0 .../shared/lib/core/profile/actions/index.ts | 3 +- .../initial-active-profile.constant.ts | 2 +- .../profile/interfaces/profile.interface.ts | 2 +- .../profile/stores/active-wallets.store.ts | 2 +- .../settings/advanced-settings-route.enum.ts | 2 +- .../core/wallet/actions/consolidateOutputs.ts | 6 ++-- .../generateSingleConsolidationActivity.ts | 8 ++--- .../generateSingleGovernanceActivity.ts | 6 ++-- .../generateVestingActivity.ts | 8 ++--- .../getDirectionFromOutgoingTransaction.ts | 2 +- .../transactions/getSenderFromTransaction.ts | 4 +-- .../interfaces/settings-features.interface.ts | 2 +- .../interfaces/wallet-features.interface.ts | 2 +- ...balance.mock.ts => wallet-balance.mock.ts} | 8 +++-- .../shared/lib/tests/__mocks__/wallet.mock.ts | 4 +-- packages/shared/locales/en.json | 20 +++++------ 58 files changed, 193 insertions(+), 201 deletions(-) rename packages/desktop/components/{AccountActivity.svelte => WalletActivity.svelte} (100%) rename packages/desktop/components/{AccountSummary.svelte => WalletSummary.svelte} (85%) rename packages/desktop/components/buttons/menu-buttons/{AccountActionsButton.svelte => WalletActionsButton.svelte} (79%) rename packages/desktop/components/popups/{DeleteAccountPopup.svelte => DeleteWalletPopup.svelte} (85%) delete mode 100644 packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte create mode 100644 packages/desktop/views/dashboard/settings/views/advanced/HiddenWallets.svelte rename packages/shared/components/menu-items/{ToggleHiddenAccountMenuItem.svelte => ToggleHiddenWalletMenuItem.svelte} (71%) delete mode 100644 packages/shared/lib/core/nfts/utils/isNftOwnedByAnyAccount.ts create mode 100644 packages/shared/lib/core/nfts/utils/isNftOwnedByAnyWallet.ts rename packages/shared/lib/core/profile/actions/{active-accounts => active-wallet}/findActiveWalletWithAddress.ts (100%) rename packages/shared/lib/core/profile/actions/{active-accounts => active-wallet}/getWalletColorById.ts (100%) rename packages/shared/lib/core/profile/actions/{active-accounts => active-wallet}/index.ts (100%) rename packages/shared/lib/core/profile/actions/{active-accounts => active-wallet}/updateActiveWalletPersistedData.ts (100%) rename packages/shared/lib/tests/__mocks__/{account-balance.mock.ts => wallet-balance.mock.ts} (71%) diff --git a/packages/desktop/components/AccountActivity.svelte b/packages/desktop/components/WalletActivity.svelte similarity index 100% rename from packages/desktop/components/AccountActivity.svelte rename to packages/desktop/components/WalletActivity.svelte diff --git a/packages/desktop/components/AccountSummary.svelte b/packages/desktop/components/WalletSummary.svelte similarity index 85% rename from packages/desktop/components/AccountSummary.svelte rename to packages/desktop/components/WalletSummary.svelte index 8ff8e230589..db247d9197e 100644 --- a/packages/desktop/components/AccountSummary.svelte +++ b/packages/desktop/components/WalletSummary.svelte @@ -1,5 +1,5 @@ - +
{localize('general.balanceWithNetwork', { values: { network: fomattedNetworkName } })} - +
-
+ diff --git a/packages/desktop/components/buttons/menu-buttons/AccountActionsButton.svelte b/packages/desktop/components/buttons/menu-buttons/WalletActionsButton.svelte similarity index 79% rename from packages/desktop/components/buttons/menu-buttons/AccountActionsButton.svelte rename to packages/desktop/components/buttons/menu-buttons/WalletActionsButton.svelte index 03eb4801298..1c7b763b8f2 100644 --- a/packages/desktop/components/buttons/menu-buttons/AccountActionsButton.svelte +++ b/packages/desktop/components/buttons/menu-buttons/WalletActionsButton.svelte @@ -5,7 +5,7 @@ let modal: Modal - + - + diff --git a/packages/desktop/components/buttons/menu-buttons/index.js b/packages/desktop/components/buttons/menu-buttons/index.js index 8542bc19bd0..be9e7f30ece 100644 --- a/packages/desktop/components/buttons/menu-buttons/index.js +++ b/packages/desktop/components/buttons/menu-buttons/index.js @@ -1 +1 @@ -export { default as AccountActionsButton } from './AccountActionsButton.svelte' +export { default as WalletActionsButton } from './WalletActionsButton.svelte' diff --git a/packages/desktop/components/buttons/popup-buttons/RefreshTokenMetadataButton.svelte b/packages/desktop/components/buttons/popup-buttons/RefreshTokenMetadataButton.svelte index 794c4fbb42c..b52e926957e 100644 --- a/packages/desktop/components/buttons/popup-buttons/RefreshTokenMetadataButton.svelte +++ b/packages/desktop/components/buttons/popup-buttons/RefreshTokenMetadataButton.svelte @@ -2,14 +2,14 @@ import { OnboardingButton } from '@ui' import { localize } from '@core/i18n' - import { refreshAccountAssetsForActiveProfile } from '@core/wallet' + import { refreshWalletAssetsForActiveProfile } from '@core/wallet' import { showAppNotification } from '@auxiliary/notification' import { closePopup, openPopup, PopupId } from '@auxiliary/popup' import { TextHintVariant } from 'shared/components/enums' function refreshTokenMetadata(): void { - refreshAccountAssetsForActiveProfile(true) + refreshWalletAssetsForActiveProfile(true) showAppNotification({ type: 'success', message: localize('notifications.refreshTokenMetadata.success'), diff --git a/packages/desktop/components/index.js b/packages/desktop/components/index.js index 0143a5740b5..99d664c7e45 100644 --- a/packages/desktop/components/index.js +++ b/packages/desktop/components/index.js @@ -5,8 +5,8 @@ export * from './modals' export * from './panes' export * from './popups' -export { default as AccountActivity } from './AccountActivity.svelte' -export { default as AccountSummary } from './AccountSummary.svelte' +export { default as WalletActivity } from './WalletActivity.svelte' +export { default as WalletSummary } from './WalletSummary.svelte' export { default as WalletSwitcher } from './WalletSwitcher.svelte' export { default as OnboardingLayout } from './OnboardingLayout.svelte' export { default as Proposals } from './Proposals.svelte' diff --git a/packages/desktop/components/modals/VestingModal.svelte b/packages/desktop/components/modals/VestingModal.svelte index 98f9548065a..1f8a80b4838 100644 --- a/packages/desktop/components/modals/VestingModal.svelte +++ b/packages/desktop/components/modals/VestingModal.svelte @@ -14,11 +14,11 @@ - + - + diff --git a/packages/desktop/components/modals/WalletActionsMenu.svelte b/packages/desktop/components/modals/WalletActionsMenu.svelte index b69d3afec15..920fe201699 100644 --- a/packages/desktop/components/modals/WalletActionsMenu.svelte +++ b/packages/desktop/components/modals/WalletActionsMenu.svelte @@ -1,5 +1,5 @@ - + {#if $activeProfile?.network?.id === NetworkId.Iota || $activeProfile?.network?.id === NetworkId.IotaAlphanet} {/if} - + {#if $isActiveLedgerProfile} {/if} - +
- {#if showDeleteAccount} + {#if showDeleteWallet} {/if} -
+
diff --git a/packages/desktop/components/modals/WalletSwitcherModal.svelte b/packages/desktop/components/modals/WalletSwitcherModal.svelte index fa5e892fed3..35594e214e4 100644 --- a/packages/desktop/components/modals/WalletSwitcherModal.svelte +++ b/packages/desktop/components/modals/WalletSwitcherModal.svelte @@ -17,7 +17,7 @@ async function scrollToSelectedWallet(): Promise { await tick() - const element = document.getElementById(`account-${$selectedWallet.id}`) + const element = document.getElementById(`wallet-${$selectedWallet.id}`) element?.scrollIntoView({ behavior: 'auto' }) } @@ -34,13 +34,13 @@ size="large" position={{ top: '30px', left: '50%' }} > - - + + {#each $visibleActiveWallets as wallet} - + {/each} - - + +
- - + + diff --git a/packages/desktop/components/popups/DeleteAccountPopup.svelte b/packages/desktop/components/popups/DeleteWalletPopup.svelte similarity index 85% rename from packages/desktop/components/popups/DeleteAccountPopup.svelte rename to packages/desktop/components/popups/DeleteWalletPopup.svelte index 336dd7acc74..185d81b7e5f 100644 --- a/packages/desktop/components/popups/DeleteAccountPopup.svelte +++ b/packages/desktop/components/popups/DeleteWalletPopup.svelte @@ -17,11 +17,11 @@ async function onDeleteClick(): Promise { error = null isBusy = true - await deleteStrongholdAccount(password) + await deleteStrongholdWallet(password) isBusy = false } - async function deleteStrongholdAccount(password: string): Promise { + async function deleteStrongholdWallet(password: string): Promise { try { if ($isSoftwareProfile) { await setStrongholdPassword(password) @@ -41,17 +41,17 @@
- {localize('popups.deleteAccount.title', { + {localize('popups.deleteWallet.title', { values: { name: $selectedWallet?.name }, })}
- {localize('popups.deleteAccount.body')} - + {localize('popups.deleteWallet.body')} +
{#if $isSoftwareProfile} - {localize('popups.deleteAccount.typePassword')} + {localize('popups.deleteWallet.typePassword')} - {localize('actions.deleteAccount')} + {localize('actions.deleteWallet')}
diff --git a/packages/desktop/components/popups/ManageWalletPopup.svelte b/packages/desktop/components/popups/ManageWalletPopup.svelte index 1a5587b5c8a..7c444dbb7af 100644 --- a/packages/desktop/components/popups/ManageWalletPopup.svelte +++ b/packages/desktop/components/popups/ManageWalletPopup.svelte @@ -48,12 +48,12 @@ } - +
{localize('general.manageWallet')} - + - - + +
- + @@ -78,5 +78,5 @@ > {localize('actions.save')} - -
+ + diff --git a/packages/desktop/components/popups/Popup.svelte b/packages/desktop/components/popups/Popup.svelte index c4a13c92b98..8231c96932b 100644 --- a/packages/desktop/components/popups/Popup.svelte +++ b/packages/desktop/components/popups/Popup.svelte @@ -21,7 +21,7 @@ import ConnectLedgerPopup from './ConnectLedgerPopup.svelte' import createWalletPopup from './CreateWalletPopup.svelte' import DeepLinkErrorPopup from './DeepLinkErrorPopup.svelte' - import DeleteAccountPopup from './DeleteAccountPopup.svelte' + import DeleteWalletPopup from './DeleteWalletPopup.svelte' import DeleteProfilePopup from './DeleteProfilePopup.svelte' import DiagnosticsPopup from './DiagnosticsPopup.svelte' import EnableLedgerBlindSigningPopup from './EnableLedgerBlindSigningPopup.svelte' @@ -107,7 +107,7 @@ [PopupId.ConnectLedger]: ConnectLedgerPopup, [PopupId.createWallet]: createWalletPopup, [PopupId.DeepLinkError]: DeepLinkErrorPopup, - [PopupId.DeleteAccount]: DeleteAccountPopup, + [PopupId.DeleteWallet]: DeleteWalletPopup, [PopupId.DeleteProfile]: DeleteProfilePopup, [PopupId.Diagnostics]: DiagnosticsPopup, [PopupId.EnableLedgerBlindSigning]: EnableLedgerBlindSigningPopup, diff --git a/packages/desktop/components/popups/VestingRewardsFinderPopup.svelte b/packages/desktop/components/popups/VestingRewardsFinderPopup.svelte index 08c09d9a464..d0385c99e8d 100644 --- a/packages/desktop/components/popups/VestingRewardsFinderPopup.svelte +++ b/packages/desktop/components/popups/VestingRewardsFinderPopup.svelte @@ -20,8 +20,8 @@ import { truncateString } from '@core/utils' import { formatTokenAmountBestMatch, - generateAndStoreActivitiesForAllAccounts, - refreshAccountAssetsForActiveProfile, + generateAndStoreActivitiesForAllWallets, + refreshWalletAssetsForActiveProfile, } from '@core/wallet' import VirtualList from '@sveltejs/svelte-virtual-list' import { Button, FontWeight, KeyValueBox, Text, TextHint, TextType } from 'shared/components' @@ -97,8 +97,8 @@ onDestroy(async () => { if (hasUsedVestingRewardsFinder) { - await refreshAccountAssetsForActiveProfile() - await generateAndStoreActivitiesForAllAccounts() + await refreshWalletAssetsForActiveProfile() + await generateAndStoreActivitiesForAllWallets() loadNftsForActiveProfile() } }) diff --git a/packages/desktop/components/popups/WalletSwitcherPopup.svelte b/packages/desktop/components/popups/WalletSwitcherPopup.svelte index ffd39cf5291..365c96acae2 100644 --- a/packages/desktop/components/popups/WalletSwitcherPopup.svelte +++ b/packages/desktop/components/popups/WalletSwitcherPopup.svelte @@ -22,10 +22,10 @@ - {localize('popups.deeplinkAccountSwitch.title')} + {localize('popups.deeplinkWalletSwitch.title')}
- {localize('popups.deeplinkAccountSwitch.body')} + {localize('popups.deeplinkWalletSwitch.body')}
diff --git a/packages/desktop/components/popups/send/SendConfirmationPopup.svelte b/packages/desktop/components/popups/send/SendConfirmationPopup.svelte index c6e671a0652..023bf2d8bfa 100644 --- a/packages/desktop/components/popups/send/SendConfirmationPopup.svelte +++ b/packages/desktop/components/popups/send/SendConfirmationPopup.svelte @@ -66,7 +66,7 @@ $: isBaseTokenTransfer = transactionDetails.type === NewTransactionType.TokenTransfer && transactionDetails.asset?.metadata?.standard === TokenStandard.BaseToken - $: isInternal = recipient.type === 'account' + $: isInternal = recipient.type === 'wallet' $: isLayer2Transaction = !!layer2Parameters $: isTransferring = $selectedWallet.isTransferring $: hideGiftToggle = isBaseTokenTransfer || isLayer2Transaction || (disableToggleGift && !giftStorageDeposit) diff --git a/packages/desktop/features/settings.features.ts b/packages/desktop/features/settings.features.ts index dc83ed8cb4d..5d42fb74ccb 100644 --- a/packages/desktop/features/settings.features.ts +++ b/packages/desktop/features/settings.features.ts @@ -79,7 +79,7 @@ const settingsFeatures: ISettingsFeatures = { balanceFinder: { enabled: true, }, - hiddenAccounts: { + hiddenWallets: { enabled: true, }, developerToggle: { diff --git a/packages/desktop/features/wallet.features.ts b/packages/desktop/features/wallet.features.ts index 46a9b567440..4eb393048ee 100644 --- a/packages/desktop/features/wallet.features.ts +++ b/packages/desktop/features/wallet.features.ts @@ -2,7 +2,7 @@ import { IWalletFeatures } from '@lib/features/interfaces' const walletFeatures: IWalletFeatures = { enabled: true, - accountSummary: { + walletSummary: { enabled: true, }, sendAndReceive: { diff --git a/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte b/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte deleted file mode 100644 index ce386e4fb99..00000000000 --- a/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - -{localize('views.settings.hiddenAccounts.title')} -{localize('views.settings.hiddenAccounts.description')} - diff --git a/packages/desktop/views/dashboard/settings/views/advanced/HiddenWallets.svelte b/packages/desktop/views/dashboard/settings/views/advanced/HiddenWallets.svelte new file mode 100644 index 00000000000..4128181daa4 --- /dev/null +++ b/packages/desktop/views/dashboard/settings/views/advanced/HiddenWallets.svelte @@ -0,0 +1,17 @@ + + +{localize('views.settings.hiddenWallets.title')} +{localize('views.settings.hiddenWallets.description')} + diff --git a/packages/desktop/views/dashboard/settings/views/advanced/advanced-settings.constant.js b/packages/desktop/views/dashboard/settings/views/advanced/advanced-settings.constant.js index d1008ec4037..6aa72684b90 100644 --- a/packages/desktop/views/dashboard/settings/views/advanced/advanced-settings.constant.js +++ b/packages/desktop/views/dashboard/settings/views/advanced/advanced-settings.constant.js @@ -1,8 +1,8 @@ -import { BalanceFinder, HiddenAccounts, DeveloperToggle } from '.' +import { BalanceFinder, HiddenWallets, DeveloperToggle } from '.' import { AdvancedSettingsRoute } from '@core/router' export const ADVANCED_SETTINGS = [ { component: BalanceFinder, childRoute: AdvancedSettingsRoute.BalanceFinder, requiresLogin: true }, - { component: HiddenAccounts, childRoute: AdvancedSettingsRoute.HiddenAccounts, requiresLogin: true }, + { component: HiddenWallets, childRoute: AdvancedSettingsRoute.HiddenAccounts, requiresLogin: true }, { component: DeveloperToggle, childRoute: AdvancedSettingsRoute.DeveloperToggle, requiresLogin: true }, ] diff --git a/packages/desktop/views/dashboard/settings/views/advanced/index.js b/packages/desktop/views/dashboard/settings/views/advanced/index.js index 59fd5f7b0fd..801ec3427b8 100644 --- a/packages/desktop/views/dashboard/settings/views/advanced/index.js +++ b/packages/desktop/views/dashboard/settings/views/advanced/index.js @@ -1,5 +1,5 @@ export { default as DeveloperToggle } from './DeveloperToggle.svelte' -export { default as HiddenAccounts } from './HiddenAccounts.svelte' +export { default as HiddenWallets } from './HiddenWallets.svelte' export { default as BalanceFinder } from './BalanceFinder.svelte' export * from './advanced-settings.constant' diff --git a/packages/desktop/views/dashboard/wallet/views/WalletView.svelte b/packages/desktop/views/dashboard/wallet/views/WalletView.svelte index 632cf8adb08..6fa00af8aa0 100644 --- a/packages/desktop/views/dashboard/wallet/views/WalletView.svelte +++ b/packages/desktop/views/dashboard/wallet/views/WalletView.svelte @@ -1,6 +1,6 @@ @@ -11,8 +11,8 @@
- {#if features?.wallet?.accountSummary?.enabled} - + {#if features?.wallet?.walletSummary?.enabled} + {/if} @@ -31,7 +31,7 @@ {#if features?.wallet?.activityHistory?.enabled} - + {/if}
diff --git a/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte b/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte index ca735cb4d2d..90455196fe2 100644 --- a/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte +++ b/packages/desktop/views/onboarding/views/network-setup/views/CustomNetworkView.svelte @@ -43,7 +43,7 @@ updateOnboardingProfile({ clientOptions: { nodes: [node], primaryNode: node } }) await initialiseOnboardingProfile(true) - // The API request to check if a node is reachable requires an existing account manager. + // The API request to check if a node is reachable requires an existing wallet manager. const nodeInfoResponse = await getNodeInfo(node.url) // Check network of node matches selected id if ( diff --git a/packages/shared/components/inputs/RecipientInput.svelte b/packages/shared/components/inputs/RecipientInput.svelte index 80498e5143c..257d0c4a6a1 100644 --- a/packages/shared/components/inputs/RecipientInput.svelte +++ b/packages/shared/components/inputs/RecipientInput.svelte @@ -17,11 +17,11 @@ let error: string let selected: IOption = - recipient?.type === 'account' - ? { key: recipient.account.name, value: recipient.account.depositAddress } + recipient?.type === 'wallet' + ? { key: recipient.wallet.name, value: recipient.wallet.depositAddress } : { value: recipient?.address } - $: accountOptions = isLayer2 ? [] : getLayer1AccountOptions() + $: walletOptions = isLayer2 ? [] : getLayer1WalletOptions() $: recipient = getSubjectFromAddress(selected?.value) $: isLayer2, (error = '') @@ -37,7 +37,7 @@ } else { validateBech32Address(getNetworkHrp(), recipient?.address) } - } else if (recipient?.type === 'account') { + } else if (recipient?.type === 'wallet') { if (isLayer2) { throw new Layer1RecipientError() } @@ -52,7 +52,7 @@ } } - function getLayer1AccountOptions(): IOption[] { + function getLayer1WalletOptions(): IOption[] { return $visibleActiveWallets .filter((wallet) => wallet.id !== $selectedWalletId) .map((wallet) => ({ @@ -70,7 +70,7 @@ bind:modal bind:error {disabled} - options={accountOptions} + options={walletOptions} pickerHeight="max-h-48" {...$$restProps} let:option diff --git a/packages/shared/components/menu-items/ToggleHiddenAccountMenuItem.svelte b/packages/shared/components/menu-items/ToggleHiddenWalletMenuItem.svelte similarity index 71% rename from packages/shared/components/menu-items/ToggleHiddenAccountMenuItem.svelte rename to packages/shared/components/menu-items/ToggleHiddenWalletMenuItem.svelte index d80cffac866..a2a3b5c69e7 100644 --- a/packages/shared/components/menu-items/ToggleHiddenAccountMenuItem.svelte +++ b/packages/shared/components/menu-items/ToggleHiddenWalletMenuItem.svelte @@ -7,24 +7,24 @@ export let onClick: () => unknown - function onShowAccountClick(): void { + function onShowWalletClick(): void { if ($selectedWallet) { updateActiveWalletPersistedData($selectedWallet.id, { hidden: false }) onClick && onClick() } } - function onHideAccountClick(): void { + function onHideWalletClick(): void { if ($nonHiddenActiveWallets.length > 1) { if ($selectedWallet) { updateActiveWalletPersistedData($selectedWallet.id, { hidden: true }) - if (!$activeProfile.showHiddenAccounts) { + if (!$activeProfile.showHiddenWallets) { setNextSelectedWallet() } onClick && onClick() } } else { - console.error('Not enough accounts visible: ', $nonHiddenActiveWallets.length) + console.error('Not enough wallets visible: ', $nonHiddenActiveWallets.length) } } @@ -32,8 +32,8 @@ {#if $selectedWallet} ($selectedWallet.hidden ? onShowAccountClick() : onHideAccountClick())} + title={localize($selectedWallet.hidden ? 'actions.showWallet' : 'actions.hideWallet')} + onClick={() => ($selectedWallet.hidden ? onShowWalletClick() : onHideWalletClick())} disabled={!$selectedWallet.hidden && $nonHiddenActiveWallets.length <= 1} {...$$restProps} /> diff --git a/packages/shared/components/menu-items/index.js b/packages/shared/components/menu-items/index.js index 664fd37c341..370c15a68f3 100644 --- a/packages/shared/components/menu-items/index.js +++ b/packages/shared/components/menu-items/index.js @@ -1,2 +1,2 @@ export { default as WalletSwitcherMenuItem } from './WalletSwitcherMenuItem.svelte' -export { default as ToggleHiddenAccountMenuItem } from './ToggleHiddenAccountMenuItem.svelte' +export { default as ToggleHiddenWalletMenuItem } from './ToggleHiddenWalletMenuItem.svelte' diff --git a/packages/shared/components/tiles/tileContents/NftActivityTileContent.svelte b/packages/shared/components/tiles/tileContents/NftActivityTileContent.svelte index 91582a53fb8..78b998b982c 100644 --- a/packages/shared/components/tiles/tileContents/NftActivityTileContent.svelte +++ b/packages/shared/components/tiles/tileContents/NftActivityTileContent.svelte @@ -13,7 +13,7 @@ activity.direction === ActivityDirection.Incoming || activity.direction === ActivityDirection.SelfTransaction $: action = localize(getActivityTileTitle(activity)) $: subject = localize(isIncoming ? 'general.fromAddress' : 'general.toAddress', { - values: { account: subjectLocale }, + values: { address: subjectLocale }, }) $: formattedAsset = { text: nft?.name ?? '', diff --git a/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts b/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts index 5a5a73d0669..6ad00566a50 100644 --- a/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts +++ b/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts @@ -31,7 +31,7 @@ export const SETTINGS_ICON_SVG = { [SecuritySettingsRoute.ChangePassword]: Icon.Lock2, [SecuritySettingsRoute.ChangePincode]: Icon.Lock, [AdvancedSettingsRoute.BalanceFinder]: Icon.Reset, - [AdvancedSettingsRoute.HiddenAccounts]: Icon.View, + [AdvancedSettingsRoute.hiddenWallets]: Icon.View, [AdvancedSettingsRoute.DeveloperToggle]: Icon.Dev, [HelpAndInfoRoute.Diagnostics]: Icon.Tools, [HelpAndInfoRoute.ErrorLog]: Icon.Warning, diff --git a/packages/shared/lib/auxiliary/popup/enums/popup-id.enum.ts b/packages/shared/lib/auxiliary/popup/enums/popup-id.enum.ts index 11da53d0e17..15ba39fd236 100644 --- a/packages/shared/lib/auxiliary/popup/enums/popup-id.enum.ts +++ b/packages/shared/lib/auxiliary/popup/enums/popup-id.enum.ts @@ -13,7 +13,7 @@ export enum PopupId { ConnectLedger = 'connectLedger', createWallet = 'createWallet', DeepLinkError = 'deepLinkError', - DeleteAccount = 'deleteAccount', + DeleteWallet = 'deleteWallet', DeleteProfile = 'deleteProfile', Diagnostics = 'diagnostics', EnableLedgerBlindSigning = 'enableLedgerBlindSigning', diff --git a/packages/shared/lib/contexts/governance/actions/registerProposalsFromNodes.ts b/packages/shared/lib/contexts/governance/actions/registerProposalsFromNodes.ts index ef0d50b85ec..759af4c8d7c 100644 --- a/packages/shared/lib/contexts/governance/actions/registerProposalsFromNodes.ts +++ b/packages/shared/lib/contexts/governance/actions/registerProposalsFromNodes.ts @@ -1,13 +1,8 @@ -import { get } from 'svelte/store' - import { IWalletState } from '@core/wallet/interfaces' -import { INode } from '@core/network/interfaces' -import { activeProfile } from '@core/profile/stores' - +import { getActiveProfile } from '@core/profile/stores' import { registerProposalsForWallets } from './registerProposalsForWallets' -// TODO(2.0) FIx this -export async function registerProposalsFromNodes(accounts: IWalletState[], nodes?: INode[]): Promise { - const _nodes = nodes ? nodes : get(activeProfile)?.clientOptions?.nodes - await Promise.all(_nodes.map((node) => registerProposalsForWallets({ node }, accounts))) +export async function registerProposalsFromNodes(wallets: IWalletState[]): Promise { + const nodes = getActiveProfile().clientOptions?.nodes || [] + await Promise.all(nodes.map((node) => registerProposalsForWallets({ node }, wallets))) } diff --git a/packages/shared/lib/core/nfts/utils/index.ts b/packages/shared/lib/core/nfts/utils/index.ts index ea8bd888dc2..d3a959ef871 100644 --- a/packages/shared/lib/core/nfts/utils/index.ts +++ b/packages/shared/lib/core/nfts/utils/index.ts @@ -4,7 +4,7 @@ export * from './composeUrlFromNftUri' export * from './convertAndFormatNftMetadata' export * from './getSpendableStatusFromUnspentNftOutput' export * from './fetchWithTimeout' -export * from './isNftOwnedByAnyAccount' +export * from './isNftOwnedByAnyWallet' export * from './parseNftMetadata' export * from './rewriteIpfsUri' export * from './getParentMimeType' diff --git a/packages/shared/lib/core/nfts/utils/isNftOwnedByAnyAccount.ts b/packages/shared/lib/core/nfts/utils/isNftOwnedByAnyAccount.ts deleted file mode 100644 index 2b30770fdb5..00000000000 --- a/packages/shared/lib/core/nfts/utils/isNftOwnedByAnyAccount.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { get } from 'svelte/store' -import { allWalletNfts } from '../stores' - -export function isNftOwnedByAnyAccount(nftId: string): boolean { - for (const accountNfts of get(allWalletNfts) ?? []) { - const nft = accountNfts.find((nft) => nft.id === nftId) - if (nft?.isSpendable) { - return true - } - } - return false -} diff --git a/packages/shared/lib/core/nfts/utils/isNftOwnedByAnyWallet.ts b/packages/shared/lib/core/nfts/utils/isNftOwnedByAnyWallet.ts new file mode 100644 index 00000000000..9cb16b6468e --- /dev/null +++ b/packages/shared/lib/core/nfts/utils/isNftOwnedByAnyWallet.ts @@ -0,0 +1,12 @@ +import { get } from 'svelte/store' +import { allWalletNfts } from '../stores' + +export function isNftOwnedByAnyWallet(nftId: string): boolean { + for (const walletNfts of Object.values(get(allWalletNfts) ?? {})) { + const nft = walletNfts.find((nft) => nft.id === nftId) + if (nft?.isSpendable) { + return true + } + } + return false +} diff --git a/packages/shared/lib/core/profile/actions/active-profile/checkAndRemoveProfilePicture.ts b/packages/shared/lib/core/profile/actions/active-profile/checkAndRemoveProfilePicture.ts index 8c528c1c6e2..b02b7a4f8ef 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/checkAndRemoveProfilePicture.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/checkAndRemoveProfilePicture.ts @@ -1,11 +1,11 @@ -import { isNftOwnedByAnyAccount } from '@core/nfts/utils' +import { isNftOwnedByAnyWallet } from '@core/nfts/utils' import { activeProfile, updateActiveProfile } from '@core/profile/stores' import { get } from 'svelte/store' export function checkAndRemoveProfilePicture(): void { const _activeProfile = get(activeProfile) if (_activeProfile.pfp) { - const isProfilePictureStillOwned = isNftOwnedByAnyAccount(_activeProfile.pfp.id) + const isProfilePictureStillOwned = isNftOwnedByAnyWallet(_activeProfile.pfp.id) if (!isProfilePictureStillOwned) { updateActiveProfile({ pfp: undefined }) } diff --git a/packages/shared/lib/core/profile/actions/active-accounts/findActiveWalletWithAddress.ts b/packages/shared/lib/core/profile/actions/active-wallet/findActiveWalletWithAddress.ts similarity index 100% rename from packages/shared/lib/core/profile/actions/active-accounts/findActiveWalletWithAddress.ts rename to packages/shared/lib/core/profile/actions/active-wallet/findActiveWalletWithAddress.ts diff --git a/packages/shared/lib/core/profile/actions/active-accounts/getWalletColorById.ts b/packages/shared/lib/core/profile/actions/active-wallet/getWalletColorById.ts similarity index 100% rename from packages/shared/lib/core/profile/actions/active-accounts/getWalletColorById.ts rename to packages/shared/lib/core/profile/actions/active-wallet/getWalletColorById.ts diff --git a/packages/shared/lib/core/profile/actions/active-accounts/index.ts b/packages/shared/lib/core/profile/actions/active-wallet/index.ts similarity index 100% rename from packages/shared/lib/core/profile/actions/active-accounts/index.ts rename to packages/shared/lib/core/profile/actions/active-wallet/index.ts diff --git a/packages/shared/lib/core/profile/actions/active-accounts/updateActiveWalletPersistedData.ts b/packages/shared/lib/core/profile/actions/active-wallet/updateActiveWalletPersistedData.ts similarity index 100% rename from packages/shared/lib/core/profile/actions/active-accounts/updateActiveWalletPersistedData.ts rename to packages/shared/lib/core/profile/actions/active-wallet/updateActiveWalletPersistedData.ts diff --git a/packages/shared/lib/core/profile/actions/index.ts b/packages/shared/lib/core/profile/actions/index.ts index 8c0a1f8d30e..fbfb5c66e78 100644 --- a/packages/shared/lib/core/profile/actions/index.ts +++ b/packages/shared/lib/core/profile/actions/index.ts @@ -5,7 +5,6 @@ export * from './recoverWallets' export * from './clearProfileFromMemory' export * from './deleteWallet' export * from './changePasswordAndUnlockStronghold' - -export * from './active-accounts' +export * from './active-wallet' export * from './active-profile' export * from './profiles' diff --git a/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts b/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts index 29fcb2d3064..a30d90f5349 100644 --- a/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts +++ b/packages/shared/lib/core/profile/constants/initial-active-profile.constant.ts @@ -13,5 +13,5 @@ export const INITIAL_ACTIVE_PROFILE: Partial = { to: string } }>({}), - showHiddenAccounts: false, + showHiddenWallets: false, } diff --git a/packages/shared/lib/core/profile/interfaces/profile.interface.ts b/packages/shared/lib/core/profile/interfaces/profile.interface.ts index d2842936271..66bc58aab04 100644 --- a/packages/shared/lib/core/profile/interfaces/profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/profile.interface.ts @@ -13,5 +13,5 @@ export interface IProfile extends IPersistedProfile { }> loggedIn: Writable lastActiveAt: Writable - showHiddenAccounts: boolean + showHiddenWallets: boolean } diff --git a/packages/shared/lib/core/profile/stores/active-wallets.store.ts b/packages/shared/lib/core/profile/stores/active-wallets.store.ts index 19d6379e070..4b1b566860d 100644 --- a/packages/shared/lib/core/profile/stores/active-wallets.store.ts +++ b/packages/shared/lib/core/profile/stores/active-wallets.store.ts @@ -33,7 +33,7 @@ export const visibleActiveWallets: Readable = derived( return [] } const unsortedVisiblewallets = - $activeProfile?.showHiddenAccounts ?? false + $activeProfile?.showHiddenWallets ?? 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/router/enums/settings/advanced-settings-route.enum.ts b/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts index eb30fbdfd60..1b3daa0c8b5 100644 --- a/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts +++ b/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts @@ -1,5 +1,5 @@ export enum AdvancedSettingsRoute { BalanceFinder = 'balanceFinder', - HiddenAccounts = 'hiddenAccounts', + hiddenWallets = 'hiddenWallets', DeveloperToggle = 'developerToggle', } diff --git a/packages/shared/lib/core/wallet/actions/consolidateOutputs.ts b/packages/shared/lib/core/wallet/actions/consolidateOutputs.ts index f1a4eb7db28..8595d870ffd 100644 --- a/packages/shared/lib/core/wallet/actions/consolidateOutputs.ts +++ b/packages/shared/lib/core/wallet/actions/consolidateOutputs.ts @@ -5,9 +5,9 @@ import { processAndAddToActivities } from '../utils' import { plainToInstance } from 'class-transformer' import { updateActiveWallet } from '@core/profile' -export async function consolidateOutputs(accountToConsolidate?: IWalletState): Promise { - const wallet = accountToConsolidate || getSelectedWallet() - if (!wallet) return Promise.reject('No account selected') +export async function consolidateOutputs(walletToConsolidate?: IWalletState): Promise { + const wallet = walletToConsolidate || getSelectedWallet() + if (!wallet) return Promise.reject('No wallet selected') try { updateActiveWallet(wallet.id, { hasConsolidatingOutputsTransactionInProgress: true, isTransferring: true }) diff --git a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleConsolidationActivity.ts b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleConsolidationActivity.ts index c0959a4009e..886347d457d 100644 --- a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleConsolidationActivity.ts +++ b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleConsolidationActivity.ts @@ -20,7 +20,7 @@ export async function generateSingleConsolidationActivity( const isHidden = false const isAssetHidden = false - const containsValue = await activityOutputContainsValue(account, wrappedOutput) + const containsValue = await activityOutputContainsValue(wallet, wrappedOutput) const outputId = wrappedOutput.outputId const id = outputId || transactionId @@ -32,10 +32,10 @@ export async function generateSingleConsolidationActivity( const tag = getTagFromOutput(output) const metadata = getMetadataFromOutput(output) - const sendingInfo = getSendingInformation(processedTransaction, output, account) - const asyncData = await getAsyncDataFromOutput(output, outputId, claimingData, account) + const sendingInfo = getSendingInformation(processedTransaction, output, wallet) + const asyncData = await getAsyncDataFromOutput(output, outputId, claimingData, wallet) - const { storageDeposit, giftedStorageDeposit } = await getStorageDepositFromOutput(account, output) + const { storageDeposit, giftedStorageDeposit } = await getStorageDepositFromOutput(wallet, output) return { type: ActivityType.Consolidation, isHidden, diff --git a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleGovernanceActivity.ts b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleGovernanceActivity.ts index 973e6adc094..8b9b55db578 100644 --- a/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleGovernanceActivity.ts +++ b/packages/shared/lib/core/wallet/utils/generateActivity/generateSingleGovernanceActivity.ts @@ -21,7 +21,7 @@ export async function generateSingleGovernanceActivity( const isHidden = false const isAssetHidden = false - const containsValue = await activityOutputContainsValue(account, wrappedOutput) + const containsValue = await activityOutputContainsValue(wallet, wrappedOutput) const outputId = wrappedOutput.outputId const id = outputId || transactionId @@ -31,9 +31,9 @@ export async function generateSingleGovernanceActivity( const tag = getTagFromOutput(output) const metadata = getMetadataFromOutput(output) - const sendingInfo = getSendingInformation(processedTransaction, output, account) + const sendingInfo = getSendingInformation(processedTransaction, output, wallet) - const { storageDeposit } = await getStorageDepositFromOutput(account, output) + const { storageDeposit } = await getStorageDepositFromOutput(wallet, output) const votingPower = getAmountFromOutput(output) const governanceInfo = getGovernanceInfo(output, wrappedInputs, metadata) diff --git a/packages/shared/lib/core/wallet/utils/generateActivity/generateVestingActivity.ts b/packages/shared/lib/core/wallet/utils/generateActivity/generateVestingActivity.ts index 21c142d6fd6..4f548995571 100644 --- a/packages/shared/lib/core/wallet/utils/generateActivity/generateVestingActivity.ts +++ b/packages/shared/lib/core/wallet/utils/generateActivity/generateVestingActivity.ts @@ -23,7 +23,7 @@ export async function generateVestingActivity( const isHidden = false const isAssetHidden = false - const containsValue = await activityOutputContainsValue(account, wrappedOutput) + const containsValue = await activityOutputContainsValue(wallet, wrappedOutput) const outputId = wrappedOutput.outputId const id = outputId || transactionId @@ -33,12 +33,12 @@ export async function generateVestingActivity( const tag = getTagFromOutput(output) const metadata = getMetadataFromOutput(output) - const sendingInfo = getSendingInformation(processedTransaction, output, account) - const asyncData = await getAsyncDataFromOutput(output, outputId, claimingData, account) + const sendingInfo = getSendingInformation(processedTransaction, output, wallet) + const asyncData = await getAsyncDataFromOutput(output, outputId, claimingData, wallet) const { parsedLayer2Metadata, destinationNetwork } = getLayer2ActivityInformation(metadata, sendingInfo) - const { storageDeposit, giftedStorageDeposit } = await getStorageDepositFromOutput(account, output) + const { storageDeposit, giftedStorageDeposit } = await getStorageDepositFromOutput(wallet, output) const rawAmount = getAmountFromOutput(output) - storageDeposit const assetId = getCoinType() diff --git a/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts b/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts index 74a71a83cc1..6182044ba1a 100644 --- a/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts +++ b/packages/shared/lib/core/wallet/utils/transactions/getDirectionFromOutgoingTransaction.ts @@ -13,6 +13,6 @@ export function getDirectionFromOutgoingTransaction( return walletDepositAddress !== outputRecipient }) - // If there is any output not destined for the account, it's an outgoing transaction. + // If there is any output not destined for the wallet, it's an outgoing transaction. return containsNonWalletRecipient ? ActivityDirection.Outgoing : ActivityDirection.SelfTransaction } diff --git a/packages/shared/lib/core/wallet/utils/transactions/getSenderFromTransaction.ts b/packages/shared/lib/core/wallet/utils/transactions/getSenderFromTransaction.ts index 4de7c6b7924..2ac2f52b562 100644 --- a/packages/shared/lib/core/wallet/utils/transactions/getSenderFromTransaction.ts +++ b/packages/shared/lib/core/wallet/utils/transactions/getSenderFromTransaction.ts @@ -5,12 +5,12 @@ import { SubjectType } from '@core/wallet/enums' export function getSenderFromTransaction( isIncoming: boolean, - accountAddress: string, + walletAddress: string, output: CommonOutput ): Subject | undefined { if (isIncoming) { return getSenderFromOutput(output) } else { - return { type: SubjectType.Address, address: accountAddress } + return { type: SubjectType.Address, address: walletAddress } } } diff --git a/packages/shared/lib/features/interfaces/settings-features.interface.ts b/packages/shared/lib/features/interfaces/settings-features.interface.ts index 0caa6800a69..c1f6c0da6af 100644 --- a/packages/shared/lib/features/interfaces/settings-features.interface.ts +++ b/packages/shared/lib/features/interfaces/settings-features.interface.ts @@ -36,7 +36,7 @@ interface INetworkSettingsFeatures extends IFeatureFlag { interface IAdvancedSettingsFeatures extends IFeatureFlag { balanceFinder: IFeatureFlag - hiddenAccounts: IFeatureFlag + hiddenWallets: IFeatureFlag developerToggle: IFeatureFlag } diff --git a/packages/shared/lib/features/interfaces/wallet-features.interface.ts b/packages/shared/lib/features/interfaces/wallet-features.interface.ts index 3a321800586..d00242a47d0 100644 --- a/packages/shared/lib/features/interfaces/wallet-features.interface.ts +++ b/packages/shared/lib/features/interfaces/wallet-features.interface.ts @@ -1,7 +1,7 @@ import { IFeatureFlag } from './feature-flag.interface' export interface IWalletFeatures extends IFeatureFlag { - accountSummary: IFeatureFlag + walletSummary: IFeatureFlag sendAndReceive: IFeatureFlag & { nft: IFeatureFlag } diff --git a/packages/shared/lib/tests/__mocks__/account-balance.mock.ts b/packages/shared/lib/tests/__mocks__/wallet-balance.mock.ts similarity index 71% rename from packages/shared/lib/tests/__mocks__/account-balance.mock.ts rename to packages/shared/lib/tests/__mocks__/wallet-balance.mock.ts index 236adf76b2d..cfc5c6a00a8 100644 --- a/packages/shared/lib/tests/__mocks__/account-balance.mock.ts +++ b/packages/shared/lib/tests/__mocks__/wallet-balance.mock.ts @@ -1,20 +1,22 @@ import { Balance } from '@iota/sdk/out/types' -export const MOCK_ACCOUNT_BALANCE: Balance = { +export const MOCK_WALLET_BALANCE: Balance = { baseCoin: { total: BigInt('10000'), available: BigInt('9000'), votingPower: '0', }, - aliases: [], foundries: [], nativeTokens: [], nfts: [], potentiallyLockedOutputs: {}, + accounts: [], + delegations: [], requiredStorageDeposit: { - alias: BigInt('0'), basic: BigInt('0'), foundry: BigInt('0'), nft: BigInt('0'), + account: BigInt('0'), + delegation: BigInt('0'), }, } diff --git a/packages/shared/lib/tests/__mocks__/wallet.mock.ts b/packages/shared/lib/tests/__mocks__/wallet.mock.ts index 14cd5dcbce7..8f7fea18e16 100644 --- a/packages/shared/lib/tests/__mocks__/wallet.mock.ts +++ b/packages/shared/lib/tests/__mocks__/wallet.mock.ts @@ -27,7 +27,7 @@ import { } from '@iota/sdk/out/types' import { IWallet } from '../../core/profile/interfaces' -import { MOCK_ACCOUNT_BALANCE } from './account-balance.mock' +import { MOCK_WALLET_BALANCE } from './wallet-balance.mock' export class WalletMock implements Partial { public id: string @@ -93,7 +93,7 @@ export class WalletMock implements Partial { } getBalance(): Promise { - return Promise.resolve(MOCK_ACCOUNT_BALANCE) + return Promise.resolve(MOCK_WALLET_BALANCE) } getIncomingTransaction(transactionId: string): Promise { diff --git a/packages/shared/locales/en.json b/packages/shared/locales/en.json index 0cf52f264b8..f000c5978a8 100644 --- a/packages/shared/locales/en.json +++ b/packages/shared/locales/en.json @@ -348,7 +348,7 @@ "title": "Balance finder", "description": "Perform an extended search of your balance" }, - "hiddenAccounts": { + "hiddenWallets": { "title": "Hidden wallets", "description": "Selecting this options will show wallets that were previously hidden" }, @@ -818,7 +818,7 @@ "title": "Backup your stronghold file", "body": "It is important to back up your wallet regularly to ensure you have a copy of your wallets and transaction history. If you lose your backup and recovery phrase you will lose access to your funds." }, - "deeplinkAccountSwitch": { + "deeplinkWalletSwitch": { "title": "Select a wallet", "body": "You just followed a deep link. Please select the wallet with which you want to continue." }, @@ -826,7 +826,7 @@ "title": "Failed link", "body": "This link failed or is invalid. Please try again or double check the source of the link." }, - "deleteAccount": { + "showDeleteWallet": { "title": "Delete {name}?", "body": "Are you sure you want to delete this wallet?", "hint": "Note: once deleted, you can restore this wallet by using the \"Wallet Finder\" in the settings.", @@ -1191,7 +1191,7 @@ "addProposal": { "title": "Add proposal", "body": "Please provide the information listed below to add a proposal.", - "addToAllAccounts": "Add the proposal to all accounts" + "addToAllWallets": "Add the proposal to all accounts" }, "editProposal": { "title": "Edit proposal", @@ -1343,7 +1343,7 @@ "customizeAcount": "Customise wallet", "hideAccount": "Hide wallet", "showAccount": "Unhide wallet", - "deleteAccount": "Delete wallet", + "showDeleteWallet": "Delete wallet", "max": "Max", "addNode": "Add node", "addingNode": "Adding node", @@ -1383,7 +1383,7 @@ "viewAddressHistory": "View address history", "viewBalanceBreakdown": "View balance breakdown", "verifyDepositAddress": "Verify deposit address", - "showHiddenAccounts": "Show hidden wallets", + "showHiddenWallets": "Show hidden wallets", "confirm": "Confirm", "hideNetworkStatistics": "Hide network statistics", "findWallets": "Find wallets", @@ -1610,12 +1610,8 @@ "creatingProfile": "Creating profile, please wait...", "fundMigration": "Fund migration", "accountRemoved": "This wallet is hidden. Unhide it to perform transfers.", - "fromAddress": "from {account}", - "toAddress": "to {account}", - "stakedFor": "Staked for {account}", - "unstakedFor": "Unstaked for {account}", - "votedFor": "Voted for {account}", - "unvotedFor": "Unvoted for {account}", + "fromAddress": "from {address}", + "toAddress": "to {address}", "stakingTransaction": "Staking Transaction", "unstakingTransaction": "Unstaking Transaction", "legacyNetwork": "Legacy Network", From 6ecfa1dcb5bbe8d61dd48a406862aa30c9732a73 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 29 Jan 2024 15:22:56 +0100 Subject: [PATCH 21/37] feat: Profile-centric file scheme for wallets --- .../lib/core/profile/utils/getStorageDirectoryOfWallet.ts | 6 ++++++ packages/shared/lib/core/profile/utils/index.ts | 1 + 2 files changed, 7 insertions(+) create mode 100644 packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts diff --git a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts new file mode 100644 index 00000000000..ec8fda43512 --- /dev/null +++ b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts @@ -0,0 +1,6 @@ +import { getStorageDirectoryOfProfile } from './getStorageDirectoryOfProfile' + +export const getStorageDirectoryOfWallet = async (profileId: string, walletId: string): Promise => { + const profilePath = await getStorageDirectoryOfProfile(profileId) + return `${profilePath}/${walletId}` +} diff --git a/packages/shared/lib/core/profile/utils/index.ts b/packages/shared/lib/core/profile/utils/index.ts index 450cb16ab86..97cf12e8298 100644 --- a/packages/shared/lib/core/profile/utils/index.ts +++ b/packages/shared/lib/core/profile/utils/index.ts @@ -6,3 +6,4 @@ export * from './removeProfileFolder' export * from './validateProfileName' export * from './getSecretManagerPath' export * from './getSecretManagerFromProfileType' +export * from './getStorageDirectoryOfWallet' From ecb5fa14af97eb91adaf95089e598cdc77446e9e Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 29 Jan 2024 16:01:35 +0100 Subject: [PATCH 22/37] chore: Clean up 2.0 comments --- packages/desktop/electron/preload.js | 21 +------------- .../actions/initialiseOnboardingProfile.ts | 1 - .../migrateStrongholdFromOnboardingProfile.ts | 2 +- ...eBackupForShimmerClaimingProfileManager.ts | 2 +- .../copyStrongholdFileToProfileDirectory.ts | 3 -- .../helpers/restoreBackupByCopyingFile.ts | 3 -- .../helpers/validateStrongholdCoinType.ts | 10 +++---- .../lib/core/api/interfaces/api.interface.ts | 1 - .../nfts/stores/selected-wallet-nfts.store.ts | 1 - ...ildProfileManagerOptionsFromProfileData.ts | 28 ------------------- .../lib/core/profile/actions/createWallet.ts | 2 +- .../lib/core/profile/actions/deleteWallet.ts | 10 +++++-- .../lib/core/profile/actions/getWallet.ts | 1 - .../lib/core/profile/actions/getWallets.ts | 2 -- .../profile/interfaces/wallet.interface.ts | 1 - .../profile/stores/active-profile.store.ts | 7 +++++ .../profile/stores/active-wallets.store.ts | 8 ++++-- .../profile/utils/getSecretManagerPath.ts | 1 - .../core/wallet/actions/createNewWallet.ts | 2 -- .../events-handlers/handleSpentOutputEvent.ts | 1 - .../core/wallet/actions/setSelectedWallet.ts | 1 - .../lib/core/wallet/enums/subject.enum.ts | 2 +- .../wallet/stores/selected-wallet-id.store.ts | 1 - .../core/wallet/utils/sumBalanceForWallets.ts | 1 - .../core/wallet/utils/sumTotalFromOutputs.ts | 1 - .../core/wallet/utils/syncWalletsInSeries.ts | 1 - .../core/wallet/utils/validateWalletName.ts | 2 -- 27 files changed, 29 insertions(+), 87 deletions(-) delete mode 100644 packages/shared/lib/core/profile/actions/buildProfileManagerOptionsFromProfileData.ts diff --git a/packages/desktop/electron/preload.js b/packages/desktop/electron/preload.js index 524cb2de6d4..eb08db5ae35 100644 --- a/packages/desktop/electron/preload.js +++ b/packages/desktop/electron/preload.js @@ -122,8 +122,7 @@ try { bindMethodsAcrossContextBridge(IotaSdk.Client.prototype, client) return client }, - // TODO(2.0): Is there a difference between this and getWallet? They both really make the same thing - async createWallet(id, walletOptions) { + async getWallet(id, walletOptions) { let wallet = wallets[id] if (!wallet) { wallet = await IotaSdk.Wallet.create(walletOptions) @@ -142,24 +141,6 @@ try { delete wallets[id] } }, - // TODO(2.0): Rename this to getWallet and fix all usages - async getWallet(id, walletOptions) { - let wallet = wallets[id] - if (!wallet) { - wallet = await IotaSdk.Wallet.create(walletOptions) - wallet.id = id - wallets[id] = wallet - bindMethodsAcrossContextBridge(IotaSdk.Wallet.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)) - accounts.forEach((account) => bindMethodsAcrossContextBridge(IotaSdk.Wallet.prototype, account)) - return accounts - }, async clearWalletsFromMemory() { for (const [id, wallet] of Object.entries(wallets)) { await wallet.stopBackgroundSync() diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts index c108777e71a..689ab9f2340 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfile.ts @@ -25,5 +25,4 @@ export async function initialiseOnboardingProfile( const _newProfile = buildInitialOnboardingProfile(isDeveloperProfile) onboardingProfile.set(_newProfile) - return Promise.resolve() // TODO(2.0) This is a temporal promise } diff --git a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts index f1e11fc49fd..d6e9dde83b0 100644 --- a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts @@ -12,7 +12,7 @@ import { clearProfileFromMemory } from '@core/profile' export async function migrateStrongholdFromOnboardingProfile(password: string): Promise { const profile = get(onboardingProfile) const profileDirectory = await getStorageDirectoryOfProfile(profile?.id) - // TODO(2.0) Update getSecretManagerPath + const secretManagerPath = getSecretManagerPath(profileDirectory) await copyStrongholdFileToProfileDirectory(profileDirectory, profile?.importFilePath ?? '') diff --git a/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts index 12a63374a65..35e335bb3a8 100644 --- a/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts @@ -21,7 +21,7 @@ export async function restoreBackupForShimmerClaimingProfileManager(strongholdPa * NOTE: We must check that the Stronghold was an IOTA-based backup and * not a Shimmer one. */ - await validateStrongholdCoinType(shimmerClaimingProfileManager, NetworkId.Iota) + validateStrongholdCoinType(shimmerClaimingProfileManager, NetworkId.Iota) const profileDirectory = await getStorageDirectoryOfProfile(id) await restoreBackupByCopyingFile( diff --git a/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts b/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts index 10e70b7b395..5e6b5e696ae 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts @@ -1,10 +1,7 @@ import { Platform } from '@core/app' import { getSecretManagerPath } from '@core/profile/utils' - import { UnableToCopyStrongholdBackupFileError } from '../errors' -// TODO(2.0) Fix getSecretManagerPath - export async function copyStrongholdFileToProfileDirectory( profileDirectory: string, importFilePath: string diff --git a/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts b/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts index dc1ac93bd65..1c4e8e4015c 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/restoreBackupByCopyingFile.ts @@ -12,9 +12,6 @@ export async function restoreBackupByCopyingFile( try { await copyStrongholdFileToProfileDirectory(storageDirectory, importFilePath) await secretManager.setStrongholdPassword(strongholdPassword) - // TODO(2.0) The secret manager doesn't need the client options, so this is fine to not do anymore - // But, we should make sure 100% of it anyway - // await secretManager.setClientOptions(clientOptions) } catch (err) { if (CLIENT_ERROR_REGEXES[ClientError.MigrationRequired].test(err?.error)) { throw new StrongholdMigrationRequiredError() diff --git a/packages/shared/lib/contexts/onboarding/helpers/validateStrongholdCoinType.ts b/packages/shared/lib/contexts/onboarding/helpers/validateStrongholdCoinType.ts index 77ec587a5aa..4da699e44eb 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/validateStrongholdCoinType.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/validateStrongholdCoinType.ts @@ -1,16 +1,14 @@ import { COIN_TYPE, NetworkId } from '@core/network' -import { getWallets } from 'shared/lib/core/profile' +import { getActiveWallets } from 'shared/lib/core/profile' import { get } from 'svelte/store' import { OnboardingType } from '../enums' import { CannotRestoreWithMismatchedCoinTypeError } from '../errors' import { onboardingProfile } from '../stores' -// Todo(2.0) Fix this -export async function validateStrongholdCoinType(networkId: NetworkId): Promise { - const wallets = await getWallets() // TODO (2.0) Should we be passing like a profile ID or something here? +export function validateStrongholdCoinType(networkId: NetworkId): void { + const wallets = getActiveWallets() - // TODO(2.0) Fix this - if (wallets[0]?.coinType !== COIN_TYPE[networkId]) { + if (wallets[0]?.walletOptions.bipPath?.coinType !== COIN_TYPE[networkId]) { const isClaiming = get(onboardingProfile)?.onboardingType === OnboardingType.Claim throw new CannotRestoreWithMismatchedCoinTypeError(isClaiming) } diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts index b5f73c3fc05..40c413a87da 100644 --- a/packages/shared/lib/core/api/interfaces/api.interface.ts +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -13,7 +13,6 @@ import { } 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 { getClientFromWallet(id: string): Promise createSecretManager(options: SecretManagerType): Promise diff --git a/packages/shared/lib/core/nfts/stores/selected-wallet-nfts.store.ts b/packages/shared/lib/core/nfts/stores/selected-wallet-nfts.store.ts index 396798d62db..4971fec3413 100644 --- a/packages/shared/lib/core/nfts/stores/selected-wallet-nfts.store.ts +++ b/packages/shared/lib/core/nfts/stores/selected-wallet-nfts.store.ts @@ -5,7 +5,6 @@ import { allWalletNfts } from './all-wallet-nfts.store' import { time } from '@core/app/stores/time.store' import { selectedWalletId } from '@core/wallet/stores/selected-wallet-id.store' -// TODO(2.0) Rename this export const selectedWalletNfts: Readable = derived( [selectedWalletId, allWalletNfts], ([$selectedWalletId, $allWalletNfts]) => { diff --git a/packages/shared/lib/core/profile/actions/buildProfileManagerOptionsFromProfileData.ts b/packages/shared/lib/core/profile/actions/buildProfileManagerOptionsFromProfileData.ts deleted file mode 100644 index 81729346e2c..00000000000 --- a/packages/shared/lib/core/profile/actions/buildProfileManagerOptionsFromProfileData.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { getSecretManagerFromProfileType, getStorageDirectoryOfProfile, IPersistedProfile } from '@core/profile' -import { COIN_TYPE, getDefaultClientOptions } from '@core/network' -import { WalletOptions } from '@iota/sdk/out/types' - -// TODO(2.0) Fix this and all usages -// - Do we even need this function at all? -export async function buildProfileOptionsFromProfileData( - profileData: Partial -): Promise { - const { id, type, network } = profileData - const storagePath = await getStorageDirectoryOfProfile(id) - const coinType = network?.coinType ? network?.coinType : network ? COIN_TYPE[network?.id] ?? 1 : 1 - const useDefaultClientOptions = - !profileData?.clientOptions || - !profileData?.clientOptions?.nodes || - profileData?.clientOptions?.nodes?.length < 1 - const clientOptions = useDefaultClientOptions ? getDefaultClientOptions(network.id) : profileData?.clientOptions - const secretManager = getSecretManagerFromProfileType(type, storagePath) - - return { - storagePath, - bipPath: { - coinType, - }, - clientOptions, - secretManager, - } -} diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index edfa49a60c4..9256e8c199a 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -31,7 +31,7 @@ export async function createWallet(profile: IPersistedProfile, password?: string const walletOptions = getWalletOptions(profile, storagePath, password) // TODO(2.0) It is weird to use the profile ID as the wallet ID, // we should probably have one for wallet and another one for the profile - const wallet = await api.createWallet(profile.id, { + const wallet = await api.getWallet(profile.id, { ...walletOptions, storagePath, }) diff --git a/packages/shared/lib/core/profile/actions/deleteWallet.ts b/packages/shared/lib/core/profile/actions/deleteWallet.ts index f722b2c2e3e..43c0a78594f 100644 --- a/packages/shared/lib/core/profile/actions/deleteWallet.ts +++ b/packages/shared/lib/core/profile/actions/deleteWallet.ts @@ -3,10 +3,13 @@ import { get } from 'svelte/store' import { api } from '@core/api' import { AppContext } from '@core/app/enums' import { routerManager } from '@core/router/stores' -import { visibleActiveWallets } from '../stores' +import { + removeWalletFromActiveWallets, + removeWalletPersistedDataFromActiveProfile, + visibleActiveWallets, +} from '../stores' import { CannotRemoveWalletError, RemoveNotLastWalletError, 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 wallets = get(visibleActiveWallets) const walletToBeDeleted = wallets.find((wallet) => wallet?.id === id) @@ -17,7 +20,8 @@ export async function deleteWallet(id: string): Promise { try { await api.deleteWallet(id) - // TODO(2.0) do we need this?: removewalletFromactiveWallets(id) + removeWalletFromActiveWallets(id) + removeWalletPersistedDataFromActiveProfile(id) setSelectedWallet(wallets[0]?.id ?? null) get(routerManager).resetRouterForAppContext(AppContext.Dashboard) } catch (err) { diff --git a/packages/shared/lib/core/profile/actions/getWallet.ts b/packages/shared/lib/core/profile/actions/getWallet.ts index 596c9c894c1..d5a7b3d45ea 100644 --- a/packages/shared/lib/core/profile/actions/getWallet.ts +++ b/packages/shared/lib/core/profile/actions/getWallet.ts @@ -4,7 +4,6 @@ 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 getWallet(walletId: string): Promise { const profile: IPersistedProfile = get(activeProfile) const persistedWallet: IPersistedWalletData = profile?.walletPersistedData[walletId] diff --git a/packages/shared/lib/core/profile/actions/getWallets.ts b/packages/shared/lib/core/profile/actions/getWallets.ts index 68d6d39d310..75d0fd6b593 100644 --- a/packages/shared/lib/core/profile/actions/getWallets.ts +++ b/packages/shared/lib/core/profile/actions/getWallets.ts @@ -3,8 +3,6 @@ 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 getWallets(): Promise { const profile = get(activeProfile) let wallets: IWallet[] = [] diff --git a/packages/shared/lib/core/profile/interfaces/wallet.interface.ts b/packages/shared/lib/core/profile/interfaces/wallet.interface.ts index 419fef5575b..4ba2a0c815b 100644 --- a/packages/shared/lib/core/profile/interfaces/wallet.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/wallet.interface.ts @@ -1,6 +1,5 @@ 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 } 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 56ebc7a914a..1ad5a314644 100644 --- a/packages/shared/lib/core/profile/stores/active-profile.store.ts +++ b/packages/shared/lib/core/profile/stores/active-profile.store.ts @@ -34,6 +34,13 @@ export function addWalletPersistedDataToActiveProfile( }) } +export function removeWalletPersistedDataFromActiveProfile(walletId: string): void { + activeProfile?.update((state) => { + delete state.walletPersistedData[walletId] + return state + }) +} + export function getActiveProfilePersistedWalletData(walletId: string): IPersistedWalletData | undefined { return get(activeProfile)?.walletPersistedData?.[walletId] } diff --git a/packages/shared/lib/core/profile/stores/active-wallets.store.ts b/packages/shared/lib/core/profile/stores/active-wallets.store.ts index 4b1b566860d..2de60f7b68c 100644 --- a/packages/shared/lib/core/profile/stores/active-wallets.store.ts +++ b/packages/shared/lib/core/profile/stores/active-wallets.store.ts @@ -1,10 +1,14 @@ -import { derived, Readable, writable } from 'svelte/store' +import { derived, get, Readable, writable } from 'svelte/store' import { IWalletState } from '@core/wallet/interfaces' import { activeProfile } from './active-profile.store' export const activeWallets = writable([]) -export function removewalletFromactiveWallets(walletId: string): void { +export function getActiveWallets(): IWalletState[] { + return get(activeWallets) +} + +export function removeWalletFromActiveWallets(walletId: string): void { activeWallets?.update((state) => state.filter((wallet) => wallet.id !== walletId)) } diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts b/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts index 71b005c7ffd..6e9a2a5bd0e 100644 --- a/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts @@ -1,4 +1,3 @@ -// TODO(2.0) Fix all usages and rename export function getSecretManagerPath(profileDirectory: string): string { return `${profileDirectory}/wallet.stronghold` } diff --git a/packages/shared/lib/core/wallet/actions/createNewWallet.ts b/packages/shared/lib/core/wallet/actions/createNewWallet.ts index 952c0421593..b5505350d2b 100644 --- a/packages/shared/lib/core/wallet/actions/createNewWallet.ts +++ b/packages/shared/lib/core/wallet/actions/createNewWallet.ts @@ -26,10 +26,8 @@ export async function createNewWallet(name?: string, color?: string): Promise { const wallet = get(activeWallets)?.find((wallet) => wallet.id === walletId) const output = payload.output diff --git a/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts b/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts index 75558bf6a35..2d647fbaf15 100644 --- a/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts +++ b/packages/shared/lib/core/wallet/actions/setSelectedWallet.ts @@ -6,7 +6,6 @@ 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) diff --git a/packages/shared/lib/core/wallet/enums/subject.enum.ts b/packages/shared/lib/core/wallet/enums/subject.enum.ts index 1ca8304f6ae..3b4f9535833 100644 --- a/packages/shared/lib/core/wallet/enums/subject.enum.ts +++ b/packages/shared/lib/core/wallet/enums/subject.enum.ts @@ -1,4 +1,4 @@ export enum SubjectType { - Wallet = 'wallet', // TODO(2.0) This should be Wallet? + Wallet = 'wallet', Address = 'address', } 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 index 456a51a869d..dddb20e4386 100644 --- a/packages/shared/lib/core/wallet/stores/selected-wallet-id.store.ts +++ b/packages/shared/lib/core/wallet/stores/selected-wallet-id.store.ts @@ -1,4 +1,3 @@ import { writable } from 'svelte/store' -// TODO(2.0) Fix all usages export const selectedWalletId = writable(null) diff --git a/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts b/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts index a72b8aedf34..2193bd17cd5 100644 --- a/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts +++ b/packages/shared/lib/core/wallet/utils/sumBalanceForWallets.ts @@ -1,6 +1,5 @@ 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/wallet/utils/sumTotalFromOutputs.ts b/packages/shared/lib/core/wallet/utils/sumTotalFromOutputs.ts index 74871861357..021c8fff081 100644 --- a/packages/shared/lib/core/wallet/utils/sumTotalFromOutputs.ts +++ b/packages/shared/lib/core/wallet/utils/sumTotalFromOutputs.ts @@ -1,6 +1,5 @@ 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/syncWalletsInSeries.ts b/packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts index 723d89ac9c5..560194647c6 100644 --- a/packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts +++ b/packages/shared/lib/core/wallet/utils/syncWalletsInSeries.ts @@ -1,7 +1,6 @@ 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) { diff --git a/packages/shared/lib/core/wallet/utils/validateWalletName.ts b/packages/shared/lib/core/wallet/utils/validateWalletName.ts index ac156f1ca59..6969cb553b2 100644 --- a/packages/shared/lib/core/wallet/utils/validateWalletName.ts +++ b/packages/shared/lib/core/wallet/utils/validateWalletName.ts @@ -4,7 +4,6 @@ import { getTrimmedLength } from '@core/utils' import { get } from 'svelte/store' import { MAX_WALLET_NAME_LENGTH } from '../constants' -// TODO(2.0) Fix all usages export function validateWalletName( name: string, validateLength = true, @@ -14,7 +13,6 @@ export function validateWalletName( return Promise.reject( new Error( localize('error.wallet.length', { - // TODO(2.0) Rename error code values: { length: MAX_WALLET_NAME_LENGTH, }, From 7637dbb1c2f9aa15a62ff1fbf9d50ee5b3916b2c Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 29 Jan 2024 16:04:40 +0100 Subject: [PATCH 23/37] more --- packages/desktop/electron/preload.js | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/desktop/electron/preload.js b/packages/desktop/electron/preload.js index eb08db5ae35..00ff2a1c226 100644 --- a/packages/desktop/electron/preload.js +++ b/packages/desktop/electron/preload.js @@ -132,7 +132,6 @@ try { } return wallet }, - // TODO(2.0): also remove from file system? Does it make sense? file system != memoery async deleteWallet(id) { if (id && id in wallets) { const wallet = wallets[id] From 73779d8d8f656722e014aec3d0d89133fe127951 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 29 Jan 2024 16:05:52 +0100 Subject: [PATCH 24/37] more --- packages/shared/lib/core/wallet/actions/prepareOutput.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/shared/lib/core/wallet/actions/prepareOutput.ts b/packages/shared/lib/core/wallet/actions/prepareOutput.ts index 4bda095ecc4..bec5496b06a 100644 --- a/packages/shared/lib/core/wallet/actions/prepareOutput.ts +++ b/packages/shared/lib/core/wallet/actions/prepareOutput.ts @@ -1,7 +1,6 @@ import { Output, OutputParams, TransactionOptions } from '@iota/sdk/out/types' import { getWallet } from '@core/profile' -// TODO(2.0) Fix all usages export async function prepareOutput( walletId: string, params: OutputParams, From 3673d25c7a0a16ad4b1da195c22f872b7ed53fb8 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Mon, 29 Jan 2024 16:18:21 +0100 Subject: [PATCH 25/37] more --- .../contexts/governance/stores/registered-proposals.store.ts | 1 - .../core/profile/actions/active-wallet/getWalletColorById.ts | 1 - .../shared/lib/core/profile/stores/active-wallets.store.ts | 4 ++-- packages/shared/lib/core/wallet/actions/getBalance.ts | 1 - .../lib/core/wallet/actions/getParticipationOverview.ts | 1 - packages/shared/lib/core/wallet/actions/getVotingPower.ts | 1 - .../shared/lib/core/wallet/actions/setNextSelectedWallet.ts | 1 - .../lib/core/wallet/actions/tryCreateAdditionalWallet.ts | 1 - 8 files changed, 2 insertions(+), 9 deletions(-) diff --git a/packages/shared/lib/contexts/governance/stores/registered-proposals.store.ts b/packages/shared/lib/contexts/governance/stores/registered-proposals.store.ts index f4ca89ed706..c60536293ca 100644 --- a/packages/shared/lib/contexts/governance/stores/registered-proposals.store.ts +++ b/packages/shared/lib/contexts/governance/stores/registered-proposals.store.ts @@ -6,7 +6,6 @@ import { getProposalStatusForMilestone } from '../utils' export const registeredProposals = writable<{ [walletId: string]: IRegisteredProposals }>({}) -// TODO(2.0) Rename this export const registeredProposalsForSelectedWallet: Readable<{ [proposalId: string]: IProposal }> = derived( [selectedWalletId, registeredProposals, networkStatus], ([$selectedWalletId, $registeredProposals, $networkStatus]) => { diff --git a/packages/shared/lib/core/profile/actions/active-wallet/getWalletColorById.ts b/packages/shared/lib/core/profile/actions/active-wallet/getWalletColorById.ts index 8acb27fb37a..b299236f7af 100644 --- a/packages/shared/lib/core/profile/actions/active-wallet/getWalletColorById.ts +++ b/packages/shared/lib/core/profile/actions/active-wallet/getWalletColorById.ts @@ -1,7 +1,6 @@ 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/stores/active-wallets.store.ts b/packages/shared/lib/core/profile/stores/active-wallets.store.ts index 2de60f7b68c..09bc5468394 100644 --- a/packages/shared/lib/core/profile/stores/active-wallets.store.ts +++ b/packages/shared/lib/core/profile/stores/active-wallets.store.ts @@ -27,7 +27,7 @@ export const nonHiddenActiveWallets: Readable = derived([activeW return [] } const unsortedNonHiddenwallets = $activeWallets?.filter((wallet) => !wallet?.hidden) - return unsortedNonHiddenwallets // TODO(2.0): Sort them: .sort((a, b) => a.index - b.index) + return unsortedNonHiddenwallets }) export const visibleActiveWallets: Readable = derived( @@ -40,6 +40,6 @@ export const visibleActiveWallets: Readable = derived( $activeProfile?.showHiddenWallets ?? false ? $activeWallets : $activeWallets?.filter((wallet) => !wallet?.hidden) - return unsortedVisiblewallets // TODO(2.0): Sort them: .sort((a, b) => a.index - b.index) + return unsortedVisiblewallets } ) diff --git a/packages/shared/lib/core/wallet/actions/getBalance.ts b/packages/shared/lib/core/wallet/actions/getBalance.ts index 98c24fcbf53..101a2880bd2 100644 --- a/packages/shared/lib/core/wallet/actions/getBalance.ts +++ b/packages/shared/lib/core/wallet/actions/getBalance.ts @@ -1,7 +1,6 @@ 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 index 7aeeea578eb..9ffe627e939 100644 --- a/packages/shared/lib/core/wallet/actions/getParticipationOverview.ts +++ b/packages/shared/lib/core/wallet/actions/getParticipationOverview.ts @@ -1,7 +1,6 @@ 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 index 3d3001c0c6a..97bb0aadbc3 100644 --- a/packages/shared/lib/core/wallet/actions/getVotingPower.ts +++ b/packages/shared/lib/core/wallet/actions/getVotingPower.ts @@ -1,6 +1,5 @@ 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/setNextSelectedWallet.ts b/packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts index da7416b4ba7..603ce34a799 100644 --- a/packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts +++ b/packages/shared/lib/core/wallet/actions/setNextSelectedWallet.ts @@ -3,7 +3,6 @@ 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) diff --git a/packages/shared/lib/core/wallet/actions/tryCreateAdditionalWallet.ts b/packages/shared/lib/core/wallet/actions/tryCreateAdditionalWallet.ts index 9f40fb1a6e7..7e0d08acbfd 100644 --- a/packages/shared/lib/core/wallet/actions/tryCreateAdditionalWallet.ts +++ b/packages/shared/lib/core/wallet/actions/tryCreateAdditionalWallet.ts @@ -10,7 +10,6 @@ import { createNewWallet } from './createNewWallet' import { setSelectedWallet } from './setSelectedWallet' import { IError } from '@core/error/interfaces' -// TODO(2.0) Fix all usages export async function tryCreateAdditionalWallet(alias: string, color: string): Promise { try { const wallet = await createNewWallet(alias, color) From 6e8dcd5870f7677bc52b85c81cf3e2088f854839 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Tue, 30 Jan 2024 10:19:37 +0100 Subject: [PATCH 26/37] works --- .../views/ChooseCreateProfileFlowView.svelte | 6 +-- .../actions/completeOnboardingProcess.ts | 2 +- ...aliseOnboardingProfileWithSecretManager.ts | 7 ++-- .../actions/active-profile/loadWallets.ts | 6 ++- .../lib/core/profile/actions/createWallet.ts | 40 +++++++++---------- .../utils/getSecretManagerFromProfileType.ts | 5 +-- .../getStorageDirectoryOfSecretManager.ts | 6 +++ .../shared/lib/core/profile/utils/index.ts | 1 + .../buildWalletStateAndPersistedData.ts | 14 +++++-- .../core/wallet/actions/createNewWallet.ts | 14 +++++-- .../lib/core/wallet/actions/loadWallet.ts | 4 +- 11 files changed, 63 insertions(+), 42 deletions(-) create mode 100644 packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts 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 fe06b7a4882..0cb6c4a9c12 100644 --- a/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte +++ b/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte @@ -6,7 +6,7 @@ ProfileType, clearProfileFromMemory, getSecretManagerFromProfileType, - getStorageDirectoryOfProfile, + getStorageDirectoryOfSecretManager, removeProfileFolder, } from '@core/profile' import features from '@features/features' @@ -28,8 +28,8 @@ async function onProfileTypeClick(createProfileType: CreateProfileType): Promise { isBusy = { ...isBusy, [createProfileType]: true } const type = createProfileType === CreateProfileType.Ledger ? ProfileType.Ledger : ProfileType.Software - const storagePath = await getStorageDirectoryOfProfile($onboardingProfile.id) - const secretManagerOptions = getSecretManagerFromProfileType(type, storagePath) + const secretManagerPath = await getStorageDirectoryOfSecretManager($onboardingProfile.id) + const secretManagerOptions = getSecretManagerFromProfileType(type, secretManagerPath) updateOnboardingProfile({ createProfileType, type, secretManagerOptions }) $createProfileRouter.next() } diff --git a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts index 8564649bbab..9cb4c85e3df 100644 --- a/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts +++ b/packages/shared/lib/contexts/onboarding/actions/completeOnboardingProcess.ts @@ -55,7 +55,7 @@ export async function initWallet(profile: IOnboardingProfile, strongholdPassword await wallet.sync(DEFAULT_SYNC_OPTIONS) // 4. Create a wrapper over the wallet instance and the persisted data - const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName) + const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(profile.id, wallet, walletName) addWalletToActiveWallets(walletState) addWalletPersistedDataToActiveProfile(walletState.id, walletPersistedData) diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts index fdd4a07790c..27f0f2ebd5d 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts @@ -1,6 +1,6 @@ import { get } from 'svelte/store' import { onboardingProfileSecretManager } from '../stores' -import { getSecretManagerFromProfileType, getStorageDirectoryOfProfile, removeProfileFolder } from '@core/profile' +import { getSecretManagerFromProfileType, getStorageDirectoryOfSecretManager, removeProfileFolder } from '@core/profile' import { onboardingProfile, updateOnboardingProfile } from '../stores' export async function initialiseOnboardingProfileWithSecretManager( @@ -21,9 +21,8 @@ export async function initialiseOnboardingProfileWithSecretManager( } } - const storagePath = await getStorageDirectoryOfProfile(activeOnboardingProfile.id) - - const secretManagerOptions = getSecretManagerFromProfileType(activeOnboardingProfile.type, storagePath) + const secretManagerPath = await getStorageDirectoryOfSecretManager(activeOnboardingProfile.id) + const secretManagerOptions = getSecretManagerFromProfileType(activeOnboardingProfile.type, secretManagerPath) updateOnboardingProfile({ secretManagerOptions }) } diff --git a/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts b/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts index 5c1f3da229e..833ba3f23ac 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/loadWallets.ts @@ -4,14 +4,16 @@ import { activeWallets, activeProfile } from '../../stores' import { getWallets } from '../getWallets' export async function loadWallets(): Promise { - const { hasLoadedWallets } = get(activeProfile) + const { hasLoadedWallets, id } = get(activeProfile) const walletsResponse = await getWallets() if (walletsResponse.length === 0) { hasLoadedWallets.set(true) return } if (walletsResponse) { - const loadedWallets = await Promise.all(walletsResponse?.map((walletResponse) => loadWallet(walletResponse))) + const loadedWallets = await Promise.all( + walletsResponse?.map((walletResponse) => loadWallet(id, walletResponse)) + ) activeWallets.set(loadedWallets) hasLoadedWallets.set(true) } diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index 9256e8c199a..3e340266dda 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -1,14 +1,24 @@ import { api } from '@core/api' import { IPersistedProfile, IWallet } from '../interfaces' -import { getSecretManagerFromProfileType, getStorageDirectoryOfProfile } from '../utils' +import { + getSecretManagerFromProfileType, + getStorageDirectoryOfSecretManager, + getStorageDirectoryOfWallet, +} from '../utils' import { WalletOptions } from '@iota/sdk' import { selectedWalletId } from '../../wallet' +import { generateRandomId } from '../../utils' -export function getWalletOptions(profile: IPersistedProfile, storagePath: string, password?: string): WalletOptions { +export function getWalletOptions( + profile: IPersistedProfile, + storagePath: string, + secretManagerPath: string, + password?: string +): WalletOptions { return { clientOptions: profile.clientOptions, storagePath, - secretManager: getSecretManagerFromProfileType(profile.type, storagePath, password), + secretManager: getSecretManagerFromProfileType(profile.type, secretManagerPath, password), bipPath: { coinType: profile.network.coinType, account: 0, @@ -17,25 +27,15 @@ export function getWalletOptions(profile: IPersistedProfile, storagePath: string } } -// TODO(2.0): Fix and finish this method -/* - __storage__/ - - profile_id_1 - - secret manager - - __wallet1__/ - - __wallet2__/ -*/ - export async function createWallet(profile: IPersistedProfile, password?: string): Promise { - const storagePath = await getStorageDirectoryOfProfile(profile.id) + const walletId = generateRandomId() + const walletDBPath = await getStorageDirectoryOfWallet(profile.id, walletId) + const secretManagerPath = await getStorageDirectoryOfSecretManager(profile.id) + const walletOptions = getWalletOptions(profile, walletDBPath, secretManagerPath, password) - const walletOptions = getWalletOptions(profile, storagePath, password) - // TODO(2.0) It is weird to use the profile ID as the wallet ID, - // we should probably have one for wallet and another one for the profile - const wallet = await api.getWallet(profile.id, { - ...walletOptions, - storagePath, - }) + const wallet = await api.getWallet(walletId, walletOptions) + + selectedWalletId.set(walletId) - selectedWalletId.set(profile.id) return wallet } diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts index c9c47370b57..13a43d373f5 100644 --- a/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts +++ b/packages/shared/lib/core/profile/utils/getSecretManagerFromProfileType.ts @@ -3,14 +3,13 @@ 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, + strongholdPath?: string, password?: string ): SecretManagerType { const strongholdSecretManager = { - stronghold: { snapshotPath: `${storagePath}/wallet.stronghold`, password }, + stronghold: { snapshotPath: `${strongholdPath}/wallet.stronghold`, password }, } const ledgerSecretManager = { ledgerNano: USE_LEDGER_SIMULATOR, diff --git a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts new file mode 100644 index 00000000000..d4a42a0d32a --- /dev/null +++ b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts @@ -0,0 +1,6 @@ +import { getStorageDirectoryOfProfile } from './getStorageDirectoryOfProfile' + +export const getStorageDirectoryOfSecretManager = async (profileId: string): Promise => { + const profilePath = await getStorageDirectoryOfProfile(profileId) + return `${profilePath}/secret-manager` +} diff --git a/packages/shared/lib/core/profile/utils/index.ts b/packages/shared/lib/core/profile/utils/index.ts index 97cf12e8298..7f40c940b64 100644 --- a/packages/shared/lib/core/profile/utils/index.ts +++ b/packages/shared/lib/core/profile/utils/index.ts @@ -7,3 +7,4 @@ export * from './validateProfileName' export * from './getSecretManagerPath' export * from './getSecretManagerFromProfileType' export * from './getStorageDirectoryOfWallet' +export * from './getStorageDirectoryOfSecretManager' diff --git a/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts b/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts index f4356ac9333..e9142326908 100644 --- a/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts +++ b/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts @@ -4,16 +4,24 @@ import { IWallet } from '@core/profile/interfaces' import { IWalletState } from '../interfaces/wallet-state.interface' import { IPersistedWalletData } from '../interfaces/persisted-wallet-data.interface' import { buildWalletState } from './buildWalletState' -import { activeProfile, getStorageDirectoryOfProfile, getWalletOptions } from '@core/profile' +import { + activeProfile, + getStorageDirectoryOfSecretManager, + getStorageDirectoryOfWallet, + getWalletOptions, +} from '@core/profile' import { get } from 'svelte/store' export async function buildWalletStateAndPersistedData( + profileId: string, wallet: IWallet, name?: string, color?: string ): Promise<[IWalletState, IPersistedWalletData]> { - const storagePath = await getStorageDirectoryOfProfile(wallet.id) - const walletOptions = getWalletOptions(get(activeProfile), storagePath) + const storagePath = await getStorageDirectoryOfWallet(profileId, wallet.id) + const secretManagerPath = await getStorageDirectoryOfSecretManager(profileId) + + const walletOptions = getWalletOptions(get(activeProfile), storagePath, secretManagerPath) const persistedWalletData: IPersistedWalletData = { name: name || `${localize('general.wallet')}`, diff --git a/packages/shared/lib/core/wallet/actions/createNewWallet.ts b/packages/shared/lib/core/wallet/actions/createNewWallet.ts index b5505350d2b..859c1cc1ca3 100644 --- a/packages/shared/lib/core/wallet/actions/createNewWallet.ts +++ b/packages/shared/lib/core/wallet/actions/createNewWallet.ts @@ -4,27 +4,33 @@ import { addWalletPersistedDataToActiveProfile, addWalletToActiveWallets, createWallet, + getActiveProfile, } from '@core/profile' import { get } from 'svelte/store' - import { DEFAULT_SYNC_OPTIONS } from '@core/wallet/constants' import { IWalletState } from '@core/wallet/interfaces' - import { buildWalletStateAndPersistedData } from './buildWalletStateAndPersistedData' import { addEmptyWalletActivitiesToAllWalletActivities } from '../stores' export async function createNewWallet(name?: string, color?: string): Promise { + const activeProfile = getActiveProfile() + // 1. Get the wallet name const walletName = name || `${localize('general.wallet')} ${(get(activeWallets)?.length ?? 0) + 1}` // 2. Create the wallet instance - const wallet = await createWallet() + const wallet = await createWallet(activeProfile) // 3. Sync the wallet with the Node await wallet.sync(DEFAULT_SYNC_OPTIONS) // 4. Create a wrapper over the wallet instance and the persisted data - const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet, walletName, color) + const [walletState, walletPersistedData] = await buildWalletStateAndPersistedData( + activeProfile.id, + wallet, + walletName, + color + ) addWalletToActiveWallets(walletState) addWalletPersistedDataToActiveProfile(walletState.id, walletPersistedData) diff --git a/packages/shared/lib/core/wallet/actions/loadWallet.ts b/packages/shared/lib/core/wallet/actions/loadWallet.ts index 42172f8496c..4d679a7bc32 100644 --- a/packages/shared/lib/core/wallet/actions/loadWallet.ts +++ b/packages/shared/lib/core/wallet/actions/loadWallet.ts @@ -4,7 +4,7 @@ import { IWalletState } from '../interfaces' import { buildWalletStateAndPersistedData } from './buildWalletStateAndPersistedData' import { buildWalletState } from './buildWalletState' -export async function loadWallet(wallet: IWallet): Promise { +export async function loadWallet(profileId: string, wallet: IWallet): Promise { const walletId = wallet.id await wallet.sync(DEFAULT_SYNC_OPTIONS) const walletPersistedData = getActiveProfilePersistedWalletData(walletId) @@ -13,7 +13,7 @@ export async function loadWallet(wallet: IWallet): Promise { if (walletPersistedData) { accountState = await buildWalletState(wallet, walletPersistedData) } else { - const [newAccountState, walletPersistedData] = await buildWalletStateAndPersistedData(wallet) + const [newAccountState, walletPersistedData] = await buildWalletStateAndPersistedData(profileId, wallet) addWalletPersistedDataToActiveProfile(walletId, walletPersistedData) accountState = newAccountState } From 72383a784939866eb0562fa21de7c6b98e611615 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 08:44:57 +0100 Subject: [PATCH 27/37] clean up --- .../shared/lib/core/api/interfaces/api.interface.ts | 10 +++++----- .../lib/core/profile/stores/active-wallets.store.ts | 7 +++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts index 40c413a87da..9e53f17aa96 100644 --- a/packages/shared/lib/core/api/interfaces/api.interface.ts +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -28,16 +28,16 @@ export interface IApi { ): Promise migrateDbChrysalisToStardust(path: string, pinCode: string): Promise> // Mapped from sdk#Utils - generateMnemonic(): Promise - verifyMnemonic(mnemonic: string): Promise + generateMnemonic(): string + verifyMnemonic(mnemonic: string): void hexToBech32(hex: HexEncodedString, bech32Hrp: string): Bech32Address bech32ToHex(bech32: Bech32Address): HexEncodedString computeAccountId(outputId: string): AccountId - computeFoundryId(accountId: AccountId, serialNumber: number, tokenSchemeType: number): Promise + computeFoundryId(accountId: AccountId, serialNumber: number, tokenSchemeType: number): FoundryId 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 + computeOutputId(id: TransactionId, index: number): OutputId + outputHexBytes(output: Output): HexEncodedString } diff --git a/packages/shared/lib/core/profile/stores/active-wallets.store.ts b/packages/shared/lib/core/profile/stores/active-wallets.store.ts index 09bc5468394..b6a0a7dddb0 100644 --- a/packages/shared/lib/core/profile/stores/active-wallets.store.ts +++ b/packages/shared/lib/core/profile/stores/active-wallets.store.ts @@ -26,8 +26,7 @@ export const nonHiddenActiveWallets: Readable = derived([activeW if (!$activeWallets) { return [] } - const unsortedNonHiddenwallets = $activeWallets?.filter((wallet) => !wallet?.hidden) - return unsortedNonHiddenwallets + return $activeWallets?.filter((wallet) => !wallet?.hidden) }) export const visibleActiveWallets: Readable = derived( @@ -36,10 +35,10 @@ export const visibleActiveWallets: Readable = derived( if (!$activeWallets || !$activeProfile) { return [] } - const unsortedVisiblewallets = + const visibleWallets = $activeProfile?.showHiddenWallets ?? false ? $activeWallets : $activeWallets?.filter((wallet) => !wallet?.hidden) - return unsortedVisiblewallets + return visibleWallets } ) From d4dc55c7a090d6c9f85d52e1fc6075a1c7bed126 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 08:48:38 +0100 Subject: [PATCH 28/37] clean up --- packages/shared/lib/core/api/interfaces/api.interface.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/shared/lib/core/api/interfaces/api.interface.ts b/packages/shared/lib/core/api/interfaces/api.interface.ts index 9e53f17aa96..70baa8eddfa 100644 --- a/packages/shared/lib/core/api/interfaces/api.interface.ts +++ b/packages/shared/lib/core/api/interfaces/api.interface.ts @@ -17,9 +17,9 @@ export interface IApi { getClientFromWallet(id: string): Promise createSecretManager(options: SecretManagerType): Promise createWallet(id: string, payload: WalletOptions): Promise - deleteWallet(id: string): void + deleteWallet(id: string): Promise getWallet(id: string, walletOptions: WalletOptions): Promise - clearWalletsFromMemory(): void + clearWalletsFromMemory(): Promise migrateStrongholdSnapshotV2ToV3( currentPath: string, currentPassword: string, From 599a98facbc2eac1008ed9691f46c6c8ba9a2d60 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 08:56:44 +0100 Subject: [PATCH 29/37] clean up --- .../popups/send/SendConfirmationPopup.svelte | 4 ++-- .../views/advanced/HiddenAccounts.svelte | 17 ----------------- .../components/inputs/RecipientInput.svelte | 5 +++-- .../icon/constants/settings-icon-svg.ts | 2 +- ...y-profile-manager-directory-name.constant.ts | 1 - .../chrysalis-persisted-profile.interface.ts | 2 +- .../settings/advanced-settings-route.enum.ts | 2 +- packages/shared/locales/en.json | 8 ++++---- 8 files changed, 12 insertions(+), 29 deletions(-) delete mode 100644 packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte delete mode 100644 packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts diff --git a/packages/desktop/components/popups/send/SendConfirmationPopup.svelte b/packages/desktop/components/popups/send/SendConfirmationPopup.svelte index 023bf2d8bfa..e66a834d4e9 100644 --- a/packages/desktop/components/popups/send/SendConfirmationPopup.svelte +++ b/packages/desktop/components/popups/send/SendConfirmationPopup.svelte @@ -7,7 +7,7 @@ import { checkActiveProfileAuth, isActiveLedgerProfile } from '@core/profile' import { TimePeriod } from '@core/utils' import { sendOutput } from '@core/wallet/actions' - import { TokenStandard } from '@core/wallet/enums' + import { SubjectType, TokenStandard } from '@core/wallet/enums' import { NewTransactionType, newTransactionDetails, updateNewTransactionDetails } from '@core/wallet/stores' import { NewTokenTransactionDetails, NftActivity, TransactionActivity, VestingActivity } from '@core/wallet/types' import { @@ -66,7 +66,7 @@ $: isBaseTokenTransfer = transactionDetails.type === NewTransactionType.TokenTransfer && transactionDetails.asset?.metadata?.standard === TokenStandard.BaseToken - $: isInternal = recipient.type === 'wallet' + $: isInternal = recipient.type === SubjectType.Wallet $: isLayer2Transaction = !!layer2Parameters $: isTransferring = $selectedWallet.isTransferring $: hideGiftToggle = isBaseTokenTransfer || isLayer2Transaction || (disableToggleGift && !giftStorageDeposit) diff --git a/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte b/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte deleted file mode 100644 index ce386e4fb99..00000000000 --- a/packages/desktop/views/dashboard/settings/views/advanced/HiddenAccounts.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - -{localize('views.settings.hiddenAccounts.title')} -{localize('views.settings.hiddenAccounts.description')} - diff --git a/packages/shared/components/inputs/RecipientInput.svelte b/packages/shared/components/inputs/RecipientInput.svelte index 257d0c4a6a1..dba8f10260b 100644 --- a/packages/shared/components/inputs/RecipientInput.svelte +++ b/packages/shared/components/inputs/RecipientInput.svelte @@ -7,6 +7,7 @@ import { Layer1RecipientError } from '@core/layer-2/errors' import { getNetworkHrp, getWalletColorById, visibleActiveWallets } from '@core/profile' import { selectedWalletId } from '@core/wallet/stores' + import { SubjectType } from 'shared/lib/core/wallet' export let recipient: Subject export let disabled = false @@ -17,7 +18,7 @@ let error: string let selected: IOption = - recipient?.type === 'wallet' + recipient?.type === SubjectType.Wallet ? { key: recipient.wallet.name, value: recipient.wallet.depositAddress } : { value: recipient?.address } @@ -37,7 +38,7 @@ } else { validateBech32Address(getNetworkHrp(), recipient?.address) } - } else if (recipient?.type === 'wallet') { + } else if (recipient?.type === SubjectType.Wallet) { if (isLayer2) { throw new Layer1RecipientError() } diff --git a/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts b/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts index 6ad00566a50..2b7d9f3ceb2 100644 --- a/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts +++ b/packages/shared/lib/auxiliary/icon/constants/settings-icon-svg.ts @@ -31,7 +31,7 @@ export const SETTINGS_ICON_SVG = { [SecuritySettingsRoute.ChangePassword]: Icon.Lock2, [SecuritySettingsRoute.ChangePincode]: Icon.Lock, [AdvancedSettingsRoute.BalanceFinder]: Icon.Reset, - [AdvancedSettingsRoute.hiddenWallets]: Icon.View, + [AdvancedSettingsRoute.HiddenWallets]: Icon.View, [AdvancedSettingsRoute.DeveloperToggle]: Icon.Dev, [HelpAndInfoRoute.Diagnostics]: Icon.Tools, [HelpAndInfoRoute.ErrorLog]: Icon.Warning, diff --git a/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts b/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts deleted file mode 100644 index 8d405a33509..00000000000 --- a/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts +++ /dev/null @@ -1 +0,0 @@ -export const TEMPORARY_WALLET_DIRECTORY_NAME = 'temp' diff --git a/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts b/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts index a8ba0f29a73..2e76b031a9a 100644 --- a/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts +++ b/packages/shared/lib/core/profile/interfaces/chrysalis-persisted-profile.interface.ts @@ -18,7 +18,7 @@ export interface IChrysalisPersistedProfile { hasVisitedStaking?: boolean lastShimmerPeriodVisitedStaking?: number lastAssemblyPeriodVisitedStaking?: number - lastUsedAccountId?: string // TODO(2.0) Accounts are gone + lastUsedWalletId?: string accounts?: IChrysalisProfileAccount[] stakingRewards?: ChrysalisAccountStakingRewards[] hasFinishedSingleAccountGuide?: boolean diff --git a/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts b/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts index 1b3daa0c8b5..d716495bdf5 100644 --- a/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts +++ b/packages/shared/lib/core/router/enums/settings/advanced-settings-route.enum.ts @@ -1,5 +1,5 @@ export enum AdvancedSettingsRoute { BalanceFinder = 'balanceFinder', - hiddenWallets = 'hiddenWallets', + HiddenWallets = 'hiddenWallets', DeveloperToggle = 'developerToggle', } diff --git a/packages/shared/locales/en.json b/packages/shared/locales/en.json index 1ec0cbc087e..c559957271c 100644 --- a/packages/shared/locales/en.json +++ b/packages/shared/locales/en.json @@ -1191,7 +1191,7 @@ "addProposal": { "title": "Add proposal", "body": "Please provide the information listed below to add a proposal.", - "addToAllWallets": "Add the proposal to all accounts" + "addToAllWallets": "Add the proposal to all wallets" }, "editProposal": { "title": "Edit proposal", @@ -1341,8 +1341,8 @@ "refresh": "Refresh", "saveBackup": "Save Stronghold backup", "customizeAcount": "Customise wallet", - "hideAccount": "Hide wallet", - "showAccount": "Unhide wallet", + "hideWallet": "Hide wallet", + "showWallet": "Unhide wallet", "showDeleteWallet": "Delete wallet", "max": "Max", "addNode": "Add node", @@ -1628,7 +1628,7 @@ "notStaked": "Not staked", "stakedFunds": "Staked funds", "unstakedFunds": "Unstaked funds", - "accountColor": "Wallet color", + "walletColor": "Wallet color", "transactionTime": "Transaction time", "surplus": "Surplus", "storageDeposit": "Storage deposit", From c994e770f7d1e7f8f5589e648863a51a6934c4d0 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 11:41:02 +0100 Subject: [PATCH 30/37] chore: Simplify path management --- .../views/ChooseCreateProfileFlowView.svelte | 4 +-- .../createShimmerClaimingProfileManager.ts | 4 +-- .../actions/destroyShimmerClaimingWallet.ts | 6 ++-- ...aliseOnboardingProfileWithSecretManager.ts | 4 +-- .../migrateStrongholdFromOnboardingProfile.ts | 8 ++--- ...eBackupForShimmerClaimingProfileManager.ts | 8 ++--- .../restoreBackupFromStrongholdFile.ts | 4 +-- .../contexts/onboarding/constants/index.ts | 1 - ...profile-manager-directory-name.constant.ts | 1 - .../copyStrongholdFileToProfileDirectory.ts | 9 ++--- .../getTemporaryWalletStorageDirectory.ts | 7 ---- .../lib/contexts/onboarding/helpers/index.ts | 1 - .../migrateStrongholdFromActiveProfile.ts | 5 ++- .../lib/core/profile/actions/createWallet.ts | 21 +++++------ .../actions/profiles/cleanupEmptyProfiles.ts | 9 ++--- .../profiles/migrateDbChrysalisToStardust.ts | 4 +-- .../core/profile/classes/DirectoryManager.ts | 36 +++++++++++++++++++ .../shared/lib/core/profile/classes/index.ts | 1 + .../lib/core/profile/constants/index.ts | 1 + ...emporary-wallet-directory-name.constant.ts | 0 packages/shared/lib/core/profile/index.ts | 1 + .../profile/utils/getSecretManagerPath.ts | 3 -- .../utils/getStorageDirectoryOfProfile.ts | 6 ---- .../getStorageDirectoryOfSecretManager.ts | 6 ---- .../utils/getStorageDirectoryOfWallet.ts | 6 ---- .../shared/lib/core/profile/utils/index.ts | 5 --- .../core/profile/utils/removeProfileFolder.ts | 4 +-- .../buildWalletStateAndPersistedData.ts | 14 +++----- 28 files changed, 85 insertions(+), 94 deletions(-) delete mode 100644 packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts delete mode 100644 packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts create mode 100644 packages/shared/lib/core/profile/classes/DirectoryManager.ts create mode 100644 packages/shared/lib/core/profile/classes/index.ts rename packages/shared/lib/{contexts/onboarding => core/profile}/constants/temporary-wallet-directory-name.constant.ts (100%) delete mode 100644 packages/shared/lib/core/profile/utils/getSecretManagerPath.ts delete mode 100644 packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfile.ts delete mode 100644 packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts delete mode 100644 packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts 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 0cb6c4a9c12..de3fc244680 100644 --- a/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte +++ b/packages/desktop/views/onboarding/views/create-profile/views/ChooseCreateProfileFlowView.svelte @@ -6,7 +6,6 @@ ProfileType, clearProfileFromMemory, getSecretManagerFromProfileType, - getStorageDirectoryOfSecretManager, removeProfileFolder, } from '@core/profile' import features from '@features/features' @@ -15,6 +14,7 @@ import { createProfileRouter } from '../create-profile-router' import { Icon as IconEnum } from '@auxiliary/icon' import { AnimationEnum } from '@auxiliary/animation' + import { DirectoryManager } from '@core/profile/classes' let isBusy = { [CreateProfileType.Mnemonic]: false, @@ -28,7 +28,7 @@ async function onProfileTypeClick(createProfileType: CreateProfileType): Promise { isBusy = { ...isBusy, [createProfileType]: true } const type = createProfileType === CreateProfileType.Ledger ? ProfileType.Ledger : ProfileType.Software - const secretManagerPath = await getStorageDirectoryOfSecretManager($onboardingProfile.id) + const secretManagerPath = await DirectoryManager.forSecretManager($onboardingProfile.id) const secretManagerOptions = getSecretManagerFromProfileType(type, secretManagerPath) updateOnboardingProfile({ createProfileType, type, secretManagerOptions }) $createProfileRouter.next() diff --git a/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts index 4291f378b4b..8a6b00a7a3a 100644 --- a/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/createShimmerClaimingProfileManager.ts @@ -4,8 +4,8 @@ import { generateRandomId } from '@core/utils' import { getSecretManagerFromProfileType } from '@core/profile' import { get } from 'svelte/store' import { RestoreProfileType } from '../enums' -import { getTemporaryWalletStorageDirectory } from '../helpers' import { onboardingProfile, shimmerClaimingProfileManager } from '../stores' +import { DirectoryManager } from '@core/profile/classes' // TODO(2.0): Fix all shimmer claiming and rename this export async function createShimmerClaimingProfileManager(): Promise { @@ -14,7 +14,7 @@ export async function createShimmerClaimingProfileManager(): Promise { return } - const storagePath = await getTemporaryWalletStorageDirectory() + const storagePath = await DirectoryManager.forTemporaryWallet() const coinType = COIN_TYPE[NetworkId.Iota] const clientOptions = $onboardingProfile?.clientOptions const secretManager = getSecretManagerFromProfileType($onboardingProfile?.type, storagePath) diff --git a/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts b/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts index 6689a014f28..990aee3bd59 100644 --- a/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts +++ b/packages/shared/lib/contexts/onboarding/actions/destroyShimmerClaimingWallet.ts @@ -1,10 +1,10 @@ import { get } from 'svelte/store' -import { Platform } from '@core/app' +import { Platform } from '@core/app/classes' -import { getTemporaryWalletStorageDirectory } from '../helpers' import { shimmerClaimingProfileManager } from '../stores' import { clearProfileFromMemory } from '@core/profile/actions' +import { DirectoryManager } from '@core/profile/classes' // TODO(2.0) Fix this @@ -14,6 +14,6 @@ export async function destroyShimmerClaimingWallet(): Promise { return } await clearProfileFromMemory(shimmerClaimingProfileManager) - const profilePath = await getTemporaryWalletStorageDirectory() + const profilePath = await DirectoryManager.forTemporaryWallet() await Platform.removeProfileFolder(profilePath) } diff --git a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts index 27f0f2ebd5d..673d7246268 100644 --- a/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/initialiseOnboardingProfileWithSecretManager.ts @@ -1,6 +1,6 @@ import { get } from 'svelte/store' import { onboardingProfileSecretManager } from '../stores' -import { getSecretManagerFromProfileType, getStorageDirectoryOfSecretManager, removeProfileFolder } from '@core/profile' +import { getSecretManagerFromProfileType, removeProfileFolder, DirectoryManager } from '@core/profile' import { onboardingProfile, updateOnboardingProfile } from '../stores' export async function initialiseOnboardingProfileWithSecretManager( @@ -21,7 +21,7 @@ export async function initialiseOnboardingProfileWithSecretManager( } } - const secretManagerPath = await getStorageDirectoryOfSecretManager(activeOnboardingProfile.id) + const secretManagerPath = await DirectoryManager.forSecretManager(activeOnboardingProfile.id) const secretManagerOptions = getSecretManagerFromProfileType(activeOnboardingProfile.type, secretManagerPath) updateOnboardingProfile({ secretManagerOptions }) diff --git a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts index d6e9dde83b0..1ca4dfedfc3 100644 --- a/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/migrateStrongholdFromOnboardingProfile.ts @@ -1,21 +1,19 @@ import { get } from 'svelte/store' -import { getSecretManagerPath, getStorageDirectoryOfProfile } from '@core/profile/utils' import { StrongholdVersion } from '@core/stronghold/enums' import { copyStrongholdFileToProfileDirectory } from '../helpers' import { onboardingProfile, updateOnboardingProfile } from '../stores' import { initialiseOnboardingProfileWithSecretManager } from './initialiseOnboardingProfileWithSecretManager' import { api } from '@core/api' -import { clearProfileFromMemory } from '@core/profile' +import { clearProfileFromMemory, DirectoryManager } from '@core/profile' export async function migrateStrongholdFromOnboardingProfile(password: string): Promise { const profile = get(onboardingProfile) - const profileDirectory = await getStorageDirectoryOfProfile(profile?.id) - const secretManagerPath = getSecretManagerPath(profileDirectory) + const secretManagerPath = await DirectoryManager.forStronghold(profile?.id) - await copyStrongholdFileToProfileDirectory(profileDirectory, profile?.importFilePath ?? '') + await copyStrongholdFileToProfileDirectory(profile?.id, profile?.importFilePath ?? '') updateOnboardingProfile({ strongholdPassword: password, importFilePath: secretManagerPath, importFile: null }) if (profile?.strongholdVersion === StrongholdVersion.V2) { diff --git a/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts b/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts index 35e335bb3a8..ae41f580397 100644 --- a/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts +++ b/packages/shared/lib/contexts/onboarding/actions/restoreBackupForShimmerClaimingProfileManager.ts @@ -1,14 +1,14 @@ import { NetworkId } from '@core/network/enums' -import { getStorageDirectoryOfProfile } from '@core/profile/utils' +import { DirectoryManager } from '@core/profile/classes' import { get } from 'svelte/store' -import { getTemporaryWalletStorageDirectory, restoreBackupByCopyingFile, validateStrongholdCoinType } from '../helpers' +import { restoreBackupByCopyingFile, validateStrongholdCoinType } from '../helpers' import { onboardingProfile, shimmerClaimingProfileManager } from '../stores' // TODO(2.0) Fix this export async function restoreBackupForShimmerClaimingProfileManager(strongholdPassword: string): Promise { try { const { id, importFilePath, clientOptions } = get(onboardingProfile) - const tempProfileDirectory = await getTemporaryWalletStorageDirectory() + const tempProfileDirectory = await DirectoryManager.forTemporaryWallet() await restoreBackupByCopyingFile( importFilePath, tempProfileDirectory, @@ -23,7 +23,7 @@ export async function restoreBackupForShimmerClaimingProfileManager(strongholdPa */ validateStrongholdCoinType(shimmerClaimingProfileManager, NetworkId.Iota) - const profileDirectory = await getStorageDirectoryOfProfile(id) + const profileDirectory = await DirectoryManager.forProfile(id) await restoreBackupByCopyingFile( importFilePath, profileDirectory, diff --git a/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts b/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts index 7e501d82525..6c65c766067 100644 --- a/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts +++ b/packages/shared/lib/contexts/onboarding/actions/restoreBackupFromStrongholdFile.ts @@ -1,4 +1,4 @@ -import { getStorageDirectoryOfProfile } from '@core/profile' +import { DirectoryManager } from '@core/profile/classes' import { restoreBackup } from '@core/wallet' import { get } from 'svelte/store' import { restoreBackupByCopyingFile } from '../helpers' @@ -11,7 +11,7 @@ export async function restoreBackupFromStrongholdFile(strongholdPassword: string try { await restoreBackup(importFilePath, strongholdPassword, network.protocol.bech32Hrp) } catch (err) { - const storageDirectory = await getStorageDirectoryOfProfile(id) + const storageDirectory = await DirectoryManager.forProfile(id) const secretManager = get(onboardingProfileSecretManager) await restoreBackupByCopyingFile(importFilePath, storageDirectory, strongholdPassword, secretManager) } diff --git a/packages/shared/lib/contexts/onboarding/constants/index.ts b/packages/shared/lib/contexts/onboarding/constants/index.ts index 1257eb313a5..89bac62d5fd 100644 --- a/packages/shared/lib/contexts/onboarding/constants/index.ts +++ b/packages/shared/lib/contexts/onboarding/constants/index.ts @@ -1,6 +1,5 @@ export * from './default-stronghold-password.constant' export * from './shimmer-claiming-account-recovery-configuration.constant' export * from './shimmer-claiming-account-sync-options.constant' -export * from './temporary-wallet-directory-name.constant' export * from './stronghold-regex.constant' export * from './shimmer-claim-default-transaction-options.constant' diff --git a/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts b/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts deleted file mode 100644 index 8d405a33509..00000000000 --- a/packages/shared/lib/contexts/onboarding/constants/temporary-profile-manager-directory-name.constant.ts +++ /dev/null @@ -1 +0,0 @@ -export const TEMPORARY_WALLET_DIRECTORY_NAME = 'temp' diff --git a/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts b/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts index 5e6b5e696ae..44abdd1982b 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/copyStrongholdFileToProfileDirectory.ts @@ -1,13 +1,10 @@ import { Platform } from '@core/app' -import { getSecretManagerPath } from '@core/profile/utils' import { UnableToCopyStrongholdBackupFileError } from '../errors' +import { DirectoryManager } from '@core/profile' -export async function copyStrongholdFileToProfileDirectory( - profileDirectory: string, - importFilePath: string -): Promise { +export async function copyStrongholdFileToProfileDirectory(profileId: string, importFilePath: string): Promise { try { - const secretManagerPath = getSecretManagerPath(profileDirectory) + const secretManagerPath = await DirectoryManager.forStronghold(profileId) await Platform.copyFile(importFilePath, secretManagerPath) } catch (err) { console.error(err) diff --git a/packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts b/packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts deleted file mode 100644 index a594e3d2f2b..00000000000 --- a/packages/shared/lib/contexts/onboarding/helpers/getTemporaryWalletStorageDirectory.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { getStorageDirectoryOfProfiles } from '@core/profile' -import { TEMPORARY_WALLET_DIRECTORY_NAME } from '../constants' - -export async function getTemporaryWalletStorageDirectory(): Promise { - const storageDir = await getStorageDirectoryOfProfiles() - return `${storageDir}/${TEMPORARY_WALLET_DIRECTORY_NAME}` -} diff --git a/packages/shared/lib/contexts/onboarding/helpers/index.ts b/packages/shared/lib/contexts/onboarding/helpers/index.ts index 49a273d318c..6d6ac76a79f 100644 --- a/packages/shared/lib/contexts/onboarding/helpers/index.ts +++ b/packages/shared/lib/contexts/onboarding/helpers/index.ts @@ -3,7 +3,6 @@ export * from './convertOnboardingProfileToPersistedProfile' export * from './copyStrongholdFileToProfileDirectory' export * from './deriveShimmerClaimingWalletState' export * from './getSortedRenamedBoundAccounts' -export * from './getTemporaryWalletStorageDirectory' export * from './prepareShimmerClaimingAccount' export * from './restoreBackupByCopyingFile' export * from './validateStrongholdCoinType' diff --git a/packages/shared/lib/core/profile/actions/active-profile/migrateStrongholdFromActiveProfile.ts b/packages/shared/lib/core/profile/actions/active-profile/migrateStrongholdFromActiveProfile.ts index d125699ff6c..8acd0a3d604 100644 --- a/packages/shared/lib/core/profile/actions/active-profile/migrateStrongholdFromActiveProfile.ts +++ b/packages/shared/lib/core/profile/actions/active-profile/migrateStrongholdFromActiveProfile.ts @@ -1,12 +1,11 @@ import { StrongholdVersion } from '@core/stronghold/enums' -import { getSecretManagerPath, getStorageDirectoryOfProfile } from '../../utils' +import { DirectoryManager } from '@core/profile/classes' import { getActiveProfile, updateActiveProfile } from '../../stores' import { api } from '@core/api' export async function migrateStrongholdFromActiveProfile(password: string): Promise { const profile = getActiveProfile() - const profileDirectory = await getStorageDirectoryOfProfile(profile?.id) - const secretManagerPath = getSecretManagerPath(profileDirectory) + const secretManagerPath = await DirectoryManager.forSecretManager(profile?.id) if (!profile.strongholdVersion || profile.strongholdVersion === StrongholdVersion.V2) { await api.migrateStrongholdSnapshotV2ToV3(secretManagerPath, password, secretManagerPath, password) diff --git a/packages/shared/lib/core/profile/actions/createWallet.ts b/packages/shared/lib/core/profile/actions/createWallet.ts index 3e340266dda..9b5eeb060eb 100644 --- a/packages/shared/lib/core/profile/actions/createWallet.ts +++ b/packages/shared/lib/core/profile/actions/createWallet.ts @@ -1,23 +1,20 @@ import { api } from '@core/api' import { IPersistedProfile, IWallet } from '../interfaces' -import { - getSecretManagerFromProfileType, - getStorageDirectoryOfSecretManager, - getStorageDirectoryOfWallet, -} from '../utils' +import { getSecretManagerFromProfileType } from '../utils' import { WalletOptions } from '@iota/sdk' -import { selectedWalletId } from '../../wallet' -import { generateRandomId } from '../../utils' +import { selectedWalletId } from '@core/wallet' +import { generateRandomId } from '@core/utils' +import { DirectoryManager } from '@core/profile/classes' export function getWalletOptions( profile: IPersistedProfile, - storagePath: string, + walletPath: string, secretManagerPath: string, password?: string ): WalletOptions { return { clientOptions: profile.clientOptions, - storagePath, + storagePath: walletPath, secretManager: getSecretManagerFromProfileType(profile.type, secretManagerPath, password), bipPath: { coinType: profile.network.coinType, @@ -29,9 +26,9 @@ export function getWalletOptions( export async function createWallet(profile: IPersistedProfile, password?: string): Promise { const walletId = generateRandomId() - const walletDBPath = await getStorageDirectoryOfWallet(profile.id, walletId) - const secretManagerPath = await getStorageDirectoryOfSecretManager(profile.id) - const walletOptions = getWalletOptions(profile, walletDBPath, secretManagerPath, password) + const walletPath = await DirectoryManager.forWallet(profile.id, walletId) + const secretManagerPath = await DirectoryManager.forSecretManager(profile.id) + const walletOptions = getWalletOptions(profile, walletPath, secretManagerPath, password) const wallet = await api.getWallet(walletId, walletOptions) diff --git a/packages/shared/lib/core/profile/actions/profiles/cleanupEmptyProfiles.ts b/packages/shared/lib/core/profile/actions/profiles/cleanupEmptyProfiles.ts index 1bfd710f50f..0d6b7b67f05 100644 --- a/packages/shared/lib/core/profile/actions/profiles/cleanupEmptyProfiles.ts +++ b/packages/shared/lib/core/profile/actions/profiles/cleanupEmptyProfiles.ts @@ -1,7 +1,8 @@ -import { Platform } from '@core/app' +import { Platform } from '@core/app/classes' import { get } from 'svelte/store' import { profiles } from '../../stores' -import { getStorageDirectoryOfProfiles, removeProfileFolder } from '../../utils' +import { removeProfileFolder } from '../../utils' +import { DirectoryManager } from '../../classes' /** * Cleanup profile listed that have nothing stored and stored profiles not in app. @@ -10,8 +11,8 @@ import { getStorageDirectoryOfProfiles, removeProfileFolder } from '../../utils' */ export async function cleanupEmptyProfiles(): Promise { try { - const profileDataPath = await getStorageDirectoryOfProfiles() - const storedProfiles = await Platform.listProfileFolders(profileDataPath) + const profilesPath = await DirectoryManager.forProfiles() + const storedProfiles = await Platform.listProfileFolders(profilesPath) profiles.update((_profiles) => _profiles?.filter((_profile) => storedProfiles.includes(_profile?.id))) diff --git a/packages/shared/lib/core/profile/actions/profiles/migrateDbChrysalisToStardust.ts b/packages/shared/lib/core/profile/actions/profiles/migrateDbChrysalisToStardust.ts index daef79adb9e..d3b35bef0df 100644 --- a/packages/shared/lib/core/profile/actions/profiles/migrateDbChrysalisToStardust.ts +++ b/packages/shared/lib/core/profile/actions/profiles/migrateDbChrysalisToStardust.ts @@ -1,6 +1,6 @@ import { logAndNotifyError } from '@core/error/actions' import { updateProfile } from '@core/profile/stores' -import { getStorageDirectoryOfProfile } from '@core/profile/utils' +import { DirectoryManager } from '@core/profile/classes' import { api } from '@core/api' /** @@ -10,7 +10,7 @@ import { api } from '@core/api' * @returns A boolean indicating the migration outcome. */ export async function migrateDbChrysalisToStardust(profileId: string, pinCode: string): Promise { - const profileDirectory = await getStorageDirectoryOfProfile(profileId) + const profileDirectory = await DirectoryManager.forProfile(profileId) const response = await api.migrateDbChrysalisToStardust(profileDirectory, pinCode) if (response instanceof Error) { diff --git a/packages/shared/lib/core/profile/classes/DirectoryManager.ts b/packages/shared/lib/core/profile/classes/DirectoryManager.ts new file mode 100644 index 00000000000..c3b02a30154 --- /dev/null +++ b/packages/shared/lib/core/profile/classes/DirectoryManager.ts @@ -0,0 +1,36 @@ +import { Platform } from '@core/app/classes' +import { PROFILE_STORAGE_DIRECTORY, TEMPORARY_WALLET_DIRECTORY_NAME } from '../constants' + +class DirectoryManagerBase { + profilePathResolver: Promise + + constructor() { + this.profilePathResolver = Platform.getUserDataPath().then((profilesPath) => `${profilesPath}/${PROFILE_STORAGE_DIRECTORY}`) + } + + forProfiles(): Promise { + return this.profilePathResolver + } + + async forProfile(profileId: string): Promise { + return `${await this.profilePathResolver}/${profileId}` + } + + async forWallet(profileId: string, walletId: string): Promise { + return `${await this.forProfile(profileId)}/${walletId}` + } + + async forSecretManager(profileId: string): Promise { + return `${await this.forProfile(profileId)}/secret-manager` + } + + async forStronghold(profileId: string): Promise { + return `${await this.forSecretManager(profileId)}/wallet.stronghold` + } + + async forTemporaryWallet(): Promise { + return `${await this.profilePathResolver}/${TEMPORARY_WALLET_DIRECTORY_NAME}` + } +} + +export const DirectoryManager = new DirectoryManagerBase() diff --git a/packages/shared/lib/core/profile/classes/index.ts b/packages/shared/lib/core/profile/classes/index.ts new file mode 100644 index 00000000000..4f709979d7c --- /dev/null +++ b/packages/shared/lib/core/profile/classes/index.ts @@ -0,0 +1 @@ +export * from './DirectoryManager' diff --git a/packages/shared/lib/core/profile/constants/index.ts b/packages/shared/lib/core/profile/constants/index.ts index 469e58aa61d..c26a3d817e8 100644 --- a/packages/shared/lib/core/profile/constants/index.ts +++ b/packages/shared/lib/core/profile/constants/index.ts @@ -10,3 +10,4 @@ export * from './max-stronghold-password-length.constant' export * from './profile-storage-directory.constant' export * from './profile-version.constant' export * from './default_stronghold_password_timeout_in_minutes.constant' +export * from './temporary-wallet-directory-name.constant' diff --git a/packages/shared/lib/contexts/onboarding/constants/temporary-wallet-directory-name.constant.ts b/packages/shared/lib/core/profile/constants/temporary-wallet-directory-name.constant.ts similarity index 100% rename from packages/shared/lib/contexts/onboarding/constants/temporary-wallet-directory-name.constant.ts rename to packages/shared/lib/core/profile/constants/temporary-wallet-directory-name.constant.ts diff --git a/packages/shared/lib/core/profile/index.ts b/packages/shared/lib/core/profile/index.ts index 1636124d2c7..e0074200a31 100644 --- a/packages/shared/lib/core/profile/index.ts +++ b/packages/shared/lib/core/profile/index.ts @@ -6,3 +6,4 @@ export * from './interfaces' export * from './enums' export * from './types' export * from './utils' +export * from './classes' diff --git a/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts b/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts deleted file mode 100644 index 6e9a2a5bd0e..00000000000 --- a/packages/shared/lib/core/profile/utils/getSecretManagerPath.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function getSecretManagerPath(profileDirectory: string): string { - return `${profileDirectory}/wallet.stronghold` -} diff --git a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfile.ts b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfile.ts deleted file mode 100644 index 94b929b122a..00000000000 --- a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfile.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { getStorageDirectoryOfProfiles } from './getStorageDirectoryOfProfiles' - -export const getStorageDirectoryOfProfile = async (id: string): Promise => { - const profilesStorageDirectory = await getStorageDirectoryOfProfiles() - return `${profilesStorageDirectory}/${id}` -} diff --git a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts deleted file mode 100644 index d4a42a0d32a..00000000000 --- a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfSecretManager.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { getStorageDirectoryOfProfile } from './getStorageDirectoryOfProfile' - -export const getStorageDirectoryOfSecretManager = async (profileId: string): Promise => { - const profilePath = await getStorageDirectoryOfProfile(profileId) - return `${profilePath}/secret-manager` -} diff --git a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts deleted file mode 100644 index ec8fda43512..00000000000 --- a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfWallet.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { getStorageDirectoryOfProfile } from './getStorageDirectoryOfProfile' - -export const getStorageDirectoryOfWallet = async (profileId: string, walletId: string): Promise => { - const profilePath = await getStorageDirectoryOfProfile(profileId) - return `${profilePath}/${walletId}` -} diff --git a/packages/shared/lib/core/profile/utils/index.ts b/packages/shared/lib/core/profile/utils/index.ts index 7f40c940b64..60a6afea89b 100644 --- a/packages/shared/lib/core/profile/utils/index.ts +++ b/packages/shared/lib/core/profile/utils/index.ts @@ -1,10 +1,5 @@ -export * from './getStorageDirectoryOfProfile' -export * from './getStorageDirectoryOfProfiles' export * from './isLedgerProfile' export * from './removeProfileFolder' export * from './removeProfileFolder' export * from './validateProfileName' -export * from './getSecretManagerPath' export * from './getSecretManagerFromProfileType' -export * from './getStorageDirectoryOfWallet' -export * from './getStorageDirectoryOfSecretManager' diff --git a/packages/shared/lib/core/profile/utils/removeProfileFolder.ts b/packages/shared/lib/core/profile/utils/removeProfileFolder.ts index ceb4563e073..f610829d3af 100644 --- a/packages/shared/lib/core/profile/utils/removeProfileFolder.ts +++ b/packages/shared/lib/core/profile/utils/removeProfileFolder.ts @@ -1,5 +1,5 @@ import { Platform } from '@core/app' -import { getStorageDirectoryOfProfile } from '@core/profile' +import { DirectoryManager } from '../classes' /** * Remove the profile folder from storage @@ -9,7 +9,7 @@ import { getStorageDirectoryOfProfile } from '@core/profile' */ export const removeProfileFolder = async (id: string): Promise => { try { - const profileDataPath = await getStorageDirectoryOfProfile(id) + const profileDataPath = await DirectoryManager.forProfile(id) await Platform.removeProfileFolder(profileDataPath) } catch (err) { // TODO: improve error handling here diff --git a/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts b/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts index e9142326908..5d6cc9b3075 100644 --- a/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts +++ b/packages/shared/lib/core/wallet/actions/buildWalletStateAndPersistedData.ts @@ -4,13 +4,9 @@ import { IWallet } from '@core/profile/interfaces' import { IWalletState } from '../interfaces/wallet-state.interface' import { IPersistedWalletData } from '../interfaces/persisted-wallet-data.interface' import { buildWalletState } from './buildWalletState' -import { - activeProfile, - getStorageDirectoryOfSecretManager, - getStorageDirectoryOfWallet, - getWalletOptions, -} from '@core/profile' +import { activeProfile, getWalletOptions } from '@core/profile' import { get } from 'svelte/store' +import { DirectoryManager } from '@core/profile/classes' export async function buildWalletStateAndPersistedData( profileId: string, @@ -18,10 +14,10 @@ export async function buildWalletStateAndPersistedData( name?: string, color?: string ): Promise<[IWalletState, IPersistedWalletData]> { - const storagePath = await getStorageDirectoryOfWallet(profileId, wallet.id) - const secretManagerPath = await getStorageDirectoryOfSecretManager(profileId) + const walletPath = await DirectoryManager.forWallet(profileId, wallet.id) + const secretManagerPath = await DirectoryManager.forSecretManager(profileId) - const walletOptions = getWalletOptions(get(activeProfile), storagePath, secretManagerPath) + const walletOptions = getWalletOptions(get(activeProfile), walletPath, secretManagerPath) const persistedWalletData: IPersistedWalletData = { name: name || `${localize('general.wallet')}`, From 52c1e02d2562f6f5527b0d164c45774f87ef52a8 Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 11:47:30 +0100 Subject: [PATCH 31/37] fmt --- packages/shared/lib/core/profile/classes/DirectoryManager.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/shared/lib/core/profile/classes/DirectoryManager.ts b/packages/shared/lib/core/profile/classes/DirectoryManager.ts index c3b02a30154..c7ae70afc0e 100644 --- a/packages/shared/lib/core/profile/classes/DirectoryManager.ts +++ b/packages/shared/lib/core/profile/classes/DirectoryManager.ts @@ -5,7 +5,9 @@ class DirectoryManagerBase { profilePathResolver: Promise constructor() { - this.profilePathResolver = Platform.getUserDataPath().then((profilesPath) => `${profilesPath}/${PROFILE_STORAGE_DIRECTORY}`) + this.profilePathResolver = Platform.getUserDataPath().then( + (profilesPath) => `${profilesPath}/${PROFILE_STORAGE_DIRECTORY}` + ) } forProfiles(): Promise { From e901a4062d0a1922271eefcaf7e15d6977cc3d7c Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 12:17:33 +0100 Subject: [PATCH 32/37] chore: Adapt to sdk changes --- .../actions/initializeRegisteredProposals.ts | 39 ++++++++++--------- .../actions/registerParticipationEvents.ts | 37 +++++++++--------- .../getWalletAssetsForSelectedWallet.ts | 6 +-- .../refreshWalletAssetsForActiveProfile.ts | 6 +-- 4 files changed, 45 insertions(+), 43 deletions(-) diff --git a/packages/shared/lib/contexts/governance/actions/initializeRegisteredProposals.ts b/packages/shared/lib/contexts/governance/actions/initializeRegisteredProposals.ts index 9c5d7133ea2..aff18a0c03d 100644 --- a/packages/shared/lib/contexts/governance/actions/initializeRegisteredProposals.ts +++ b/packages/shared/lib/contexts/governance/actions/initializeRegisteredProposals.ts @@ -1,11 +1,11 @@ import { activeWallets } from 'shared/lib/core/profile' -import { getSelectedWallet, IWalletState } from 'shared/lib/core/wallet' +import { getSelectedWallet /* IWalletState*/ } from 'shared/lib/core/wallet' import { get } from 'svelte/store' import { IRegisteredProposals } from '../interfaces' import { registeredProposals } from '../stores' -import { createProposalFromError, createProposalFromEvent } from '../utils' -import { getWalletsParticipationEventStatusForEvent } from './getWalletsParticipationEventStatusForEvent' +// import { createProposalFromError, createProposalFromEvent } from '../utils' +// import { getWalletsParticipationEventStatusForEvent } from './getWalletsParticipationEventStatusForEvent' export async function initializeRegisteredProposals(): Promise { const allProposals: { [walletId: string]: IRegisteredProposals } = {} @@ -27,20 +27,21 @@ export async function initializeRegisteredProposals(): Promise { registeredProposals.set(allProposals) } -async function getParticipationEventsAndCreateProposalsForWallet(wallet: IWalletState): Promise { - const proposals: IRegisteredProposals = {} - const events = await wallet.getParticipationEvents() - for (const event of Object.values(events)) { - const proposal = createProposalFromEvent(event) - if (!getSelectedWallet()) { - break - } - try { - await getWalletsParticipationEventStatusForEvent(event.id, wallet) - proposals[event.id] = proposal - } catch (err) { - proposals[event.id] = createProposalFromError(proposal, err) - } - } - return proposals +// TODO: https://github.com/iotaledger/firefly/issues/7947 +async function getParticipationEventsAndCreateProposalsForWallet(/* wallet: IWalletState*/): Promise { + // const proposals: IRegisteredProposals = {} + // const events = await wallet.getParticipationEvents() + // for (const event of Object.values(events)) { + // const proposal = createProposalFromEvent(event) + // if (!getSelectedWallet()) { + // break + // } + // try { + // await getWalletsParticipationEventStatusForEvent(event.id, wallet) + // proposals[event.id] = proposal + // } catch (err) { + // proposals[event.id] = createProposalFromError(proposal, err) + // } + // } + return Promise.resolve({}) } diff --git a/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts b/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts index 63429b1c9a3..165fa925fd0 100644 --- a/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts +++ b/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts @@ -1,21 +1,22 @@ -import { ParticipationEventMap, ParticipationEventRegistrationOptions } from '@iota/sdk/out/types' -import { getSelectedWallet, IWalletState } from 'shared/lib/core/wallet' -import { addProposalsFromParticipationEventMap } from './addProposalsFromParticipationEventMap' +import { ParticipationEventMap /* ParticipationEventRegistrationOptions*/ } from '@iota/sdk/out/types' +// import { getSelectedWallet, IWalletState } from 'shared/lib/core/wallet' +// import { addProposalsFromParticipationEventMap } from './addProposalsFromParticipationEventMap' -export async function registerParticipationEvents( - registrationOptions: ParticipationEventRegistrationOptions, - wallet: IWalletState -): Promise { - let newRegistrationOptions = registrationOptions - const { removedProposalIds } = getSelectedWallet() ?? {} - if (removedProposalIds?.length > 0) { - newRegistrationOptions = { - ...registrationOptions, - eventsToIgnore: removedProposalIds ?? [], - } - } +// TODO: https://github.com/iotaledger/firefly/issues/7947 +export async function registerParticipationEvents(): Promise { +// registrationOptions: ParticipationEventRegistrationOptions, +// wallet: IWalletState + // let newRegistrationOptions = registrationOptions + // const { removedProposalIds } = getSelectedWallet() ?? {} + // if (removedProposalIds?.length > 0) { + // newRegistrationOptions = { + // ...registrationOptions, + // eventsToIgnore: removedProposalIds ?? [], + // } + // } - const eventMap = await wallet.registerParticipationEvents(newRegistrationOptions) - addProposalsFromParticipationEventMap(eventMap, wallet) - return eventMap + // const eventMap = await wallet.registerParticipationEvents(newRegistrationOptions) + // addProposalsFromParticipationEventMap(eventMap, wallet) + // return eventMap + return Promise.resolve({}) } diff --git a/packages/shared/lib/core/wallet/actions/getWalletAssetsForSelectedWallet.ts b/packages/shared/lib/core/wallet/actions/getWalletAssetsForSelectedWallet.ts index 3064dda07c6..d7deee71b74 100644 --- a/packages/shared/lib/core/wallet/actions/getWalletAssetsForSelectedWallet.ts +++ b/packages/shared/lib/core/wallet/actions/getWalletAssetsForSelectedWallet.ts @@ -38,9 +38,9 @@ function getWalletAssetForNetwork(marketCoinPrices: MarketCoinPrices, networkId: } const nativeTokens: IAsset[] = [] - const tokens = wallet?.balances?.nativeTokens ?? [] - for (const token of tokens) { - const persistedAsset = getAssetFromPersistedAssets(token.tokenId) + const tokens = wallet?.balances?.nativeTokens ?? {} + for (const [tokenId, token] of Object.entries(tokens)) { + const persistedAsset = getAssetFromPersistedAssets(tokenId) if (persistedAsset && persistedAsset?.metadata && isValidIrc30Token(persistedAsset.metadata)) { nativeTokens.push({ ...persistedAsset, diff --git a/packages/shared/lib/core/wallet/actions/refreshWalletAssetsForActiveProfile.ts b/packages/shared/lib/core/wallet/actions/refreshWalletAssetsForActiveProfile.ts index 8ae9d224a5b..3af2a0dc1bf 100644 --- a/packages/shared/lib/core/wallet/actions/refreshWalletAssetsForActiveProfile.ts +++ b/packages/shared/lib/core/wallet/actions/refreshWalletAssetsForActiveProfile.ts @@ -33,10 +33,10 @@ export async function refreshWalletAssetsForActiveProfile( const assets: IPersistedAsset[] = [] const wallets = get(activeWallets) for (const wallet of wallets) { - const tokens = wallet?.balances?.nativeTokens ?? [] - for (const token of tokens) { + const tokens = wallet?.balances?.nativeTokens ?? {} + for (const tokenId of Object.keys(tokens)) { try { - const persistedAsset = await getOrRequestAssetFromPersistedAssets(token.tokenId) + const persistedAsset = await getOrRequestAssetFromPersistedAssets(tokenId) if (persistedAsset) { if (keepVerificationStatus) { const verificationStatus = storedVerificationStates[persistedAsset.id] From 442cfbda83393a26c984356742b3a2767d09281c Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 12:58:41 +0100 Subject: [PATCH 33/37] fmt --- .../governance/actions/registerParticipationEvents.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts b/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts index 165fa925fd0..fd3aa33c32f 100644 --- a/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts +++ b/packages/shared/lib/contexts/governance/actions/registerParticipationEvents.ts @@ -4,8 +4,8 @@ import { ParticipationEventMap /* ParticipationEventRegistrationOptions*/ } from // TODO: https://github.com/iotaledger/firefly/issues/7947 export async function registerParticipationEvents(): Promise { -// registrationOptions: ParticipationEventRegistrationOptions, -// wallet: IWalletState + // registrationOptions: ParticipationEventRegistrationOptions, + // wallet: IWalletState // let newRegistrationOptions = registrationOptions // const { removedProposalIds } = getSelectedWallet() ?? {} // if (removedProposalIds?.length > 0) { From 57c779cec781e0e599c478d197d82de2df7c360d Mon Sep 17 00:00:00 2001 From: marc2332 Date: Wed, 31 Jan 2024 13:11:07 +0100 Subject: [PATCH 34/37] clean up --- .../utils/getStorageDirectoryOfProfiles.ts | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfiles.ts diff --git a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfiles.ts b/packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfiles.ts deleted file mode 100644 index 8194ff8859a..00000000000 --- a/packages/shared/lib/core/profile/utils/getStorageDirectoryOfProfiles.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Platform } from '@core/app' - -import { PROFILE_STORAGE_DIRECTORY } from '../constants' - -export const getStorageDirectoryOfProfiles = async (): Promise => { - const appPath = await Platform.getUserDataPath() - return `${appPath}/${PROFILE_STORAGE_DIRECTORY}` -} - -export let storageDirectoryOfProfiles = '' - -window.addEventListener('load', () => { - getStorageDirectoryOfProfiles().then((path) => { - storageDirectoryOfProfiles = path - }) -}) From ce1b12ce49c387499f7f9bea517ca94d0482252d Mon Sep 17 00:00:00 2001 From: marc2332 Date: Thu, 1 Feb 2024 15:41:09 +0100 Subject: [PATCH 35/37] feat: Update account to wallet locales and remove unused --- .../core/app/interfaces/platform.interface.ts | 1 - .../unable-to-get-bound-wallet.error.ts | 2 +- packages/shared/locales/en.json | 94 ++----------------- 3 files changed, 7 insertions(+), 90 deletions(-) diff --git a/packages/shared/lib/core/app/interfaces/platform.interface.ts b/packages/shared/lib/core/app/interfaces/platform.interface.ts index 3aa18a63bc7..fbcdde45cac 100644 --- a/packages/shared/lib/core/app/interfaces/platform.interface.ts +++ b/packages/shared/lib/core/app/interfaces/platform.interface.ts @@ -9,7 +9,6 @@ import { AppTheme } from '../enums' export interface IPlatform { getStrongholdBackupDestination(defaultPath: string): Promise saveStrongholdBackup({ allowAccess }: { allowAccess: boolean }): Promise - exportTransactionHistory(defaultPath: string, contents: string): Promise getUserDataPath(): Promise getDiagnostics(): Promise<{ label: string; value: string }[]> getOS(): Promise diff --git a/packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts b/packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts index ab273753b35..a3108d09b4d 100644 --- a/packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts +++ b/packages/shared/lib/core/wallet/errors/unable-to-get-bound-wallet.error.ts @@ -3,7 +3,7 @@ import { BaseError, DEFAULT_APP_ERROR_PARAMETERS } from '@core/error' export class UnableToGetBoundWalletError extends BaseError { constructor() { super({ - message: 'error.wallet.cannotGetBoundAccount', + message: 'error.cannotGetBoundWallet', ...DEFAULT_APP_ERROR_PARAMETERS, }) } diff --git a/packages/shared/locales/en.json b/packages/shared/locales/en.json index c559957271c..a968fe95d99 100644 --- a/packages/shared/locales/en.json +++ b/packages/shared/locales/en.json @@ -236,17 +236,6 @@ "title": "Switch Ledger apps", "body": "Please switch to the {legacy} app on your Ledger device to continue migration. When ready, press continue." }, - "selectLedgerAccountIndex": { - "title": "Choose Ledger account index", - "body": "Choose the Ledger account index you used with Trinity. For most users this will be the default index of 0.", - "accountIndex": "Account Index", - "accountPage": "Account Page", - "standard": "Standard", - "expert": "Expert", - "takingAWhile": "This is taking a while...", - "notGeneratingAddresses": "Is your Ledger generating addresses?", - "reinstallLegacy": "If not, disconnect the device and try again. If the issue persists, you may need to reinstall the {legacy} app." - }, "settings": { "settings": "Settings", "general": { @@ -325,7 +314,7 @@ }, "refreshNftMedia": { "title": "Refresh NFT media", - "description": "NFT media cached for this account will be deleted and then downloaded again" + "description": "NFT media cached for this wallet will be deleted and then downloaded again" }, "changePassword": { "title": "Change password", @@ -397,10 +386,6 @@ "title": "Diagnostics", "description": "View system and application information" }, - "migrateLedgerIndex": { - "title": "Migrate Ledger index", - "description": "Migrate another Trinity account index" - }, "troubleshoot": { "title": "Troubleshoot", "description": "Use the troubleshooting wizard to solve common problems" @@ -585,7 +570,7 @@ "voted": "Voted", "successEdit": "Proposal successfully edited", "successAdd": "{numberOfProposals, select, one {Proposal} other {Proposals}} successfully added", - "successAddAll": "{numberOfProposals, select, one {Proposal} other {Proposals}} successfully added to all accounts", + "successAddAll": "{numberOfProposals, select, one {Proposal} other {Proposals}} successfully added to all wallets", "successRemove": "Proposal successfully removed", "emptyTitle": "No proposals" }, @@ -914,13 +899,6 @@ } } }, - "switchNetwork": { - "title": "Switch network", - "newNetwork": "New network", - "resetWarning": "Changing networks will log you out and reset all accounts, balances, and transaction history for this profile.", - "switchingNetwork": "Switching network", - "typePassword": "Type your password to switch to:" - }, "errorLog": { "title": "Error Log", "empty": "The error log is empty." @@ -1033,25 +1011,6 @@ "title": "Confirm receive address", "body": "Confirm that the receive address displayed on your Ledger matches the one displayed below. If they match, press both buttons on your Ledger as prompted." }, - "ledgerMigrateIndex": { - "title": "Do you need to migrate another Trinity account index?", - "body": "You can also migrate later in Advanced Settings." - }, - "exportTransactionHistory": { - "title": "Export transaction history", - "body": "Export the transaction history for the selected wallet. The exported file will be in .csv format.", - "profileName": "Profile name:", - "accountName": "Wallet name:", - "typePassword": "Type your password to allow exporting" - }, - "stakingManager": { - "title": "Staking Management", - "description": "When you stake a wallet, you send a transaction to yourself marking those funds as \"staked\". You can transfer the tokens at any time, but you won’t continue receiving staking rewards.", - "totalFundsStaked": "Total funds staked", - "stakedSuccessfully": "Your funds have been staked for {account}.", - "unstakedSuccessfully": "Your funds have been unstaked for {account}.", - "singleAccountHint": "Looking for your wallets? Firefly has changed. Toggle between your wallets in the top menu bar." - }, "stakingConfirmation": { "title": "Confirm Participation", "subtitleStake": "You are about to stake", @@ -1232,19 +1191,6 @@ "errorFailedGenerate": "Couldn't generate a new address" } }, - "charts": { - "incomingMi": "Incoming {value}", - "outgoingMi": "Outgoing {value}", - "portoflio": "Portfolio", - "token": "Token", - "holdings": "Holdings", - "accountValue": "Wallet Value", - "accountActivity": "Wallet Activity", - "timeframe1Hour": "1 hour", - "timeframe1Day": "1 day", - "timeframe1Week": "1 week", - "timeframe1Month": "1 month" - }, "actions": { "apply": "Apply", "continue": "Continue", @@ -1291,7 +1237,7 @@ }, "refreshNftMedia": { "title": "Refresh NFT media", - "description": "Do you want to delete and re-download all NFT media for this account?" + "description": "Do you want to delete and re-download all NFT media for this wallet?" }, "createWallet": "Create a new {network} profile", "createWalletDescription": "Create a fresh profile running on {network, select, iota {Chrysalis} shimmer {Shimmer} testnet {Testnet} custom {Custom Network} other {Unknown}}", @@ -1539,8 +1485,6 @@ "outgoing": "Outgoing", "totalIn": "Total in", "totalOut": "Total out", - "accounts": "Wallets", - "myAccounts": "My Wallets", "profiles": "Profiles", "dev": "Dev", "createWallet": "Create a Wallet", @@ -1550,7 +1494,6 @@ "transactions": "Transactions", "activity": "Activity", "security": "Security", - "accountAddress": "Wallet Address", "network": "Network", "destinationNetwork": "Destination network", "nodes": "Nodes", @@ -1586,10 +1529,6 @@ "generatingReceiveAddress": "Generating receive address", "broadcasting": "Broadcasting", "confirming": "Confirming", - "creatingAccount": "Creating wallet, please wait...", - "updatingAccount": "Updating wallet, please wait...", - "accountSyncing": "Wallet is syncing", - "accountSyncComplete": "Wallet sync complete", "passwordUpdating": "Updating password...", "passwordSuccess": "Updated password successfully", "passwordFailed": "Updating password failed", @@ -1609,7 +1548,6 @@ "passwordStrength4": "Strong", "creatingProfile": "Creating profile, please wait...", "fundMigration": "Fund migration", - "accountRemoved": "This wallet is hidden. Unhide it to perform transfers.", "fromAddress": "from {address}", "toAddress": "to {address}", "stakingTransaction": "Staking Transaction", @@ -1827,11 +1765,6 @@ "year": "{time, plural, one {# year} other {# years}}" }, "notifications": { - "valueTx": "Receiving {{value}} to {{account}}", - "confirmed": "Outgoing {{value}} from {{account}} has confirmed", - "confirmedInternal": "{{value}} from {{senderAccount}} to {{receiverAccount}} has confirmed", - "confirmedInternalNoAccounts": "{{value}} internal transfer has confirmed", - "failed": "Outgoing {{value}} from {{account}} has failed", "downloadingUpdate": "Downloading update", "updateReady": "Update ready", "updateError": "An error occurred during the update, please try again", @@ -1839,12 +1772,7 @@ "calcMinutesRemaining": "Calculating minutes remaining...", "minutesRemaining": "{minutes, plural, one {# minute remaining} other {# minutes remaining}}", "copiedToClipboard": "Copied to clipboard", - "accountsSynchronized": "Wallet synchronization complete", "fundsAvailableSoon": "Your funds will become available shortly", - "exportTransactionHistory": { - "success": "Transaction history for {accountAlias} was successfully saved to {filePath}", - "error": "Unable to export transaction history for {accountAlias}" - }, "deepLinkingRequest": { "receivedWhileLoggedOut": "Please login to initiate the deep link", "notEnabled": "Deep links are not enabled", @@ -1949,7 +1877,6 @@ "wrongAddressType": "Wrong address type" }, "wallet": { - "addressNotFound": "The address cannot be found in your account.", "length": "Your wallet name can't be longer than {length, plural, one {# character} other {# characters}}.", "emptyName": "A profile name must contain at least 1 character.", "notEmpty": "You must transfer your balance before deleting this wallet.", @@ -1958,14 +1885,11 @@ "control": "A profile name can't contain a control character.", "startDot": "A profile name can't start with the '.' character.", "chars": "A profile name can't contain the following characters <>:\"/\\|?*", - "index": "Your account index must be a number between 0 and 2,147,483,647.", - "page": "Your account page must be a number between 0 and 2,147,483,647.", "syncing": "There was an error syncing your wallets.", "cannotRemove": "Unable to remove wallet.", "withBalance": "You must transfer all balances before you can delete this wallet.", "notLast": "You can only delete your last wallet.", - "notFound": "Unable to find account", - "cannotGetBoundAccount": "Unable to get bound account" + "cannotGetBoundWallet": "Unable to get bound wallet" }, "send": { "addressLength": "Addresses should be {length, plural, one {# character} other {# characters}} long.", @@ -1980,7 +1904,7 @@ "wrongAddressFormat": "The address is not correctly formatted.", "invalidAddress": "The address is not valid.", "invalidAssetId": "The asset id is not valid.", - "unknownAsset": "The asset is not known to this account.", + "unknownAsset": "The asset is not known to this wallet.", "insufficientFunds": "This wallet has insufficient funds.", "insufficientFundsStorageDeposit": "Insufficient funds to cover the storage deposit.", "ongoingTransaction": "If you have ongoing transactions, please wait for their confirmation.", @@ -2002,7 +1926,7 @@ "reservedTagKeyword": "Unable to use reserved tag keyword" }, "layer2": { - "layer1Recipient": "A layer 2 transaction cannot be sent to a layer 1 account.", + "layer1Recipient": "A layer 2 transaction cannot be sent to a layer 1 wallet", "estimatedGas": "Failed to estimate gas." }, "node": { @@ -2069,12 +1993,6 @@ "crypto": { "cannotDecodeBech32": "Unable to decode string as Bech32 address." }, - "participation": { - "cannotUseAccount": "Unable to use the specified account.", - "cannotFindStakingEvent": "Unable to find staking event.", - "cannotVisitAirdropWebsite": "Unable to open the {airdrop} website.", - "invalidStakingEventId": "Invalid staking event ID." - }, "invalidDate": "INVALID DATE", "invalidTime": "INVALID TIME", "shimmerClaiming": { From 6af1c4f664881d9aebe497e1485f5fb8259309ea Mon Sep 17 00:00:00 2001 From: marc2332 Date: Thu, 1 Feb 2024 15:43:38 +0100 Subject: [PATCH 36/37] let's do this in another PR --- packages/shared/lib/core/app/interfaces/platform.interface.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/shared/lib/core/app/interfaces/platform.interface.ts b/packages/shared/lib/core/app/interfaces/platform.interface.ts index fbcdde45cac..3aa18a63bc7 100644 --- a/packages/shared/lib/core/app/interfaces/platform.interface.ts +++ b/packages/shared/lib/core/app/interfaces/platform.interface.ts @@ -9,6 +9,7 @@ import { AppTheme } from '../enums' export interface IPlatform { getStrongholdBackupDestination(defaultPath: string): Promise saveStrongholdBackup({ allowAccess }: { allowAccess: boolean }): Promise + exportTransactionHistory(defaultPath: string, contents: string): Promise getUserDataPath(): Promise getDiagnostics(): Promise<{ label: string; value: string }[]> getOS(): Promise From 93273913d3f930f05d5bb168ae7ea867fe0f54da Mon Sep 17 00:00:00 2001 From: marc2332 Date: Tue, 6 Feb 2024 11:44:11 +0100 Subject: [PATCH 37/37] clean up --- packages/desktop/electron/lib/menuState.js | 2 +- packages/desktop/lib/helpers.ts | 2 +- packages/shared/locales/en.json | 42 ++-------------------- 3 files changed, 5 insertions(+), 41 deletions(-) diff --git a/packages/desktop/electron/lib/menuState.js b/packages/desktop/electron/lib/menuState.js index 89b1a7bc33f..d850d0a310a 100644 --- a/packages/desktop/electron/lib/menuState.js +++ b/packages/desktop/electron/lib/menuState.js @@ -24,7 +24,7 @@ export const menuState = { paste: 'Paste', selectAll: 'Select All', wallet: 'Wallet', - addAccount: 'Add Account', + addWallet: 'Add Account', help: 'Help', troubleshoot: 'Troubleshoot', faq: 'FAQ', diff --git a/packages/desktop/lib/helpers.ts b/packages/desktop/lib/helpers.ts index 157f2eb2c88..63c9afabab7 100644 --- a/packages/desktop/lib/helpers.ts +++ b/packages/desktop/lib/helpers.ts @@ -31,7 +31,7 @@ export const getLocalisedMenuItems = (locale: Locale): unknown => ({ paste: locale('actions.paste'), selectAll: locale('actions.selectAll'), wallet: locale('general.wallet'), - addAccount: locale('actions.addAccount'), + addWallet: locale('actions.addWallet'), help: locale('general.help'), troubleshoot: locale('views.settings.troubleshoot.title'), faq: locale('views.settings.faq.title'), diff --git a/packages/shared/locales/en.json b/packages/shared/locales/en.json index a968fe95d99..8a7539e4b21 100644 --- a/packages/shared/locales/en.json +++ b/packages/shared/locales/en.json @@ -811,15 +811,6 @@ "title": "Failed link", "body": "This link failed or is invalid. Please try again or double check the source of the link." }, - "showDeleteWallet": { - "title": "Delete {name}?", - "body": "Are you sure you want to delete this wallet?", - "hint": "Note: once deleted, you can restore this wallet by using the \"Wallet Finder\" in the settings.", - "typePassword": "Type your wallet password to confirm.", - "hideAccount": "Delete wallet", - "errorTitle": "Unable to delete {name}", - "errorBody1": "You cannot delete this wallet, you must have at least one." - }, "externalUrl": { "title": "Open URL in Browser", "body": "Are you sure you want to open \"{url}\" in the browser?", @@ -827,16 +818,6 @@ "action": "Open URL", "invalidProtocol": "Cannot open URL with invalid protocol" }, - "hideAccount": { - "title": "Hide {name}?", - "body": "You can find this wallet later by enabling \"Show hidden wallets\" in Advanced Settings.", - "typePassword": "Type your wallet password to confirm.", - "hideAccount": "Hide wallet", - "errorTitle": "Unable to hide {name}", - "errorBody1": "To hide a wallet it must have 0 balance.", - "errorBody2": "You currently have {balance} remaining on this wallet. Please move these funds to a different wallet and try again.", - "errorBody3": "You cannot hide this wallet, you must have at least one." - }, "excludeNode": { "title": "Exclude node", "body": "Are you sure you want to exclude {url} from the available node pool?" @@ -926,9 +907,7 @@ "selectAmount": "Send {tokenName}", "selectRecipient": "Send {assetName} to", "transactionSummary": "Transaction to {recipient}", - "surplusIncluded": "This transaction contains a surplus amount. Please double check this is the amount you want to send.", - "sendingFromStakedAccount": "You are sending a transfer from a wallet that is currently being staked. This may unstake your tokens. Feel free to send the transfer but you may need to restake your remaining tokens afterwards.", - "sendingFromStakedAccountBelowMinReward": "You are sending a transfer from a wallet that has not yet reached the minimum staking rewards. This may unstake your tokens and you may lose your staking rewards on this wallet." + "surplusIncluded": "This transaction contains a surplus amount. Please double check this is the amount you want to send." }, "balanceFinder": { "title": "Balance finder", @@ -1053,11 +1032,6 @@ "tosCheckbox": "I've read and I accept the updated Terms of Service", "privPolicyCheckbox": "I've read and I accept the updated Privacy Policy" }, - "singleAccountGuide": { - "title": "The way you use Firefly has changed", - "body": "The content of each tab is now in the context of a single wallet. You can change the selected wallet from anywhere by using the switcher in the title bar.", - "hint": "Can't find a wallet? Use the balance finder in the settings to discover previously used wallets." - }, "transactionDetails": { "title": "Transaction details", "giftedStorageDeposit": { @@ -1309,7 +1283,7 @@ "copyAllInformation": "Copy all information", "paste": "Paste", "selectAll": "Select All", - "addAccount": "Add Wallet", + "addWallet": "Add Wallet", "checkForUpdates": "Check for Updates", "reportAnIssue": "Report an Issue", "restore": "Restore", @@ -1448,7 +1422,6 @@ "sendNft": "Send NFT", "sendNftToAddress": "Send NFT to an address", "scanQrOrPaste": "Scan a QR code or paste an Address", - "moveFundsBetweenAccounts": "Move funds between wallets", "manageWallet": "Manage Wallet", "customizeAcount": "Customize your wallet", "sendingToAddress": "Sending to address", @@ -1508,8 +1481,6 @@ "status": "Status", "confirmed": "Confirmed", "pending": "Pending", - "noAccounts": "You have no wallets, please create one.", - "loadingAccounts": "Loading, please wait...", "addProfile": "Add Profile", "noRecentHistory": "No recent history", "noFilteredActivity": "No matching activities", @@ -1533,7 +1504,6 @@ "passwordSuccess": "Updated password successfully", "passwordFailed": "Updating password failed", "syncing": "Syncing", - "syncingAccounts": "Syncing wallets...", "exportingStronghold": "Exporting Stronghold...", "exportingStrongholdSuccess": "Exported Stronghold successfully", "exportingStrongholdFailed": "Exporting Stronghold failed", @@ -1842,11 +1812,7 @@ "profile": { "length": "Your profile name can't be longer than {length, plural, one {# character} other {# characters}}.", "duplicate": "A profile with this name already exists.", - "delete": { - "nonEmptyAccounts": "You must transfer all balances before you can delete your profile." - }, "type": "Unable to determine the profile type", - "setupType": "Unable to determine the profile setup type", "chrysalisDevnetStardustError": "You can't access this profile because Chrysalis Devnet is not supported in this version of Firefly. Please use a Chrysalis compatible Firefly version." }, "password": { @@ -1909,7 +1875,6 @@ "insufficientFundsStorageDeposit": "Insufficient funds to cover the storage deposit.", "ongoingTransaction": "If you have ongoing transactions, please wait for their confirmation.", "cannotClaimTwice": "Output has been already claimed", - "noToAccount": "You have not selected a wallet to send the funds to.", "sendingDust": "You cannot send less than 1 Mi.", "leavingDust": "You cannot leave less than the minimum required storage deposit ({minRequiredStorageDeposit}) on your address.", "cancelled": "The transaction was cancelled.", @@ -1951,8 +1916,7 @@ "network": { "mismatch": "The network ID for this node is \"{networkId}\", which does not match the current network.", "notReachable": "The network ID for this node could not be retrieved, unable to add node.", - "badNodes": "Unable to connect to the network with current node configuration.", - "nonEmptyAccount": "You must transfer all balances before switching networks." + "badNodes": "Unable to connect to the network with current node configuration." }, "global": { "generic": "Something went wrong."