From fdd260a3b2bfb48d7d02c3a3e5ff39cc1f12d745 Mon Sep 17 00:00:00 2001 From: ahsan-javaiid Date: Tue, 8 Nov 2022 20:15:39 +0500 Subject: [PATCH] feat: rsk ledger integration --- background/constants/networks.ts | 2 +- background/main.ts | 4 + background/redux-slices/ledger.ts | 9 ++ background/redux-slices/ui.ts | 22 ++- background/services/ledger/index.ts | 32 +++- ui/_locales/en/messages.json | 10 +- .../LedgerMenu/EcosystemNetworkIcon.tsx | 28 ++++ .../LedgerMenu/LedgerMenuProtocolList.tsx | 49 ++++++ .../LedgerMenu/LedgerMenuProtocolListItem.tsx | 151 ++++++++++++++++++ .../OnboardingDerivationPathSelect.tsx | 10 +- ui/pages/Ledger/LedgerPrepare.tsx | 14 +- ui/pages/Ledger/LedgerSelectNetwork.tsx | 39 +++++ 12 files changed, 352 insertions(+), 18 deletions(-) create mode 100644 ui/components/LedgerMenu/EcosystemNetworkIcon.tsx create mode 100644 ui/components/LedgerMenu/LedgerMenuProtocolList.tsx create mode 100644 ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx create mode 100644 ui/pages/Ledger/LedgerSelectNetwork.tsx diff --git a/background/constants/networks.ts b/background/constants/networks.ts index 5294a9c5aa..4a6431e797 100644 --- a/background/constants/networks.ts +++ b/background/constants/networks.ts @@ -114,7 +114,7 @@ export const TEST_NETWORK_BY_CHAIN_ID = new Set( [GOERLI].map((network) => network.chainID) ) -export const NETWORK_FOR_LEDGER_SIGNING = [ETHEREUM, POLYGON] +export const NETWORK_SUPPORTED_BY_LEDGER = [ETHEREUM, POLYGON, ROOTSTOCK] // Networks that are not added to this struct will // not have an in-wallet Swap page diff --git a/background/main.ts b/background/main.ts index e9e4e124ab..34dd33e4b3 100644 --- a/background/main.ts +++ b/background/main.ts @@ -1011,6 +1011,10 @@ export default class Main extends BaseService { this.ledgerService.emitter.on("usbDeviceCount", (usbDeviceCount) => { this.store.dispatch(setUsbDeviceCount({ usbDeviceCount })) }) + + uiSliceEmitter.on("derivationPathChange", (path: string) => { + this.ledgerService.setDefaultDerivationPath(path) + }) } async connectKeyringService(): Promise { diff --git a/background/redux-slices/ledger.ts b/background/redux-slices/ledger.ts index c0ea3f573f..52df129c80 100644 --- a/background/redux-slices/ledger.ts +++ b/background/redux-slices/ledger.ts @@ -31,6 +31,7 @@ export type LedgerState = { /** Devices by ID */ devices: Record usbDeviceCount: number + derivationPath?: string } export type Events = { @@ -58,6 +59,7 @@ export const initialState: LedgerState = { currentDeviceID: null, devices: {}, usbDeviceCount: 0, + derivationPath: undefined, } const ledgerSlice = createSlice({ @@ -95,6 +97,12 @@ const ledgerSlice = createSlice({ if (!(deviceID in immerState.devices)) return immerState.currentDeviceID = deviceID }, + setDerivationPath: ( + immerState, + { payload: derivationPath }: { payload: string } + ) => { + immerState.derivationPath = derivationPath + }, setDeviceConnectionStatus: ( immerState, { @@ -224,6 +232,7 @@ export const { addLedgerAccount, setUsbDeviceCount, removeDevice, + setDerivationPath, } = ledgerSlice.actions export default ledgerSlice.reducer diff --git a/background/redux-slices/ui.ts b/background/redux-slices/ui.ts index 31521dac70..55c5d77762 100644 --- a/background/redux-slices/ui.ts +++ b/background/redux-slices/ui.ts @@ -7,6 +7,7 @@ import { AnalyticsPreferences } from "../services/preferences/types" import { AccountSignerWithId } from "../signing" import { AccountSignerSettings } from "../ui" import { AccountState, addAddressNetwork } from "./accounts" +import { setDerivationPath } from "./ledger" import { createBackgroundAsyncThunk } from "./utils" const defaultSettings = { @@ -40,6 +41,7 @@ export type Events = { snackbarMessage: string newDefaultWalletValue: boolean refreshBackgroundPage: null + derivationPathChange: string newSelectedAccount: AddressOnNetwork newSelectedAccountSwitched: AddressOnNetwork userActivityEncountered: AddressOnNetwork @@ -247,13 +249,13 @@ export const setSelectedNetwork = createBackgroundAsyncThunk( emitter.emit("newSelectedNetwork", network) // Add any accounts on the currently selected network to the newly // selected network - if those accounts don't yet exist on it. - Object.keys(account.accountsData.evm[currentlySelectedChainID]).forEach( - (address) => { - if (!account.accountsData.evm[network.chainID]?.[address]) { - dispatch(addAddressNetwork({ address, network })) - } + Object.keys( + account.accountsData.evm[currentlySelectedChainID] ?? [] + ).forEach((address) => { + if (!account.accountsData.evm[network.chainID]?.[address]) { + dispatch(addAddressNetwork({ address, network })) } - ) + }) dispatch(setNewSelectedAccount({ ...ui.selectedAccount, network })) } ) @@ -265,6 +267,14 @@ export const refreshBackgroundPage = createBackgroundAsyncThunk( } ) +export const derivationPathChange = createBackgroundAsyncThunk( + "ui/derivationPathChange", + async (derivationPath: string, { dispatch }) => { + await emitter.emit("derivationPathChange", derivationPath) + dispatch(setDerivationPath(derivationPath)) + } +) + export const selectUI = createSelector( (state: { ui: UIState }): UIState => state.ui, (uiState) => uiState diff --git a/background/services/ledger/index.ts b/background/services/ledger/index.ts index b87a81632c..06feb107da 100644 --- a/background/services/ledger/index.ts +++ b/background/services/ledger/index.ts @@ -1,5 +1,6 @@ import Transport from "@ledgerhq/hw-transport" import TransportWebUSB from "@ledgerhq/hw-transport-webusb" +import { toChecksumAddress } from "@tallyho/hd-keyring" import Eth from "@ledgerhq/hw-app-eth" import { DeviceModelId } from "@ledgerhq/devices" import { @@ -25,7 +26,7 @@ import { ServiceCreatorFunction, ServiceLifecycleEvents } from "../types" import logger from "../../lib/logger" import { getOrCreateDB, LedgerAccount, LedgerDatabase } from "./db" import { ethersTransactionFromTransactionRequest } from "../chain/utils" -import { NETWORK_FOR_LEDGER_SIGNING } from "../../constants" +import { NETWORK_SUPPORTED_BY_LEDGER, ROOTSTOCK } from "../../constants" import { normalizeEVMAddress } from "../../lib/utils" import { AddressOnNetwork } from "../../accounts" @@ -113,15 +114,24 @@ type Events = ServiceLifecycleEvents & { export const idDerivationPath = "44'/60'/0'/0/0" +const ROOTSTOCK_DERIVATION_PATH = "44'/137'/0'/0" + async function deriveAddressOnLedger(path: string, eth: Eth) { const derivedIdentifiers = await eth.getAddress(path) + + if (path.includes(ROOTSTOCK_DERIVATION_PATH.slice(0, 8))) { + // ethersGetAddress rejects Rootstock addresses so using toChecksumAddress + return toChecksumAddress(derivedIdentifiers.address, +ROOTSTOCK.chainID) + } + const address = ethersGetAddress(derivedIdentifiers.address) return address } async function generateLedgerId( transport: Transport, - eth: Eth + eth: Eth, + derivationPath: string ): Promise<[string | undefined, LedgerType]> { let extensionDeviceType = LedgerType.UNKNOWN @@ -147,7 +157,7 @@ async function generateLedgerId( return [undefined, extensionDeviceType] } - const address = await deriveAddressOnLedger(idDerivationPath, eth) + const address = await deriveAddressOnLedger(derivationPath, eth) return [address, extensionDeviceType] } @@ -172,6 +182,8 @@ async function generateLedgerId( export default class LedgerService extends BaseService { #currentLedgerId: string | null = null + #derivationPath: string = idDerivationPath + transport: Transport | undefined = undefined #lastOperationPromise = Promise.resolve() @@ -209,7 +221,11 @@ export default class LedgerService extends BaseService { const eth = new Eth(this.transport) - const [id, type] = await generateLedgerId(this.transport, eth) + const [id, type] = await generateLedgerId( + this.transport, + eth, + this.#derivationPath + ) if (!id) { throw new Error("Can't derive meaningful identification address!") @@ -239,7 +255,7 @@ export default class LedgerService extends BaseService { this.emitter.emit("ledgerAdded", { id: this.#currentLedgerId, type, - accountIDs: [idDerivationPath], + accountIDs: [this.#derivationPath], metadata: { ethereumVersion: appData.version, isArbitraryDataSigningEnabled: appData.arbitraryDataEnabled !== 0, @@ -250,6 +266,10 @@ export default class LedgerService extends BaseService { }) } + setDefaultDerivationPath(path: string): void { + this.#derivationPath = path + } + #handleUSBConnect = async (event: USBConnectionEvent): Promise => { this.emitter.emit( "usbDeviceCount", @@ -535,7 +555,7 @@ export default class LedgerService extends BaseService { hexDataToSign: HexString ): Promise { if ( - !NETWORK_FOR_LEDGER_SIGNING.find((supportedNetwork) => + !NETWORK_SUPPORTED_BY_LEDGER.find((supportedNetwork) => sameNetwork(network, supportedNetwork) ) ) { diff --git a/ui/_locales/en/messages.json b/ui/_locales/en/messages.json index 20234fb0b5..ad4a5dadfb 100644 --- a/ui/_locales/en/messages.json +++ b/ui/_locales/en/messages.json @@ -99,6 +99,13 @@ "checkLedger": "Check Ledger", "onlyRejectFromLedger": "Tx can only be Rejected from Ledger", "onboarding": { + "selectLedgerApp": { + "initialScreenHeader": "Select Ledger Live App", + "ecosystem": "{{network}} ecosystem", + "includes": "Includes", + "subheading": "Select which app you would like to start with", + "continueButton": "Continue" + }, "prepare": { "continueButton": "Continue", "tryAgainButton": "Try Again", @@ -112,7 +119,8 @@ "stepsExplainer": "Please follow the steps below and click on Try Again!", "step1": "Plug in a single Ledger", "step2": "Enter pin to unlock", - "step3": "Open Ethereum App" + "step3": "Open {{network}} App", + "derivationPath": "Select derivation path to connect with ledger" }, "selectDevice": "Select the device", "clickConnect": "Click connect", diff --git a/ui/components/LedgerMenu/EcosystemNetworkIcon.tsx b/ui/components/LedgerMenu/EcosystemNetworkIcon.tsx new file mode 100644 index 0000000000..125d73e39f --- /dev/null +++ b/ui/components/LedgerMenu/EcosystemNetworkIcon.tsx @@ -0,0 +1,28 @@ +import React, { ReactElement } from "react" +import { EVMNetwork } from "@tallyho/tally-background/networks" + +interface Props { + network: EVMNetwork +} + +export default function EcosystemNetworkIcon(props: Props): ReactElement { + const { network } = props + + return ( + + + + ) +} diff --git a/ui/components/LedgerMenu/LedgerMenuProtocolList.tsx b/ui/components/LedgerMenu/LedgerMenuProtocolList.tsx new file mode 100644 index 0000000000..18beae8a51 --- /dev/null +++ b/ui/components/LedgerMenu/LedgerMenuProtocolList.tsx @@ -0,0 +1,49 @@ +import React, { ReactElement } from "react" +import { + ARBITRUM_ONE, + ETHEREUM, + OPTIMISM, + POLYGON, + ROOTSTOCK, +} from "@tallyho/tally-background/constants" +import { FeatureFlags, isEnabled } from "@tallyho/tally-background/features" +import { sameNetwork } from "@tallyho/tally-background/networks" +import { selectCurrentNetwork } from "@tallyho/tally-background/redux-slices/selectors" +import { useBackgroundSelector } from "../../hooks" +import LedgerMenuProtocolListItem from "./LedgerMenuProtocolListItem" + +const ledgerApps = [ + { + network: ETHEREUM, + ecosystem: [OPTIMISM, ARBITRUM_ONE], + }, + { + network: POLYGON, + }, + ...(isEnabled(FeatureFlags.SUPPORT_RSK) + ? [ + { + network: ROOTSTOCK, + }, + ] + : []), +] + +export default function LedgerMenuProtocolList(): ReactElement { + const currentNetwork = useBackgroundSelector(selectCurrentNetwork) + + return ( +
+
    + {ledgerApps.map((info) => ( + + ))} +
+
+ ) +} diff --git a/ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx b/ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx new file mode 100644 index 0000000000..949e4e23af --- /dev/null +++ b/ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx @@ -0,0 +1,151 @@ +import React, { ReactElement } from "react" +import { useTranslation } from "react-i18next" +import classNames from "classnames" +import { useDispatch } from "react-redux" +import { + setSelectedNetwork, + derivationPathChange, +} from "@tallyho/tally-background/redux-slices/ui" +import { EVMNetwork } from "@tallyho/tally-background/networks" +import { ETHEREUM, ROOTSTOCK } from "@tallyho/tally-background/constants" +import EcosystemNetworkIcon from "./EcosystemNetworkIcon" + +const DEFAULT_DERIVATION_PATH = "44'/60'/0'/0/0" +const ROOTSTOCK_DERIVATION_PATH = "44'/137'/0'/0" + +interface Props { + network: EVMNetwork + ecosystem?: EVMNetwork[] + isSelected: boolean +} + +export default function LedgerMenuProtocolListItem(props: Props): ReactElement { + const { t } = useTranslation("translation", { + keyPrefix: "ledger.onboarding.selectLedgerApp", + }) + const { isSelected, network, ecosystem } = props + const dispatch = useDispatch() + + const ledgerAppSubTitle = (networks?: EVMNetwork[]): string => { + if (networks) { + return `${t("includes")} ${(networks ?? []) + .map((networkItem) => networkItem.name) + .join(" & ")}` + } + + return "" + } + + const onNetworkSelect = () => { + dispatch(setSelectedNetwork(network)) + + if (network.chainID === ROOTSTOCK.chainID) { + dispatch(derivationPathChange(ROOTSTOCK_DERIVATION_PATH)) + } else { + dispatch(derivationPathChange(DEFAULT_DERIVATION_PATH)) + } + } + + return ( +
  • +
    +
    + +
    + {ecosystem && ( +
    + {ecosystem.map((ecosystemNetwork) => ( + + ))} +
    + )} +
    +
    +
    +
    +
    + {network.chainID === ETHEREUM.chainID + ? t("ecosystem", { network: network.name }) + : network.name} +
    +
    {ledgerAppSubTitle(ecosystem)}
    +
    + +
  • + ) +} + +LedgerMenuProtocolListItem.defaultProps = { + isSelected: false, +} diff --git a/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx b/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx index 5ff3fb1282..b3606e5809 100644 --- a/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx +++ b/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx @@ -11,6 +11,7 @@ import SharedButton from "../Shared/SharedButton" import SharedInput from "../Shared/SharedInput" import SharedModal from "../Shared/SharedModal" import SharedSelect, { Option } from "../Shared/SharedSelect" +import { useBackgroundSelector } from "../../hooks" // TODO make this network specific const initialDerivationPaths: Option[] = [ @@ -51,11 +52,16 @@ export default function OnboardingDerivationPathSelect({ }): ReactElement { const { t } = useTranslation("translation", { keyPrefix: "onboarding" }) const [derivationPaths, setDerivationPaths] = useState(initialDerivationPaths) - + const ledgerState = useBackgroundSelector((state) => state.ledger) const [modalStep, setModalStep] = useState(0) const [customPath, setCustomPath] = useState(initialCustomPath) const [customPathLabel, setCustomPathLabel] = useState("") - const [defaultIndex, setDefaultIndex] = useState() + const selectedIndex = initialDerivationPaths.findIndex( + (path) => path.value === `m/${ledgerState.derivationPath}` + ) + const [defaultIndex, setDefaultIndex] = useState( + selectedIndex === -1 ? 0 : selectedIndex + ) // Reset value to display placeholder after adding a custom path const customPathValue = customPath.isReset diff --git a/ui/pages/Ledger/LedgerPrepare.tsx b/ui/pages/Ledger/LedgerPrepare.tsx index b26e5f9239..64258434d8 100644 --- a/ui/pages/Ledger/LedgerPrepare.tsx +++ b/ui/pages/Ledger/LedgerPrepare.tsx @@ -1,7 +1,10 @@ -import React, { ReactElement } from "react" +import React, { ReactElement, useState } from "react" import { useTranslation } from "react-i18next" +import { selectCurrentNetwork } from "@tallyho/tally-background/redux-slices/selectors" import LedgerContinueButton from "../../components/Ledger/LedgerContinueButton" import LedgerPanelContainer from "../../components/Ledger/LedgerPanelContainer" +import { useBackgroundSelector } from "../../hooks" +import LedgerSelectNetwork from "./LedgerSelectNetwork" export default function LedgerPrepare({ onContinue, @@ -15,12 +18,19 @@ export default function LedgerPrepare({ const { t } = useTranslation("translation", { keyPrefix: "ledger.onboarding.prepare", }) + const selectedNetwork = useBackgroundSelector(selectCurrentNetwork) const buttonLabel = initialScreen ? t("continueButton") : t("tryAgainButton") const subHeadingWord = initialScreen ? t("subheadingWord1") : t("subheadingWord2") const warningText = deviceCount === 0 ? t("noLedgerConnected") : t("multipleLedgersConnected") + const [isNetworkSelected, setIsNetworkSelected] = useState(false) + + if (!isNetworkSelected) { + return setIsNetworkSelected(true)} /> + } + return (
  • {t("step1")}
  • {t("step2")}
  • -
  • {t("step3")}
  • +
  • {t("step3", { network: selectedNetwork.name })}
  • {buttonLabel} diff --git a/ui/pages/Ledger/LedgerSelectNetwork.tsx b/ui/pages/Ledger/LedgerSelectNetwork.tsx new file mode 100644 index 0000000000..4ab1ac765d --- /dev/null +++ b/ui/pages/Ledger/LedgerSelectNetwork.tsx @@ -0,0 +1,39 @@ +import React, { ReactElement } from "react" +import { useTranslation } from "react-i18next" +import LedgerContinueButton from "../../components/Ledger/LedgerContinueButton" +import LedgerPanelContainer from "../../components/Ledger/LedgerPanelContainer" +import LedgerMenuProtocolList from "../../components/LedgerMenu/LedgerMenuProtocolList" + +export default function LedgerSelectNetwork({ + onContinue, +}: { + onContinue: () => void +}): ReactElement { + const { t } = useTranslation("translation", { + keyPrefix: "ledger.onboarding.selectLedgerApp", + }) + + return ( + +
    + +
    + + {t("continueButton")} + + + +
    + ) +}