Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor keyring redux slice to remove importing field #3309

Merged
merged 4 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion background/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1668,7 +1668,7 @@ export default class Main extends BaseService<never> {
return this.keyringService.exportPrivateKey(address)
}

async importSigner(signerRaw: SignerRawWithType): Promise<HexString | null> {
async importSigner(signerRaw: SignerRawWithType): Promise<string | null> {
return this.keyringService.importSigner(signerRaw)
}

Expand Down
58 changes: 26 additions & 32 deletions background/redux-slices/keyrings.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createSlice } from "@reduxjs/toolkit"
import Emittery from "emittery"

import { setNewSelectedAccount, UIState } from "./ui"
import { createBackgroundAsyncThunk } from "./utils"
import {
Keyring,
Expand All @@ -10,6 +9,8 @@ import {
SignerRawWithType,
} from "../services/keyring/index"
import { HexString } from "../types"
import logger from "../lib/logger"
import { UIState, setNewSelectedAccount } from "./ui"

type KeyringToVerify = {
id: string
Expand All @@ -22,7 +23,6 @@ export type KeyringsState = {
metadata: {
[keyringId: string]: SignerMetadata
}
importing: false | "pending" | "done" | "failed"
status: "locked" | "unlocked" | "uninitialized"
keyringToVerify: KeyringToVerify
}
Expand All @@ -31,7 +31,6 @@ export const initialState: KeyringsState = {
keyrings: [],
privateKeys: [],
metadata: {},
importing: false,
status: "uninitialized",
keyringToVerify: null,
}
Expand All @@ -50,23 +49,40 @@ export const importSigner = createBackgroundAsyncThunk(
async (
signerRaw: SignerRawWithType,
{ getState, dispatch, extra: { main } }
) => {
const address = await main.importSigner(signerRaw)
if (!address) return
): Promise<{ success: boolean; errorMessage?: string }> => {
let address = null

try {
address = await main.importSigner(signerRaw)
} catch (error) {
logger.error("Internal signer import failed:", error)

return {
success: false,
errorMessage: "Unexpected error during account import.",
}
}

if (!address) {
return {
success: false,
errorMessage:
"Failed to import new account. Address may already be imported.",
}
}

const { ui } = getState() as {
ui: UIState
}
// Set the selected account as the first address of the last added keyring,
// which will correspond to the last imported keyring, AKA this one. Note that
// this does rely on the KeyringService's behavior of pushing new keyrings to
// the end of the keyring list.

dispatch(
setNewSelectedAccount({
address,
network: ui.selectedAccount.network,
})
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fwiw I do feel like the logic in main.importSigner mostly belongs here rather than main--main should always do as little wiring as possible to connect to the services IMO.


return { success: true }
}
)

Expand Down Expand Up @@ -108,28 +124,6 @@ const keyringsSlice = createSlice({
keyringToVerify: payload,
}),
},
extraReducers: (builder) => {
builder
.addCase(importSigner.pending, (state) => {
return {
...state,
importing: "pending",
}
})
.addCase(importSigner.fulfilled, (state) => {
return {
...state,
importing: "done",
keyringToVerify: null,
}
})
.addCase(importSigner.rejected, (state) => {
return {
...state,
importing: "failed",
}
})
},
})

export const {
Expand Down
3 changes: 2 additions & 1 deletion background/redux-slices/migrations/to-28.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ type OldState = {
source: "import" | "internal"
}
}
importing: false | "pending" | "done" | "failed"
[sliceKey: string]: unknown
}
}
Expand All @@ -26,7 +27,7 @@ type NewState = {
export default (prevState: Record<string, unknown>): NewState => {
const oldState = prevState as OldState
const {
keyrings: { keyringMetadata, ...keyringsState },
keyrings: { keyringMetadata, importing, ...keyringsState },
} = oldState

return {
Expand Down
27 changes: 12 additions & 15 deletions ui/pages/Onboarding/OnboardingImportMetamask.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { ReactElement, useCallback, useEffect, useState } from "react"
import React, { ReactElement, useCallback, useState } from "react"
import { importSigner } from "@tallyho/tally-background/redux-slices/keyrings"
import { useHistory } from "react-router-dom"
import { isValidMnemonic } from "@ethersproject/hdnode"
Expand All @@ -7,6 +7,7 @@ import { FeatureFlags, isEnabled } from "@tallyho/tally-background/features"
import { useTranslation } from "react-i18next"
import { selectCurrentNetwork } from "@tallyho/tally-background/redux-slices/selectors"
import { SignerTypes } from "@tallyho/tally-background/services/keyring"
import { AsyncThunkFulfillmentType } from "@tallyho/tally-background/redux-slices/utils"
import SharedButton from "../../components/Shared/SharedButton"
import SharedBackButton from "../../components/Shared/SharedBackButton"
import OnboardingDerivationPathSelect from "../../components/Onboarding/OnboardingDerivationPathSelect"
Expand Down Expand Up @@ -119,19 +120,8 @@ export default function OnboardingImportMetamask(props: Props): ReactElement {
const [isImporting, setIsImporting] = useState(false)

const dispatch = useBackgroundDispatch()
const keyringImport = useBackgroundSelector(
(state) => state.keyrings.importing
)

const history = useHistory()

useEffect(() => {
if (areKeyringsUnlocked && keyringImport === "done" && isImporting) {
setIsImporting(false)
history.push(nextPage)
}
}, [history, areKeyringsUnlocked, keyringImport, nextPage, isImporting])

const importWallet = useCallback(async () => {
const plainRecoveryPhrase = recoveryPhrase
.toLowerCase()
Expand All @@ -145,18 +135,25 @@ export default function OnboardingImportMetamask(props: Props): ReactElement {
setErrorMessage(t("phraseLengthError"))
} else if (isValidMnemonic(plainRecoveryPhrase)) {
setIsImporting(true)
dispatch(

const { success } = (await dispatch(
importSigner({
type: SignerTypes.keyring,
mnemonic: plainRecoveryPhrase,
path,
source: "import",
})
)
)) as unknown as AsyncThunkFulfillmentType<typeof importSigner>

setIsImporting(false)

if (success) {
history.push(nextPage)
}
} else {
setErrorMessage(t("invalidPhraseError"))
}
}, [dispatch, recoveryPhrase, path, t])
}, [dispatch, recoveryPhrase, path, t, history, nextPage])

if (!areKeyringsUnlocked) return <></>

Expand Down
14 changes: 10 additions & 4 deletions ui/pages/Onboarding/Tabbed/ImportPrivateKey.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { SignerTypes } from "@tallyho/tally-background/services/keyring"
import { isHexString } from "ethers/lib/utils"
import React, { ReactElement, useCallback, useState } from "react"
import { useTranslation } from "react-i18next"
import { AsyncThunkFulfillmentType } from "@tallyho/tally-background/redux-slices/utils"
import SharedButton from "../../../components/Shared/SharedButton"
import SharedSeedInput from "../../../components/Shared/SharedSeedInput"
import { useBackgroundDispatch } from "../../../hooks"
Expand Down Expand Up @@ -49,14 +50,19 @@ export default function ImportPrivateKey(props: Props): ReactElement {
const trimmedPrivateKey = privateKey.toLowerCase().trim()
if (validatePrivateKey(trimmedPrivateKey)) {
setIsImporting(true)
await dispatch(
const { success } = (await dispatch(
importSigner({
type: SignerTypes.privateKey,
privateKey: trimmedPrivateKey,
})
)
dispatch(sendEvent(OneTimeAnalyticsEvent.ONBOARDING_FINISHED))
finalize()
)) as unknown as AsyncThunkFulfillmentType<typeof importSigner>

if (success) {
dispatch(sendEvent(OneTimeAnalyticsEvent.ONBOARDING_FINISHED))
finalize()
} else {
setIsImporting(false)
}
} else {
setErrorMessage(t("error"))
}
Expand Down
26 changes: 10 additions & 16 deletions ui/pages/Onboarding/Tabbed/ImportPrivateKeyJSON.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React, { ReactElement, useCallback, useEffect, useState } from "react"
import React, { ReactElement, useCallback, useState } from "react"
import { useTranslation } from "react-i18next"
import { importSigner } from "@tallyho/tally-background/redux-slices/keyrings"
import { SignerTypes } from "@tallyho/tally-background/services/keyring"
import classnames from "classnames"
import { selectCurrentAccount } from "@tallyho/tally-background/redux-slices/selectors"
import { sendEvent } from "@tallyho/tally-background/redux-slices/ui"
import { OneTimeAnalyticsEvent } from "@tallyho/tally-background/lib/posthog"
import { AsyncThunkFulfillmentType } from "@tallyho/tally-background/redux-slices/utils"
import SharedButton from "../../../components/Shared/SharedButton"
import PasswordInput from "../../../components/Shared/PasswordInput"
import SharedFileInput from "../../../components/Shared/SharedFileInput"
Expand All @@ -21,10 +22,6 @@ type Props = {
export default function ImportPrivateKeyJSON(props: Props): ReactElement {
const { setIsImporting, isImporting, finalize } = props

const keyringImportStatus = useBackgroundSelector(
(state) => state.keyrings.importing
)

const dispatch = useBackgroundDispatch()
const selectedAccountAddress =
useBackgroundSelector(selectCurrentAccount).address
Expand All @@ -49,28 +46,25 @@ export default function ImportPrivateKeyJSON(props: Props): ReactElement {
setHasError(false)
setIsImporting(true)

await dispatch(
const { success } = (await dispatch(
importSigner({
type: SignerTypes.jsonFile,
jsonFile: file,
password,
})
)
)) as unknown as AsyncThunkFulfillmentType<typeof importSigner>

setIsImporting(false)
setIsImported(true)
}, [dispatch, file, password, setIsImporting])

useEffect(() => {
if (keyringImportStatus === "failed" && isImported) {
if (success) {
setIsImported(true)
setHasError(false)
dispatch(sendEvent(OneTimeAnalyticsEvent.ONBOARDING_FINISHED))
} else {
setHasError(true)
setIsImported(false)
}

if (keyringImportStatus === "done" && isImported) {
dispatch(sendEvent(OneTimeAnalyticsEvent.ONBOARDING_FINISHED))
}
}, [isImported, keyringImportStatus, dispatch])
}, [dispatch, file, password, setIsImporting])

const showJSONForm = !isImporting && !isImported

Expand Down
29 changes: 13 additions & 16 deletions ui/pages/Onboarding/Tabbed/ImportSeed.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { ReactElement, useCallback, useEffect, useState } from "react"
import React, { ReactElement, useCallback, useState } from "react"
import { importSigner } from "@tallyho/tally-background/redux-slices/keyrings"
import { Redirect, useHistory } from "react-router-dom"
import { isValidMnemonic } from "@ethersproject/hdnode"
Expand All @@ -8,6 +8,7 @@ import { selectCurrentNetwork } from "@tallyho/tally-background/redux-slices/sel
import { SignerTypes } from "@tallyho/tally-background/services/keyring"
import { sendEvent } from "@tallyho/tally-background/redux-slices/ui"
import { OneTimeAnalyticsEvent } from "@tallyho/tally-background/lib/posthog"
import { AsyncThunkFulfillmentType } from "@tallyho/tally-background/redux-slices/utils"
import SharedButton from "../../../components/Shared/SharedButton"
import OnboardingDerivationPathSelect, {
DefaultPathIndex,
Expand Down Expand Up @@ -42,24 +43,13 @@ export default function ImportSeed(props: Props): ReactElement {
})

const dispatch = useBackgroundDispatch()
const keyringImport = useBackgroundSelector(
(state) => state.keyrings.importing
)

const history = useHistory()

const onInputChange = useCallback((seed: string) => {
setRecoveryPhrase(seed)
setErrorMessage("")
}, [])

useEffect(() => {
if (areKeyringsUnlocked && keyringImport === "done" && isImporting) {
setIsImporting(false)
history.push(nextPage)
}
}, [history, areKeyringsUnlocked, keyringImport, nextPage, isImporting])

const importWallet = useCallback(async () => {
const plainRecoveryPhrase = recoveryPhrase
.toLowerCase()
Expand All @@ -73,19 +63,26 @@ export default function ImportSeed(props: Props): ReactElement {
setErrorMessage(t("errors.phraseLengthError"))
} else if (isValidMnemonic(plainRecoveryPhrase)) {
setIsImporting(true)
await dispatch(

const { success } = (await dispatch(
importSigner({
type: SignerTypes.keyring,
mnemonic: plainRecoveryPhrase,
path,
source: "import",
})
)
dispatch(sendEvent(OneTimeAnalyticsEvent.ONBOARDING_FINISHED))
)) as unknown as AsyncThunkFulfillmentType<typeof importSigner>

if (success) {
await dispatch(sendEvent(OneTimeAnalyticsEvent.ONBOARDING_FINISHED))
history.push(nextPage)
} else {
setIsImporting(false)
}
} else {
setErrorMessage(t("errors.invalidPhraseError"))
}
}, [dispatch, recoveryPhrase, path, t])
}, [dispatch, recoveryPhrase, path, t, history, nextPage])

if (!areKeyringsUnlocked)
return (
Expand Down
Loading