Skip to content

Commit

Permalink
refactor(wallet-mobile): network legacy drop stage - 3 (#3633)
Browse files Browse the repository at this point in the history
  • Loading branch information
stackchain authored Sep 16, 2024
1 parent 4edb935 commit 04fb19c
Show file tree
Hide file tree
Showing 49 changed files with 245 additions and 919 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {Platform, StyleSheet, Text, View} from 'react-native'
import {Button, useModal} from '../../../components'
import {Space} from '../../../components/Space/Space'
import globalMessages, {confirmationMessages} from '../../../kernel/i18n/global-messages'
import {catalystConfig} from '../../../yoroi-wallets/cardano/constants/catalyst-config'
import {usePortfolioPrimaryBalance} from '../../Portfolio/common/hooks/usePortfolioPrimaryBalance'
import {catalystConfig} from '../../WalletManager/common/adapters/cardano/catalyst-config'
import {useSelectedWallet} from '../../WalletManager/common/hooks/useSelectedWallet'

const formatter = amountFormatter({template: `{{value}} {{ticker}}`, dropTraillingZeros: true})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import {useQuery, UseQueryOptions} from 'react-query'
import {time} from '../../../kernel/constants'
import {throwLoggedError} from '../../../kernel/logger/helpers/throw-logged-error'
import {queryInfo} from '../../../kernel/query-client'
import {catalystConfig} from '../../../yoroi-wallets/cardano/constants/catalyst-config'
import {YoroiWallet} from '../../../yoroi-wallets/cardano/types'
import {isShelley} from '../../../yoroi-wallets/cardano/utils'
import {usePortfolioPrimaryBalance} from '../../Portfolio/common/hooks/usePortfolioPrimaryBalance'
import {catalystConfig} from '../../WalletManager/common/adapters/cardano/catalyst-config'
import {useSelectedWallet} from '../../WalletManager/common/hooks/useSelectedWallet'

export const useCanVote = (wallet: YoroiWallet) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import {logger} from '../../../../kernel/logger/logger'
import {useMetrics} from '../../../../kernel/metrics/metricsManager'
import {SetupWalletRouteNavigation} from '../../../../kernel/navigation'
import {isEmptyString} from '../../../../kernel/utils'
import {NUMBERS} from '../../../../yoroi-wallets/cardano/numbers'
import {usePlate} from '../../../../yoroi-wallets/hooks'
import {derivationConfig} from '../../../WalletManager/common/derivation-config'
import {useCreateWalletXPub} from '../../../WalletManager/common/hooks/useCreateWalletXPub'
import {useSelectedNetwork} from '../../../WalletManager/common/hooks/useSelectedNetwork'
import {parseWalletMeta} from '../../../WalletManager/common/validators/wallet-meta'
Expand All @@ -35,9 +35,7 @@ export const SaveReadOnlyWalletScreen = () => {
const {publicKeyHex, path, walletImplementation, accountVisual, walletIdChanged} = useSetupWallet()

const normalizedPath = path.map((i) => {
if (i >= NUMBERS.HARD_DERIVATION_START) {
return i - NUMBERS.HARD_DERIVATION_START
}
if (i >= derivationConfig.hardStart) return i - derivationConfig.hardStart
return i
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {NavigationRouteContext} from '@react-navigation/native'
import {storiesOf} from '@storybook/react-native'
import React from 'react'
import * as React from 'react'

import {NETWORK_ID, WALLET_IMPLEMENTATION_ID} from '../../../../yoroi-wallets/cardano/constants/testnet/constants'
import {networkConfigs} from '../../../WalletManager/network-manager/network-manager'
import {ConnectNanoXScreen} from './ConnectNanoXScreen'

const devices = [
Expand All @@ -18,8 +18,8 @@ const bleRoute = {
name: 'name',
params: {
useUSB: false,
networkId: NETWORK_ID,
walletImplementationId: WALLET_IMPLEMENTATION_ID,
networkId: networkConfigs['mainnet'].chainId,
walletImplementationId: 'cardano-bip44',
},
}

Expand All @@ -28,8 +28,8 @@ const usbRoute = {
name: 'name',
params: {
useUSB: true,
networkId: NETWORK_ID,
walletImplementationId: WALLET_IMPLEMENTATION_ID,
networkId: networkConfigs['mainnet'].chainId,
walletImplementationId: 'cardano-bip44',
},
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,9 @@ export const cardanoConfig = freeze(
params: {
minUtxoValue: 1_000_000n,
},
derivation: {
gapLimit: 20,
hardStart: 2_147_483_648,
keyLevel: {
root: 0,
purpose: 1,
coinType: 2,
account: 3,
role: 4,
index: 5,
},
},
implementations: {
// after shelley
// https://cips.cardano.org/cip/CIP-1852
'cardano-cip1852': {
features: {
staking: {
Expand Down Expand Up @@ -52,6 +42,8 @@ export const cardanoConfig = freeze(
},
},
},
// byron
// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
'cardano-bip44': {
features: {
staking: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {freeze} from 'immer'

// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
export const derivationConfig = freeze(
{
gapLimit: 20,
hardStart: 2_147_483_648,
keyLevel: {
root: 0,
purpose: 1,
coinType: 2,
account: 3,
role: 4,
index: 5,
},
} as const,
true,
)
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {Network} from '@yoroi/types'
import {freeze} from 'immer'

export function epochProgress(epochInfo: Network.EpochInfo) {
return (date: Date) => {
return (date: Date): Readonly<Network.EpochProgress> => {
const epochStart = epochInfo.start
const epochEnd = epochInfo.end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,17 @@ import {freeze} from 'immer'

import {throwLoggedError} from '../../../../kernel/logger/helpers/throw-logged-error'
import {makeCardanoWallet} from '../../../../yoroi-wallets/cardano/cardano-wallet'
import * as MAINNET from '../../../../yoroi-wallets/cardano/constants/mainnet/constants'
import * as SANCHONET from '../../../../yoroi-wallets/cardano/constants/sanchonet/constants'
import * as TESTNET from '../../../../yoroi-wallets/cardano/constants/testnet/constants'
import {networkManagers} from '../../common/constants'
import {WalletFactory} from '../../common/types'

const ShelleyWalletMainnet = makeCardanoWallet(networkManagers[Chain.Network.Mainnet], 'cardano-cip1852', MAINNET)
const ShelleyWalletTestnet = makeCardanoWallet(networkManagers[Chain.Network.Preprod], 'cardano-cip1852', TESTNET)
const ShelleySanchonetWallet = makeCardanoWallet(networkManagers[Chain.Network.Sancho], 'cardano-cip1852', SANCHONET)
const ShelleyPreviewWallet = makeCardanoWallet(networkManagers[Chain.Network.Preview], 'cardano-cip1852', SANCHONET)
const ByronWallet = makeCardanoWallet(networkManagers[Chain.Network.Mainnet], 'cardano-bip44', MAINNET)
const ByronWalletTestnet = makeCardanoWallet(networkManagers[Chain.Network.Preprod], 'cardano-bip44', TESTNET)
const ByronSanchonetWallet = makeCardanoWallet(networkManagers[Chain.Network.Sancho], 'cardano-bip44', SANCHONET)
const ByronPreviewWallet = makeCardanoWallet(networkManagers[Chain.Network.Preview], 'cardano-bip44', SANCHONET)
const ShelleyWalletMainnet = makeCardanoWallet(networkManagers[Chain.Network.Mainnet], 'cardano-cip1852')
const ShelleyWalletTestnet = makeCardanoWallet(networkManagers[Chain.Network.Preprod], 'cardano-cip1852')
const ShelleySanchonetWallet = makeCardanoWallet(networkManagers[Chain.Network.Sancho], 'cardano-cip1852')
const ShelleyPreviewWallet = makeCardanoWallet(networkManagers[Chain.Network.Preview], 'cardano-cip1852')
const ByronWallet = makeCardanoWallet(networkManagers[Chain.Network.Mainnet], 'cardano-bip44')
const ByronWalletTestnet = makeCardanoWallet(networkManagers[Chain.Network.Preprod], 'cardano-bip44')
const ByronSanchonetWallet = makeCardanoWallet(networkManagers[Chain.Network.Sancho], 'cardano-bip44')
const ByronPreviewWallet = makeCardanoWallet(networkManagers[Chain.Network.Preview], 'cardano-bip44')

/**
* Retrieves the wallet factory based on the network and implementation ID
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {freeze} from 'immer'

import {logger} from '../../../kernel/logger/logger'
import {NetworkTokenManagers} from '../common/types'
import {dateToEpochInfo} from './helpers/date-to-epoch-info'
import {epochProgress} from './helpers/epoch-progress'

export const primaryTokenInfoMainnet = createPrimaryTokenInfo({
decimals: 6,
Expand Down Expand Up @@ -65,7 +67,7 @@ export const shelleyPreprodEraConfig: Readonly<Network.EraConfig> = freeze(
true,
)

export const protocolParamsPlaceholder = freeze({
export const protocolParamsPlaceholder: Chain.Cardano.ProtocolParams = freeze({
linearFee: {
constant: '155381',
coefficient: '44',
Expand Down Expand Up @@ -129,7 +131,6 @@ export function buildNetworkManagers({
}: {
tokenManagers: NetworkTokenManagers
}): Readonly<Record<Chain.SupportedNetworks, Network.Manager>> {
// TODO: receive and attach the explorers here as well
const managers = Object.entries(networkConfigs).reduce<Record<Chain.SupportedNetworks, Network.Manager>>(
(networkManagers, [network, config]) => {
const tokenManager = tokenManagers[network as Chain.SupportedNetworks]
Expand All @@ -140,11 +141,20 @@ export function buildNetworkManagers({
const api = {
protocolParams: () =>
getProtocolParams().catch((error) => {
logger.error(`networkManager: ${network} protocolParams has failed`, {error})
return protocolParamsPlaceholder
logger.error(`networkManager: ${network} protocolParams has failed, using hardcoded`, {error})
return Promise.resolve(protocolParamsPlaceholder)
}),
}

const info = dateToEpochInfo(config.eras)
const epoch = {
info,
progress: (date: Date) => {
const currentInfo = info(date)
return epochProgress(currentInfo)(date)
},
}

const networkManager: Network.Manager = {
...config,
tokenManager,
Expand All @@ -153,6 +163,7 @@ export function buildNetworkManagers({
legacyRootStorage,
api,
explorers: explorerManager[network as Chain.SupportedNetworks],
epoch,
}
networkManagers[network as Chain.SupportedNetworks] = networkManager

Expand Down
50 changes: 14 additions & 36 deletions apps/wallet-mobile/src/legacy/Dashboard/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,17 @@ import {Banner, Button, useModal} from '../../components'
import {Space} from '../../components/Space/Space'
import {
useGovernanceStrings,
useIsGovernanceFeatureEnabled,
useIsParticipatingInGovernance,
WithdrawWarningModal,
} from '../../features/Staking/Governance'
import {useIsGovernanceFeatureEnabled} from '../../features/Staking/Governance'
import {useSelectedNetwork} from '../../features/WalletManager/common/hooks/useSelectedNetwork'
import {useSelectedWallet} from '../../features/WalletManager/common/hooks/useSelectedWallet'
import globalMessages from '../../kernel/i18n/global-messages'
import {DashboardRoutes, useWalletNavigation} from '../../kernel/navigation'
import {isEmptyString} from '../../kernel/utils'
import {getCardanoNetworkConfigById} from '../../yoroi-wallets/cardano/networks'
import {getCardanoBaseConfig} from '../../yoroi-wallets/cardano/utils'
import {useBalances, useIsOnline, useSync} from '../../yoroi-wallets/hooks'
import {Amounts} from '../../yoroi-wallets/utils'
import {
genCurrentEpochLength,
genCurrentSlotLength,
genTimeToSlot,
genToRelativeSlotNumber,
} from '../../yoroi-wallets/utils/timeUtils'
import {PoolTransitionNotice} from '../Staking/PoolTransition/PoolTransitionNotice'
import {usePoolTransition} from '../Staking/PoolTransition/usePoolTransition'
import {EpochProgress} from './EpochProgress'
Expand Down Expand Up @@ -204,27 +197,12 @@ const useCurrentTime = () => {

const EpochInfo = () => {
const currentTime = useCurrentTime()
const {wallet} = useSelectedWallet()
// TODO: revisit drop in favor of epochUtils
const config = getCardanoBaseConfig(getCardanoNetworkConfigById(wallet.isMainnet ? 1 : 300))

const toRelativeSlotNumberFn = genToRelativeSlotNumber(config)
const timeToSlotFn = genTimeToSlot(config)

const currentAbsoluteSlot = timeToSlotFn({
time: currentTime,
})

const currentRelativeTime = toRelativeSlotNumberFn(
timeToSlotFn({
time: Date.now(),
}).slot,
)
const epochLength = genCurrentEpochLength(config)()
const slotLength = genCurrentSlotLength(config)()

const secondsLeftInEpoch = (epochLength - currentRelativeTime.slot) * slotLength
const timeLeftInEpoch = new Date(1000 * secondsLeftInEpoch - currentAbsoluteSlot.msIntoSlot)
const {networkManager} = useSelectedNetwork()
const {epoch} = networkManager.epoch.info(new Date(currentTime))
const {
timeRemaining: {days, hours, minutes, seconds},
progress,
} = networkManager.epoch.progress(new Date(currentTime))

const leftPadDate = (num: number) => {
if (num < 10) return `0${num}`
Expand All @@ -233,13 +211,13 @@ const EpochInfo = () => {

return (
<EpochProgress
percentage={Math.floor((100 * currentRelativeTime.slot) / epochLength)}
currentEpoch={currentRelativeTime.epoch}
percentage={Math.floor(progress)}
currentEpoch={epoch}
endTime={{
d: leftPadDate(Math.floor(secondsLeftInEpoch / (3600 * 24))),
h: leftPadDate(timeLeftInEpoch.getUTCHours()),
m: leftPadDate(timeLeftInEpoch.getUTCMinutes()),
s: leftPadDate(timeLeftInEpoch.getUTCSeconds()),
d: leftPadDate(days),
h: leftPadDate(hours),
m: leftPadDate(minutes),
s: leftPadDate(seconds),
}}
/>
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {useTheme} from '@yoroi/theme'
import {Balance} from '@yoroi/types'
import React, {useEffect, useState} from 'react'
import {defineMessages, useIntl} from 'react-intl'
import {Platform, ScrollView, StyleSheet, View} from 'react-native'
Expand All @@ -12,10 +11,8 @@ import {useSelectedWallet} from '../../../features/WalletManager/common/hooks/us
import {debugWalletInfo, features} from '../../../kernel/features'
import globalMessages, {txLabels} from '../../../kernel/i18n/global-messages'
import {StakingCenterRoutes, useParams, useWalletNavigation} from '../../../kernel/navigation'
import {NETWORKS} from '../../../yoroi-wallets/cardano/networks'
import {NUMBERS} from '../../../yoroi-wallets/cardano/numbers'
import {Amounts, Entries, Quantities} from '../../../yoroi-wallets/utils'
import {formatTokenAmount, formatTokenWithText} from '../../../yoroi-wallets/utils/format'
import {Amounts, Entries} from '../../../yoroi-wallets/utils'
import {formatTokenAmount} from '../../../yoroi-wallets/utils/format'
import {useStakePoolInfoAndHistory} from '../../Dashboard/StakePoolInfo'
import {Instructions as HWInstructions} from '../../HW'

Expand Down Expand Up @@ -45,8 +42,6 @@ export const DelegationConfirmation = () => {
Entries.toAmounts(yoroiUnsignedTx.staking.delegations),
wallet.portfolioPrimaryTokenInfo.id,
)
const reward = approximateReward(stakingAmount.quantity)

const [password, setPassword] = useState('')
const [useUSB, setUseUSB] = useState(false)

Expand Down Expand Up @@ -104,8 +99,6 @@ export const DelegationConfirmation = () => {

<View style={styles.itemBlock}>
<Text style={styles.text}>{strings.rewardsExplanation}</Text>

<Text style={styles.rewards}>{formatTokenWithText(reward, wallet.portfolioPrimaryTokenInfo)}</Text>
</View>

{meta.isHW && <HWInstructions useUSB={useUSB} addMargin />}
Expand Down Expand Up @@ -166,10 +159,6 @@ const useStyles = () => {
color: color.gray_900,
...atoms.body_2_md_regular,
},
rewards: {
...atoms.body_1_lg_medium,
color: color.primary_600,
},
fees: {
textAlign: 'right',
color: color.gray_900,
Expand Down Expand Up @@ -211,15 +200,3 @@ const messages = defineMessages({
defaultMessage: '!!!Unknown pool',
},
})

/**
* returns approximate rewards per epoch in lovelaces
* TODO: based on https://staking.cardano.org/en/calculator/
* needs to be update per-network
*/
const approximateReward = (stakedQuantity: Balance.Quantity): Balance.Quantity => {
return Quantities.quotient(
Quantities.product([stakedQuantity, `${NETWORKS.HASKELL_SHELLEY.PER_EPOCH_PERCENTAGE_REWARD}`]),
NUMBERS.EPOCH_REWARD_DENOMINATOR.toString() as Balance.Quantity,
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import globalMessages from '../../../kernel/i18n/global-messages'
import {logger} from '../../../kernel/logger/logger'
import {useMetrics} from '../../../kernel/metrics/metricsManager'
import {StakingCenterRouteNavigation} from '../../../kernel/navigation'
import {NETWORKS} from '../../../yoroi-wallets/cardano/networks'
import {NotEnoughMoneyToSendError} from '../../../yoroi-wallets/cardano/types'
import {useStakingTx} from '../../Dashboard/StakePoolInfos'
import {PoolDetailScreen} from '../PoolDetails'
Expand Down Expand Up @@ -138,13 +137,9 @@ const noPoolDataDialog = defineMessages({
},
})

/**
* Prepares WebView's target staking URI
* @param {*} poolList : Array of delegated pool hash
*/
const prepareStakingURL = (locale: string, plate: string): string => {
// source=mobile is constant and already included
let finalURL = NETWORKS.HASKELL_SHELLEY.POOL_EXPLORER
let finalURL = 'https://adapools.yoroiwallet.com/?source=mobile'

const lang = locale.slice(0, 2)
finalURL += `&lang=${lang}`
Expand Down
Loading

0 comments on commit 04fb19c

Please sign in to comment.