Skip to content

Commit 01e780c

Browse files
cpl121brancoder
andauthored
feat: improve migration log file when tracking an error (#95)
* feat: improve migration log file when tracking an error * fix: format * feat: add errors to error log * fix: error message notification for single bundle * fix: improve prepareMigrationLog when retry the migration * feat: show correct error in the notification * fix: append migration log on retry --------- Co-authored-by: Branko Bosnic <[email protected]>
1 parent 52c0c31 commit 01e780c

File tree

7 files changed

+136
-110
lines changed

7 files changed

+136
-110
lines changed

packages/shared/lib/errors.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@ export const addError = (err: Error): void => {
1313
errorLog.update((log) => [err, ...log])
1414
}
1515

16+
export const addMigrationError = (err: string): void => {
17+
const error: Error = {
18+
message: err,
19+
time: Date.now(),
20+
type: 'migration error',
21+
}
22+
errorLog.update((log) => [error, ...log])
23+
}
24+
1625
export function displayErrorEventToUser(error: ErrorEventPayload): void {
1726
if (get(isLedgerProfile)) {
1827
displayNotificationForLedgerProfile('error', true, true, false, false, error)

packages/shared/lib/migration.ts

Lines changed: 45 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { convertBech32AddressToEd25519Address } from './ed25519'
3232
import { Buffer } from 'buffer'
3333
import { blake2b } from 'blakejs'
3434
import { SimpleBufferCursor } from './simpleBufferCursor'
35+
import { Platform } from './platform'
3536

3637
const LEGACY_ADDRESS_WITHOUT_CHECKSUM_LENGTH = 81
3738

@@ -395,46 +396,62 @@ async function fetchMigratableBalance(hexAddress: string): Promise<number> {
395396
*
396397
* @method prepareMigrationLog
397398
*
398-
* @param {string} bundleHash
399399
* @param {string[]} trytes
400400
* @param {number} balance
401-
* @param [boolean] mine
402-
* @param [number] crackability
401+
* @param [string] bundleHash
403402
*
404403
* @returns {void}
405404
*/
406-
export const prepareMigrationLog = (bundleHash: string, trytes: string[], balance: number): void => {
407-
const transactionObjects = trytes.map((tryteString) => asTransactionObject(tryteString))
408-
const { bundles } = get(migration)
409-
410-
const bundle = get(bundles).find((bundle) => bundle.bundleHash === bundleHash)
411-
const spentInputs = bundle?.inputs?.filter((input) => input.spent === true) || []
412-
413-
const spentBundleHashes = []
414-
415-
spentInputs.forEach((input) => {
416-
input.spentBundleHashes.forEach((bundleHash) => {
417-
spentBundleHashes.push(bundleHash)
418-
})
419-
})
420-
421-
migrationLog.update((_log) => [
422-
..._log,
405+
export const prepareMigrationLog = (trytes: string[], balance: number, bundleHash?: string): void => {
406+
migrationLog.update((_logs) => [
407+
..._logs,
423408
{
424-
bundleHash: transactionObjects[0].bundle,
409+
bundleHash,
425410
timestamp: new Date().toISOString(),
426411
trytes,
427-
receiveAddressTrytes: transactionObjects.find((tx) => tx.address.startsWith('TRANSFER')).address,
412+
depositAddress: JSON.stringify(get(migrationAddress), null, 2),
428413
balance,
429-
spentBundleHashes,
430-
spentAddresses: bundle?.inputs?.filter((input) => input.spent === true).map((input) => input.address) || [],
431-
mine: bundle?.miningRuns > 0,
432-
crackability: bundle?.crackability || null,
433-
depositAddress: get(migrationAddress)?.bech32 ?? '',
434414
},
435415
])
436416
}
437417

418+
/**
419+
* Update migration log
420+
*
421+
* @method updateMigrationLog
422+
*
423+
* @param {number} index
424+
* @param {Partial<MigrationLog>} updatedProperties
425+
*
426+
* @returns {void}
427+
*/
428+
export function updateMigrationLog(index: number, updatedProperties: Partial<MigrationLog>): void {
429+
migrationLog.update((logs) => {
430+
const updatedLogs = [...logs]
431+
432+
if (updatedLogs[index]) {
433+
updatedLogs[index] = {
434+
...updatedLogs[index],
435+
...updatedProperties,
436+
}
437+
}
438+
439+
return updatedLogs
440+
})
441+
}
442+
443+
/**
444+
* Export migration log
445+
*
446+
* @method exportMigrationLog
447+
*
448+
* @returns {void}
449+
*/
450+
export function exportMigrationLog(): void {
451+
const profileId = get(activeProfile).id
452+
Platform.exportMigrationLog(get(migrationLog), `${profileId}-${LOG_FILE_NAME}`)
453+
}
454+
438455
/**
439456
* Gets migration data for ledger accounts
440457
*
@@ -756,7 +773,7 @@ export const sendLedgerMigrationBundle = (bundleHash: string, trytes: string[]):
756773
api.sendLedgerMigrationBundle(MIGRATION_NODES, trytes, MINIMUM_WEIGHT_MAGNITUDE, {
757774
onSuccess(response) {
758775
// Store migration log so that we can export it later
759-
prepareMigrationLog(bundleHash, trytes, response.payload.value)
776+
prepareMigrationLog(trytes, response.payload.value, bundleHash)
760777

761778
_sendMigrationBundle(bundleHash, response.payload)
762779

packages/shared/lib/typings/migration.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,17 +55,13 @@ export enum RiskLevel {
5555
}
5656

5757
export interface MigrationLog {
58-
bundleHash: string
58+
bundleHash?: string
5959
trytes: string[]
60-
receiveAddressTrytes: string
60+
depositAddress: string
6161
balance: number
6262
timestamp: string
63-
spentAddresses: string[]
64-
spentBundleHashes: string[]
65-
mine: boolean
66-
crackability: number | null
67-
depositAddress?: string
68-
requestId?: string
63+
requestData?: string
64+
errorMessage?: string
6965
}
7066

7167
export interface Bundle {

packages/shared/routes/setup/Balance.svelte

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import { walletSetupType } from 'shared/lib/wallet'
2424
import { SetupType } from 'shared/lib/typings/setup'
2525
import { appRouter } from '@core/router'
26+
import { addMigrationError } from '@lib/errors'
2627
2728
export let locale: Locale
2829
@@ -139,12 +140,14 @@
139140
.then(() => {
140141
isCheckingForBalance = false
141142
})
142-
.catch((error) => {
143+
.catch((err) => {
144+
const error = err?.message ? err.message : err?.toString()
143145
isCheckingForBalance = false
144146
145147
console.error(error)
146148
147149
displayNotificationForLedgerProfile('error', true, true, false, true, error)
150+
addMigrationError(error)
148151
})
149152
}
150153
const _onCancel = () => (isCheckingForBalance = false)
@@ -154,9 +157,11 @@
154157
.then(() => {
155158
isCheckingForBalance = false
156159
})
157-
.catch((error) => {
160+
.catch((err) => {
161+
const error = err?.message ? err.message : err?.toString()
158162
isCheckingForBalance = false
159163
console.error(error)
164+
addMigrationError(error)
160165
})
161166
}
162167
}

packages/shared/routes/setup/Congratulations.svelte

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,10 @@
77
import { cleanupSignup } from 'shared/lib/app'
88
import { convertToFiat, currencies, exchangeRates, formatCurrency } from 'shared/lib/currency'
99
import {
10-
LOG_FILE_NAME,
11-
migrationLog,
1210
resetMigrationState,
1311
totalMigratedBalance,
1412
migrationAddress,
13+
exportMigrationLog,
1514
} from 'shared/lib/migration'
1615
import { showAppNotification } from 'shared/lib/notifications'
1716
import { Platform } from 'shared/lib/platform'
@@ -20,7 +19,7 @@
2019
import { LedgerAppName } from 'shared/lib/typings/ledger'
2120
import { SetupType } from 'shared/lib/typings/setup'
2221
import { formatUnitBestMatch } from 'shared/lib/units'
23-
import { api, getProfileDataPath, walletSetupType } from 'shared/lib/wallet'
22+
import { api, walletSetupType } from 'shared/lib/wallet'
2423
import { onMount } from 'svelte'
2524
import { get } from 'svelte/store'
2625
@@ -30,7 +29,6 @@
3029
let localizedValues = {}
3130
3231
let exportStrongholdBusy = false
33-
let exportMigrationLogBusy = false
3432
3533
$: isLedgerProfile = $walletSetupType === SetupType.TrinityLedger
3634
$: fiatBalance = formatCurrency(
@@ -53,22 +51,6 @@
5351
}
5452
})
5553
56-
function exportMigrationLog(): void {
57-
exportMigrationLogBusy = true
58-
getProfileDataPath($activeProfile.id)
59-
.then(() => Platform.exportMigrationLog($migrationLog, `${$activeProfile.id}-${LOG_FILE_NAME}`))
60-
.catch((error) => {
61-
console.error(error)
62-
showAppNotification({
63-
type: 'error',
64-
message: locale('error.ledger.generateAddress'),
65-
})
66-
})
67-
.finally(() => {
68-
exportMigrationLogBusy = false
69-
})
70-
}
71-
7254
function exportStronghold(): void {
7355
function onPasswordSuccess(password: string, callback?: (cancelled: boolean, err?: string) => void): void {
7456
Platform.getStrongholdBackupDestination(getDefaultStrongholdName())
@@ -167,7 +149,7 @@
167149
classes="w-full"
168150
secondary
169151
onClick={migrateAnotherProfile}
170-
disabled={exportMigrationLogBusy || exportStrongholdBusy}
152+
disabled={exportStrongholdBusy}
171153
>
172154
{locale('views.congratulations.migrateAnotherProfile')}
173155
</Button>
@@ -176,7 +158,7 @@
176158
{locale('views.congratulations.exportStronghold')}
177159
</Button>
178160
{/if}
179-
<Button classes="w-full" onClick={exportMigrationLog} disabled={exportMigrationLogBusy}>
161+
<Button classes="w-full" onClick={exportMigrationLog}>
180162
{locale('views.congratulations.exportMigration')}
181163
</Button>
182164
</div>

packages/shared/routes/setup/migrate/views/Migrate.svelte

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
confirmedBundles,
99
createLedgerMigrationBundle,
1010
createMigrationBundle,
11+
exportMigrationLog,
1112
generateMigrationAddress,
1213
hardwareIndexes,
1314
hasBundlesWithSpentAddresses,
@@ -19,6 +20,7 @@
1920
sendOffLedgerMigrationRequest,
2021
totalMigratedBalance,
2122
unselectedInputs,
23+
updateMigrationLog,
2224
} from 'shared/lib/migration'
2325
import { showAppNotification } from 'shared/lib/notifications'
2426
import { closePopup } from 'shared/lib/popup'
@@ -30,6 +32,7 @@
3032
import { AvailableExchangeRates, CurrencyTypes } from 'shared/lib/typings/currency'
3133
import { walletSetupType } from 'shared/lib/wallet'
3234
import { SetupType } from 'shared/lib/typings/setup'
35+
import { addMigrationError } from '@lib/errors'
3336
3437
export let locale: Locale
3538
@@ -55,6 +58,8 @@
5558
5659
let singleMigrationBundleHash
5760
61+
let hasError: boolean = false
62+
5863
const legacyLedger = $walletSetupType === SetupType.TrinityLedger
5964
$: animation = legacyLedger ? 'ledger-migrate-desktop' : 'migrate-desktop'
6065
@@ -91,16 +96,13 @@
9196
closePopup(true) // close transaction popup
9297
singleMigrationBundleHash = bundleHash
9398
const reverseTrytesLedger = trytes.reverse()
94-
prepareMigrationLog(bundleHash, reverseTrytesLedger, migratableBalance)
99+
prepareMigrationLog(reverseTrytesLedger, migratableBalance, bundleHash)
95100
return sendOffLedgerMigrationRequest(reverseTrytesLedger, 0)
96101
})
97102
.then((receipt) => {
98-
migrationLog.update((_migrationLog) =>
99-
_migrationLog.map((log) => ({
100-
...log,
101-
requestId: receipt?.request?.requestId || '',
102-
}))
103-
)
103+
updateMigrationLog(get(migrationLog).length - 1, {
104+
requestData: JSON.stringify(receipt?.request),
105+
})
104106
totalMigratedBalance.set(migratableBalance)
105107
loading = false
106108
if ($newProfile) {
@@ -111,15 +113,19 @@
111113
newProfile.set(null)
112114
}
113115
})
114-
.catch((error) => {
116+
.catch((err) => {
117+
const error = err?.message ? err.message : err?.toString()
115118
loading = false
116119
closePopup(true) // close transaction popup
117120
closeTransport()
118121
showAppNotification({
119122
type: 'error',
120-
message: locale(getLegacyErrorMessage(error)),
123+
message: locale(getLegacyErrorMessage(err)),
121124
})
122-
console.error(error)
125+
console.error(err)
126+
updateMigrationLog(get(migrationLog).length - 1, { errorMessage: error })
127+
hasError = true
128+
addMigrationError(error)
123129
})
124130
}
125131
const _onCancel = () => {
@@ -129,18 +135,14 @@
129135
} else {
130136
createMigrationBundle($bundles[0], get(migrationAddress))
131137
.then((trytes: string[]) => {
132-
// TODO: Check the bundlehash with software profiles
133138
const reverseTrytesSoftware = trytes.reverse()
134-
prepareMigrationLog('', reverseTrytesSoftware, migratableBalance)
139+
prepareMigrationLog(reverseTrytesSoftware, migratableBalance)
135140
return sendOffLedgerMigrationRequest(reverseTrytesSoftware, 0)
136141
})
137142
.then((receipt) => {
138-
migrationLog.update((_migrationLog) =>
139-
_migrationLog.map((log) => ({
140-
...log,
141-
requestId: receipt?.request?.requestId || '',
142-
}))
143-
)
143+
updateMigrationLog(get(migrationLog).length - 1, {
144+
requestData: JSON.stringify(receipt?.request),
145+
})
144146
totalMigratedBalance.set(migratableBalance)
145147
loading = false
146148
if ($newProfile) {
@@ -151,13 +153,17 @@
151153
newProfile.set(null)
152154
}
153155
})
154-
.catch((error) => {
156+
.catch((err) => {
157+
const error = err?.message ? err.message : err.toString()
155158
loading = false
156159
showAppNotification({
157160
type: 'error',
158-
message: error.message || 'Failed to prepare transfers',
161+
message: error || 'Failed to prepare transfers',
159162
})
160163
console.error(error)
164+
updateMigrationLog(get(migrationLog).length - 1, { errorMessage: error })
165+
hasError = true
166+
addMigrationError(error)
161167
})
162168
}
163169
} else {
@@ -215,6 +221,11 @@
215221
<Spinner busy={loading} message={locale('views.migrate.migrating')} classes="justify-center" />
216222
{:else}{locale('views.migrate.beginMigration')}{/if}
217223
</Button>
224+
{#if hasError}
225+
<Button classes="w-full" onClick={exportMigrationLog}>
226+
{locale('views.congratulations.exportMigration')}
227+
</Button>
228+
{/if}
218229
</div>
219230
<div slot="rightpane" class="w-full h-full flex justify-center bg-pastel-blue dark:bg-gray-900">
220231
<Animation classes="setup-anim-aspect-ratio" {animation} />

0 commit comments

Comments
 (0)