Skip to content

Commit

Permalink
chore(wallet-mobile): clean ups (#3171)
Browse files Browse the repository at this point in the history
  • Loading branch information
stackchain committed Mar 26, 2024
1 parent 700beb3 commit a2b3df1
Show file tree
Hide file tree
Showing 12 changed files with 7 additions and 77 deletions.
2 changes: 2 additions & 0 deletions apps/wallet-mobile/src/components/Modal/ModalContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {useNavigation} from '@react-navigation/native'
import React from 'react'
import {Keyboard} from 'react-native'

type ModalState = {
height: number
Expand Down Expand Up @@ -43,6 +44,7 @@ export const ModalProvider = ({
}
},
openModal: (title: ModalState['title'], content: ModalState['content'], height?: ModalState['height']) => {
Keyboard.dismiss()
dispatch({type: 'open', title, content, height})
navigation.navigate('modal')
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {linksCardanoModuleMaker, LinksTransferRequestAdaWithLinkParams, LinksYoroiAction, useLinks} from '@yoroi/links'
import {useTransfer} from '@yoroi/transfer'
import * as React from 'react'
import {InteractionManager, Keyboard} from 'react-native'
import {InteractionManager} from 'react-native'

import {useModal} from '../../../components/Modal/ModalContext'
import {useSelectedWalletContext} from '../../../SelectedWallet'
Expand Down Expand Up @@ -63,7 +63,6 @@ export const useLinksRequestAction = () => {

const openRequestedPaymentAdaWithLink = React.useCallback(
({params, isTrusted}: {params: LinksTransferRequestAdaWithLinkParams; isTrusted: boolean}, decimals: number) => {
Keyboard.dismiss()
const title = isTrusted ? strings.trustedPaymentRequestedTitle : strings.untrustedPaymentRequestedTitle
const handleOnContinue = () =>
startTransferWithLink(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react'
import {InteractionManager, Keyboard} from 'react-native'
import {InteractionManager} from 'react-native'

import {useModal} from '../../../components/Modal/ModalContext'
import {isEmptyString} from '../../../utils/utils'
Expand All @@ -13,7 +13,6 @@ export const useLinksRequestRedirect = (redirectTo?: string) => {

const askToRedirect = React.useCallback(
(link: string) => {
Keyboard.dismiss()
const content = <AskToRedirectScreen link={link} />
openModal(strings.askToRedirectTitle, content, heightBreakpoint)
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useLinks} from '@yoroi/links'
import * as React from 'react'
import {InteractionManager, Keyboard} from 'react-native'
import {InteractionManager} from 'react-native'

import {useModal} from '../../../components/Modal/ModalContext'
import {useSelectedWalletContext} from '../../../SelectedWallet'
Expand All @@ -15,7 +15,6 @@ export const useLinksRequestWallet = () => {
const {action} = useLinks()

const askToOpenAWallet = React.useCallback(() => {
Keyboard.dismiss()
const content = <AskToOpenWalletScreen />
openModal(strings.askToOpenAWalletTitle, content, heightBreakpoint)
}, [openModal, strings.askToOpenAWalletTitle])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ export const RequestSpecificAmountScreen = () => {
const {openModal} = useModal()

const handleOnGenerateLink = React.useCallback(() => {
Keyboard.dismiss()

track.receiveAmountGeneratedPageViewed({ada_amount: Number(amount)})
openModal(strings.amountToReceive, <Modal amount={amount} address={selectedAddress} />, modalHeight)
}, [track, amount, openModal, strings.amountToReceive, selectedAddress, modalHeight])
Expand Down
1 change: 0 additions & 1 deletion apps/wallet-mobile/src/metrics/metricsManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ const infoPlugin: EnrichmentPlugin = {
type: PluginType.ENRICHMENT,
setup: async () => Promise.resolve(),
execute: async (event: Event) => {
Logger.info('[metrics-react-native]', event.event_type, event.event_properties ?? '- No properties')
return Promise.resolve(event)
},
}
Expand Down
3 changes: 0 additions & 3 deletions apps/wallet-mobile/src/wallet-manager/walletManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import uuid from 'uuid'
import {getCardanoWalletFactory} from '../yoroi-wallets/cardano/getWallet'
import {isYoroiWallet, YoroiWallet} from '../yoroi-wallets/cardano/types'
import {HWDeviceInfo} from '../yoroi-wallets/hw'
import {Logger} from '../yoroi-wallets/logging'
import {makeWalletEncryptedStorage} from '../yoroi-wallets/storage'
import {Keychain} from '../yoroi-wallets/storage/Keychain'
import {rootStorage} from '../yoroi-wallets/storage/rootStorage'
Expand Down Expand Up @@ -123,8 +122,6 @@ export class WalletManager {

await this.walletsRootStorage.setItem(id, walletMeta)

Logger.debug('WalletManager::saveWallet::wallet', wallet)

if (isYoroiWallet(wallet)) {
return wallet
}
Expand Down
11 changes: 2 additions & 9 deletions apps/wallet-mobile/src/yoroi-wallets/cardano/api/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type RequestMethod = 'POST' | 'GET'

type ResponseChecker<T> = (rawResponse: Record<string, any>, requestPayload: Record<string, any>) => Promise<T>

const _checkResponse: ResponseChecker<Record<string, any>> = async (rawResponse, requestPayload) => {
const _checkResponse: ResponseChecker<Record<string, any>> = async (rawResponse) => {
let responseBody = {}

try {
Expand All @@ -28,9 +28,6 @@ const _checkResponse: ResponseChecker<Record<string, any>> = async (rawResponse,
throw new ApiHistoryError((responseBody as any).error.response)
}

Logger.debug('Bad status code from server', status)
Logger.debug('Request payload:', requestPayload)
Logger.info('response', responseBody)
throw new ApiError((responseBody as any).error?.response)
}

Expand All @@ -47,8 +44,6 @@ type FetchRequest<T> = {
export const checkedFetch = (request: FetchRequest<any>) => {
const {endpoint, payload, method, headers} = request
const checkResponse = request.checkResponse || _checkResponse
Logger.info(`API call: ${endpoint}`)

const args = [
endpoint,
{
Expand All @@ -60,7 +55,7 @@ export const checkedFetch = (request: FetchRequest<any>) => {

return fetch(...args) // Fetch throws only for network/dns/related errors, not http statuses
.catch((e) => {
Logger.info(`API call ${endpoint} failed`, e)
Logger.error(`API call ${endpoint} failed`, e)

/* It really is TypeError according to
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Expand All @@ -72,9 +67,7 @@ export const checkedFetch = (request: FetchRequest<any>) => {
throw e
})
.then(async (r) => {
Logger.info(`API call ${endpoint} finished`)
const response = await checkResponse(r, payload)
// Logger.debug('Response:', response)
return response
})
}
Expand Down
17 changes: 0 additions & 17 deletions apps/wallet-mobile/src/yoroi-wallets/cardano/byron/ByronWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,6 @@ export class ByronWallet implements YoroiWallet {
static async restore({walletMeta, storage}: {storage: App.Storage; walletMeta: WalletMeta}) {
const data = await storage.getItem('data', parseWalletJSON)
if (!data) throw new Error('Cannot read saved data')
Logger.debug('openWallet::data', data)
Logger.info('restore wallet', walletMeta.name)

const networkId = data.networkId ?? walletMeta.networkId // can be null for versions < 3.0.0
const {internalChain, externalChain} = addressChains.restore({data, networkId})
Expand Down Expand Up @@ -395,8 +393,6 @@ export class ByronWallet implements YoroiWallet {
timeout: NodeJS.Timeout | null = null

startSync() {
Logger.info(`starting wallet: ${this.id}`)

const backgroundSync = async () => {
try {
await this.tryDoFullSync()
Expand All @@ -415,7 +411,6 @@ export class ByronWallet implements YoroiWallet {

stopSync() {
if (!this.timeout) return
Logger.info(`stopping wallet: ${this.id}`)
clearTimeout(this.timeout)
}

Expand Down Expand Up @@ -453,7 +448,6 @@ export class ByronWallet implements YoroiWallet {
assert(this.hwDeviceInfo != null, 'no device info for hardware wallet')
}
} catch (e) {
Logger.error('wallet::_integrityCheck', e)
throw new InvalidState((e as Error).message)
}
}
Expand Down Expand Up @@ -541,7 +535,6 @@ export class ByronWallet implements YoroiWallet {
.then((key) => key.derive(NUMBERS.STAKING_KEY_INDEX))
.then((key) => key.toRawKey())

Logger.info(`getStakingKey: ${Buffer.from(await stakingKey.asBytes()).toString('hex')}`)
return stakingKey
}

Expand Down Expand Up @@ -792,7 +785,6 @@ export class ByronWallet implements YoroiWallet {
})
} catch (e) {
if (e instanceof NotEnoughMoneyToSendError || e instanceof NoOutputsError) throw e
Logger.error(`shelley::createUnsignedGovernanceTx:: ${(e as Error).message}`, e)
throw new CardanoError((e as Error).message)
}
}
Expand Down Expand Up @@ -907,8 +899,6 @@ export class ByronWallet implements YoroiWallet {
}

async createVotingRegTx(pin: string, supportsCIP36: boolean) {
Logger.debug('CardanoWallet::createVotingRegTx called')

const bytes = await generatePrivateKeyForCatalyst()
.then((key) => key.toRawKey())
.then((key) => key.asBytes())
Expand Down Expand Up @@ -999,7 +989,6 @@ export class ByronWallet implements YoroiWallet {
}
} catch (e) {
if (e instanceof LocalizableError || e instanceof ExtendableError) throw e
Logger.error(`shelley::createVotingRegTx:: ${(e as Error).message}`, e)
throw new CardanoError((e as Error).message)
}
}
Expand Down Expand Up @@ -1058,7 +1047,6 @@ export class ByronWallet implements YoroiWallet {
const appAdaVersion = await getCardanoAppMajorVersion(this.hwDeviceInfo, useUSB)

if (!doesCardanoAppVersionSupportCIP36(appAdaVersion) && unsignedTx.voting.registration) {
Logger.info('CardanoWallet::signTxWithLedger: Ledger app version <= 5')
const ledgerPayload = await Cardano.buildVotingLedgerPayloadV5(
unsignedTx.unsignedTx,
Number.parseInt(this.getChainNetworkId(), 10),
Expand Down Expand Up @@ -1118,7 +1106,6 @@ export class ByronWallet implements YoroiWallet {

async submitTransaction(signedTx: string) {
const response: any = await legacyApi.submitTransaction(signedTx, this.getBackendConfig())
Logger.info(response)
return response as any
}

Expand Down Expand Up @@ -1383,8 +1370,6 @@ export class ByronWallet implements YoroiWallet {
assert(this.isInitialized, 'doFullSync: isInitialized')

if (isJormungandr(this.networkId)) return
Logger.info('Discovery done, now syncing transactions')

await this.discoverAddresses()

await Promise.all([
Expand Down Expand Up @@ -1434,8 +1419,6 @@ export class ByronWallet implements YoroiWallet {
// ========== UI state ============= //

private updateState(update: Partial<WalletState>) {
Logger.debug('Wallet::updateState', update)

this.state = {
...this.state,
...update,
Expand Down
14 changes: 0 additions & 14 deletions apps/wallet-mobile/src/yoroi-wallets/cardano/hw/hw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,14 @@ const isAdaAppClosedError = (e: Error | unknown): boolean => {

const mapLedgerError = (e: Error | any): Error | LocalizableError => {
if (isAdaAppClosedError(e)) {
Logger.info('ledgerUtils::mapLedgerError: Ada app closed', e)
return new AdaAppClosedError()
} else if (isUserError(e)) {
Logger.info('ledgerUtils::mapLedgerError: User-side error', e)
return new LedgerUserError()
} else if (isRejectedError(e)) {
Logger.info('ledgerUtils::mapLedgerError: Rejected by user error', e)
return new RejectedByUserError()
} else if (isConnectionError(e)) {
Logger.info('ledgerUtils::mapLedgerError: General/BleError', e)
return new GeneralConnectionError()
} else if (e instanceof DeprecatedAdaAppError) {
Logger.info('ledgerUtils::mapLedgerError: Deprecated Ada app', e)
return e
} else {
Logger.error('ledgerUtils::mapLedgerError: Unexpected error', e)
Expand Down Expand Up @@ -216,24 +211,19 @@ export const getHWDeviceInfo = async (
useUSB = false,
): Promise<HWDeviceInfo> => {
try {
Logger.debug('ledgerUtils::getHWDeviceInfo called')
const appAda = await connectionHandler(deviceId, deviceObj, useUSB)
// assume single account in Yoroi
const accountPath = makeCardanoAccountBIP44Path(getWalletType(walletImplementationId), NUMBERS.ACCOUNT_INDEX)
Logger.debug('bip44 account path', accountPath)
// get Cardano's first account
// i.e hdPath = [2147483692, 2147485463, 2147483648]
const extendedPublicKeyResp: GetExtendedPublicKeyResponse = await appAda.getExtendedPublicKey(accountPath)
Logger.debug('extended public key', extendedPublicKeyResp)
const serial: GetSerialResponse = await appAda.getSerial()
const hwDeviceInfo = normalizeHWResponse({
extendedPublicKeyResp,
deviceId,
deviceObj,
...serial,
})
Logger.info('ledgerUtils::getHWDeviceInfo: Ledger device OK')
Logger.info('hwDeviceInfo', hwDeviceInfo)
await appAda.transport.close()
return hwDeviceInfo
} catch (e) {
Expand Down Expand Up @@ -295,13 +285,9 @@ export const signTxWithLedger = async (
useUSB: boolean,
) => {
try {
Logger.debug('ledgerUtils::signTxWithLedger called')
const appAda = await connectionHandler(hwDeviceInfo.hwFeatures.deviceId, hwDeviceInfo.hwFeatures.deviceObj, useUSB)
Logger.debug('ledgerUtils::signTxWithLedger inputs', signRequest.tx.inputs)
Logger.debug('ledgerUtils::signTxWithLedger outputs', signRequest.tx.outputs)
const ledgerSignature: SignTransactionResponse = await appAda.signTransaction(signRequest)
await appAda.transport.close()
Logger.debug('ledgerUtils::ledgerSignature', JSON.stringify(ledgerSignature))
return ledgerSignature
} catch (e) {
throw mapLedgerError(e)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import ExtendableError from 'es6-error'

import {Logger} from '../../logging'

export class IsLockedError extends ExtendableError {}
export type Mutex = {
lock: Promise<any> | null | undefined
Expand All @@ -14,20 +12,15 @@ export const delay = (duration: number): Promise<void> => {
}
// Try locking mutex, waits if cannot be locked
export const synchronize = <T>(mutex: Mutex, factory: () => Promise<T>): Promise<T> => {
Logger.debug('Synchronize on', mutex)

if (!mutex.lock) {
Logger.debug('Synchronize lock fastpath')
// We are first and can grab lock
const myPromise = factory()
mutex.lock = myPromise
return myPromise.finally(() => {
Logger.debug('Synchronize unlock fastpath')
// clean up if we do not have anything waiting on lock
if (mutex.lock === myPromise) mutex.lock = null
})
} else {
Logger.debug('Synchronize lock wait')
// We need to update lock and at the same time wait for the original
// function
const orig: Promise<unknown> = mutex.lock as any
Expand All @@ -43,13 +36,11 @@ export const synchronize = <T>(mutex: Mutex, factory: () => Promise<T>): Promise
mutex.lock = newLock
// note: don't await on purpose
orig.finally(() => {
Logger.debug('Synchronize lock resume')
// Ok, waiting for the original is done, now let's do our work
const myPromise = factory()
myPromise
.finally(() => {
// clean up if we do not have anything waiting on lock
Logger.debug('Synchronize unlock')
if (mutex.lock === newLock) mutex.lock = null
})
.then(_resolve)
Expand Down

0 comments on commit a2b3df1

Please sign in to comment.