From 512dc72e0791538e061c4d032daf2e5a2935d431 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 | 8 +- background/main.ts | 4 + background/redux-slices/ledger.ts | 8 + background/redux-slices/selectors/index.ts | 1 + .../redux-slices/selectors/ledgerSelectors.ts | 5 + background/redux-slices/ui.ts | 22 ++- background/services/ledger/index.ts | 32 +++- ui/_locales/en/messages.json | 10 +- ui/components/Ledger/LedgerPanelContainer.tsx | 1 + .../LedgerMenu/EcosystemNetworkIcon.tsx | 27 +++ .../LedgerMenu/LedgerMenuProtocolList.tsx | 52 ++++++ .../LedgerMenu/LedgerMenuProtocolListItem.tsx | 167 ++++++++++++++++++ .../OnboardingDerivationPathSelect.tsx | 11 +- ui/pages/Ledger/LedgerPrepare.tsx | 32 +++- ui/pages/Ledger/LedgerSelectNetwork.tsx | 39 ++++ 15 files changed, 401 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 6e3c090c2d..0454f4b70d 100644 --- a/background/constants/networks.ts +++ b/background/constants/networks.ts @@ -132,7 +132,13 @@ 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, + AVALANCHE, + BINANCE_SMART_CHAIN, +] // 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 243b18df90..d2d9afa18c 100644 --- a/background/main.ts +++ b/background/main.ts @@ -1031,6 +1031,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..5a8b614fea 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 = { @@ -95,6 +96,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 +231,7 @@ export const { addLedgerAccount, setUsbDeviceCount, removeDevice, + setDerivationPath, } = ledgerSlice.actions export default ledgerSlice.reducer diff --git a/background/redux-slices/selectors/index.ts b/background/redux-slices/selectors/index.ts index 3917a0578b..44251cc5c0 100644 --- a/background/redux-slices/selectors/index.ts +++ b/background/redux-slices/selectors/index.ts @@ -1,5 +1,6 @@ export * from "./activitiesSelectors" export * from "./accountsSelectors" +export * from "./ledgerSelectors" export * from "./keyringsSelectors" export * from "./signingSelectors" export * from "./dappSelectors" diff --git a/background/redux-slices/selectors/ledgerSelectors.ts b/background/redux-slices/selectors/ledgerSelectors.ts index 3c21a47ad3..6697300ad1 100644 --- a/background/redux-slices/selectors/ledgerSelectors.ts +++ b/background/redux-slices/selectors/ledgerSelectors.ts @@ -20,4 +20,9 @@ export const selectLedgerDeviceByAddresses = createSelector( } ) +export const selectLedgerDerivationPath = createSelector( + (state: RootState) => state.ledger.derivationPath, + (path) => path +) + export default {} diff --git a/background/redux-slices/ui.ts b/background/redux-slices/ui.ts index ab7861268e..bfacba8b32 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" export 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 fa44dbbcf9..4509ed797f 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 f82b5acc41..9d4e2d63aa 100644 --- a/ui/_locales/en/messages.json +++ b/ui/_locales/en/messages.json @@ -100,6 +100,13 @@ "onlyRejectFromLedger": "Tx can only be Rejected from Ledger", "onboarding": { "connecting": "Connecting...", + "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", @@ -113,7 +120,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/Ledger/LedgerPanelContainer.tsx b/ui/components/Ledger/LedgerPanelContainer.tsx index 54dbb1b38f..3020a9516e 100644 --- a/ui/components/Ledger/LedgerPanelContainer.tsx +++ b/ui/components/Ledger/LedgerPanelContainer.tsx @@ -30,6 +30,7 @@ export default function LedgerPanelContainer({ max-width: 24rem; margin: 0 auto; padding: 1rem; + position: relative; } .indicator { diff --git a/ui/components/LedgerMenu/EcosystemNetworkIcon.tsx b/ui/components/LedgerMenu/EcosystemNetworkIcon.tsx new file mode 100644 index 0000000000..06dcae51d1 --- /dev/null +++ b/ui/components/LedgerMenu/EcosystemNetworkIcon.tsx @@ -0,0 +1,27 @@ +import React, { ReactElement } from "react" + +interface Props { + networkName: string +} + +export default function EcosystemNetworkIcon(props: Props): ReactElement { + const { networkName } = props + + return ( + + + + ) +} diff --git a/ui/components/LedgerMenu/LedgerMenuProtocolList.tsx b/ui/components/LedgerMenu/LedgerMenuProtocolList.tsx new file mode 100644 index 0000000000..2a554216e6 --- /dev/null +++ b/ui/components/LedgerMenu/LedgerMenuProtocolList.tsx @@ -0,0 +1,52 @@ +import React, { ReactElement } from "react" +import { + ARBITRUM_ONE, + ETHEREUM, + OPTIMISM, + AVALANCHE, + BINANCE_SMART_CHAIN, + POLYGON, + ROOTSTOCK, +} from "@tallyho/tally-background/constants" +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 LEDGER_APPS = [ + { + network: ETHEREUM, + ecosystem: [OPTIMISM, ARBITRUM_ONE], + }, + { + network: POLYGON, + }, + { + network: ROOTSTOCK, + }, + { + network: AVALANCHE, + }, + { + network: BINANCE_SMART_CHAIN, + }, +] + +export default function LedgerMenuProtocolList(): ReactElement { + const currentNetwork = useBackgroundSelector(selectCurrentNetwork) + + return ( +
+
    + {LEDGER_APPS.map((info) => ( + + ))} +
+
+ ) +} diff --git a/ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx b/ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx new file mode 100644 index 0000000000..ed0e98d8ec --- /dev/null +++ b/ui/components/LedgerMenu/LedgerMenuProtocolListItem.tsx @@ -0,0 +1,167 @@ +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 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} +
    + {network.chainID === ETHEREUM.chainID && ( + + {t("includes")} + {ecosystem && + ecosystem.map(({ name }) => ( + + {name} + + ))} + + )} +
    + +
  • + ) +} + +LedgerMenuProtocolListItem.defaultProps = { + isSelected: false, +} diff --git a/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx b/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx index 4d5241b055..f29c1558fd 100644 --- a/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx +++ b/ui/components/Onboarding/OnboardingDerivationPathSelect.tsx @@ -5,12 +5,14 @@ import React, { useRef, useState, } from "react" +import { selectLedgerDerivationPath } from "@tallyho/tally-background/redux-slices/selectors" import { useTranslation } from "react-i18next" import { i18n } from "../../_locales/i18n" 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[] = [ @@ -55,11 +57,16 @@ export default function OnboardingDerivationPathSelect({ }): ReactElement { const { t } = useTranslation("translation", { keyPrefix: "onboarding" }) const [derivationPaths, setDerivationPaths] = useState(initialDerivationPaths) - + const ledgerDerivationPath = useBackgroundSelector(selectLedgerDerivationPath) 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/${ledgerDerivationPath}` + ) + 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..e1481c808f 100644 --- a/ui/pages/Ledger/LedgerPrepare.tsx +++ b/ui/pages/Ledger/LedgerPrepare.tsx @@ -1,7 +1,11 @@ -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 SharedIcon from "../../components/Shared/SharedIcon" +import { useBackgroundSelector } from "../../hooks" +import LedgerSelectNetwork from "./LedgerSelectNetwork" export default function LedgerPrepare({ onContinue, @@ -15,12 +19,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 ( + {isNetworkSelected && ( + { + e.stopPropagation() + setIsNetworkSelected(false) + }} + customStyles={` + position: absolute; + top: 45px; + left: -45px; + `} + /> + )} {!initialScreen && deviceCount !== 1 ? (
    @@ -45,7 +73,7 @@ export default function LedgerPrepare({
    1. {t("step1")}
    2. {t("step2")}
    3. -
    4. {t("step3")}
    5. +
    6. {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")} + + + +
    + ) +}