Skip to content

Commit

Permalink
Refactor and add types
Browse files Browse the repository at this point in the history
  • Loading branch information
PeterBenc committed Jan 14, 2021
1 parent c1d9be8 commit 8627201
Show file tree
Hide file tree
Showing 24 changed files with 152 additions and 165 deletions.
65 changes: 42 additions & 23 deletions app/frontend/actions.ts
Expand Up @@ -29,15 +29,16 @@ import sanitizeMnemonic from './helpers/sanitizeMnemonic'
import {initialState} from './store'
import {toCoins, toAda, roundWholeAdas} from './helpers/adaConverters'
import captureBySentry from './helpers/captureBySentry'
import {State, Ada, Lovelace, GetStateFn, SetStateFn, sourceAccountState} from './state'
import {State, Ada, Lovelace, GetStateFn, SetStateFn, getSourceAccountInfo} from './state'
import ShelleyCryptoProviderFactory from './wallet/shelley/shelley-crypto-provider-factory'
import {Wallet} from './wallet/wallet'
import {ShelleyWallet} from './wallet/shelley-wallet'
import {parseUnsignedTx} from './helpers/cliParser/parser'
import {TxPlan, unsignedPoolTxToTxPlan} from './wallet/shelley/shelley-transaction-planner'
import getDonationAddress from './helpers/getDonationAddress'
import {localStorageVars} from './localStorage'
import {AccountInfo} from './types'

let wallet: ReturnType<typeof Wallet>
let wallet: ReturnType<typeof ShelleyWallet>

const debounceEvent = (callback, time) => {
let interval
Expand Down Expand Up @@ -118,6 +119,26 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
}
}

const getWalletInfo = (accountsInfo: Array<AccountInfo>) => {
const totalWalletBalance = accountsInfo.reduce(
(a, {shelleyBalances}) =>
shelleyBalances.stakingBalance + shelleyBalances.nonStakingBalance + a,
0
)
const totalRewardsBalance = accountsInfo.reduce(
(a, {shelleyBalances}) => shelleyBalances.rewardsAccountBalance + a,
0
)
const shouldShowSaturatedBanner = accountsInfo.some(
({poolRecommendation}) => poolRecommendation.shouldShowSaturatedBanner
)
return {
totalWalletBalance,
totalRewardsBalance,
shouldShowSaturatedBanner,
}
}

/* LOADING WALLET */

const loadWallet = async (
Expand All @@ -140,18 +161,16 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
}
)

wallet = await Wallet({
wallet = await ShelleyWallet({
config,
cryptoProvider,
})

const {validStakepools} = await wallet.getValidStakepools()
const {accountsInfo} = await wallet.getAccountsInfo(validStakepools)
const {
totalRewardsBalance,
totalWalletBalance,
shouldShowSaturatedBanner,
} = wallet.getWalletInfo(accountsInfo)
const validStakepools = await wallet.getValidStakepools()
const accountsInfo = await wallet.getAccountsInfo(validStakepools)
const {totalRewardsBalance, totalWalletBalance, shouldShowSaturatedBanner} = getWalletInfo(
accountsInfo
)

const conversionRatesPromise = getConversionRates(state)
const usingHwWallet = wallet.isHwWallet()
Expand Down Expand Up @@ -216,14 +235,14 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
const reloadWalletInfo = async (state: State) => {
loadingAction(state, 'Reloading wallet info...')
try {
const {accountsInfo} = await wallet.getAccountsInfo(state.validStakepools)
const accountsInfo = await wallet.getAccountsInfo(state.validStakepools)
const conversionRates = getConversionRates(state)

// timeout setting loading state, so that loading shows even if everything was cached
setTimeout(() => setState({loading: false}), 500)
setState({
accountsInfo,
...wallet.getWalletInfo(accountsInfo),
...getWalletInfo(accountsInfo),
})
await fetchConversionRates(conversionRates)
} catch (e) {
Expand Down Expand Up @@ -539,15 +558,15 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
sendAmountValidator(
state.sendAmount.fieldValue,
state.sendAmount.coins,
sourceAccountState(state).balance
getSourceAccountInfo(state).balance
)
)
setErrorState(
'donationAmountValidationError',
donationAmountValidator(
state.donationAmount.fieldValue,
state.donationAmount.coins,
sourceAccountState(state).balance
getSourceAccountInfo(state).balance
)
)
}
Expand Down Expand Up @@ -610,7 +629,7 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
}
const validationError = txPlanValidator(
coins,
sourceAccountState(state).balance, // TODO: get new balance
getSourceAccountInfo(state).balance, // TODO: get new balance
plan,
donationAmount
)
Expand Down Expand Up @@ -825,7 +844,7 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
.getMaxNonStakingAmount(address)
const coins = maxAmount && maxAmount.sendAmount
const plan = await prepareTxPlan({address, coins, txType: 'convert'})
const validationError = txPlanValidator(coins, sourceAccountState(state).balance, plan)
const validationError = txPlanValidator(coins, getSourceAccountInfo(state).balance, plan)
if (validationError) {
setErrorState('transactionSubmissionError', validationError, {
shouldShowTransactionErrorModal: true,
Expand All @@ -841,10 +860,10 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
const withdrawRewards = async (state) => {
loadingAction(state, 'Preparing transaction...')
// TODO: get reward and normal balance from be not from state
const rewards = sourceAccountState(state).shelleyBalances.rewardsAccountBalance
const rewards = getSourceAccountInfo(state).shelleyBalances.rewardsAccountBalance
const plan = await prepareTxPlan({rewards, txType: 'withdraw'})
const withdrawalValidationError =
withdrawalPlanValidator(rewards, sourceAccountState(state).balance, plan) ||
withdrawalPlanValidator(rewards, getSourceAccountInfo(state).balance, plan) ||
wallet.checkCryptoProviderVersion('WITHDRAWAL')
if (withdrawalValidationError) {
setErrorState('transactionSubmissionError', withdrawalValidationError, {
Expand Down Expand Up @@ -926,13 +945,13 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
const state = getState()
setPoolInfo(state)
const poolHash = state.shelleyDelegation.selectedPool.poolHash
const stakingKeyRegistered = sourceAccountState(state).shelleyAccountInfo.hasStakingKey
const stakingKeyRegistered = getSourceAccountInfo(state).shelleyAccountInfo.hasStakingKey
const plan = await prepareTxPlan({poolHash, stakingKeyRegistered, txType: 'delegate'})
const newState = getState()
if (hasPoolIdentifiersChanged(newState)) {
return
}
const validationError = delegationPlanValidator(sourceAccountState(state).balance, plan)
const validationError = delegationPlanValidator(getSourceAccountInfo(state).balance, plan)
if (validationError) {
setErrorState('delegationValidationError', validationError, {
calculatingDelegationFee: false,
Expand Down Expand Up @@ -1014,7 +1033,7 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
updateStakePoolIdentifier(
newState,
null,
sourceAccountState(newState).poolRecommendation.recommendedPoolHash
getSourceAccountInfo(newState).poolRecommendation.recommendedPoolHash
)
}

Expand Down Expand Up @@ -1043,7 +1062,7 @@ export default ({setState, getState}: {setState: SetStateFn; getState: GetStateF
const accountsInfo = [...state.accountsInfo, accountInfo]
setState({
accountsInfo,
...wallet.getWalletInfo(accountsInfo),
...getWalletInfo(accountsInfo),
})
setActiveAccount(state, newAccount.accountIndex)
} catch (e) {
Expand Down
4 changes: 2 additions & 2 deletions app/frontend/components/common/balance.tsx
@@ -1,7 +1,7 @@
import {h} from 'preact'
import printAda from '../../helpers/printAda'
import Conversions from './conversions'
import {Lovelace, State, activeAccountState} from '../../state'
import {Lovelace, State, getActiveAccountInfo} from '../../state'
import {AdaIcon} from './svg'
import actions from '../../actions'
import {connect} from '../../libs/unistore/preact'
Expand Down Expand Up @@ -47,7 +47,7 @@ const Balance = ({balance, reloadWalletInfo, conversionRates}: Props) => (
export default connect(
(state: State) => ({
conversionRates: state.conversionRates && state.conversionRates.data,
balance: activeAccountState(state).balance,
balance: getActiveAccountInfo(state).balance,
}),
actions
)(Balance)
8 changes: 4 additions & 4 deletions app/frontend/components/pages/accounts/accountTile.tsx
Expand Up @@ -9,8 +9,8 @@ import tooltip from '../../common/tooltip'
type TileProps = {
accountIndex: number
ticker: string | null
availableBalance: Lovelace | null
rewardsBalance: Lovelace | null
availableBalance: number | null
rewardsBalance: number | null
shouldShowSaturatedBanner: boolean
setActiveAccount: any
exploreNewAccount: any
Expand Down Expand Up @@ -106,7 +106,7 @@ const AccountTile = ({
<div className="card-column account-item-info-wrapper">
<h2 className="card-title small-margin">Available balance</h2>
<div className="balance-amount small item">
<Balance value={availableBalance} />
<Balance value={availableBalance as Lovelace} />
</div>
<div className="mobile">
{shouldShowAccountInfo && (
Expand All @@ -119,7 +119,7 @@ const AccountTile = ({
<div className="card-column account-item-info-wrapper tablet-offset">
<h2 className="card-title small-margin">Rewards balance</h2>
<div className="balance-amount small item">
<Balance value={rewardsBalance} />
<Balance value={rewardsBalance as Lovelace} />
</div>
</div>
<div className="card-column account-item-info-wrapper">
Expand Down
3 changes: 2 additions & 1 deletion app/frontend/components/pages/accounts/accountsDashboard.tsx
Expand Up @@ -9,9 +9,10 @@ import SendTransactionModal from './sendTransactionModal'
import DelegationModal from './delegationModal'
import ConfirmTransactionDialog from '../../../../frontend/components/pages/sendAda/confirmTransactionDialog'
import AccountTile from './accountTile'
import {AccountInfo} from '../../../../frontend/types'

type DashboardProps = {
accountsInfo: Array<any>
accountsInfo: Array<AccountInfo>
reloadWalletInfo: any
shouldShowSendTransactionModal: boolean
shouldShowDelegationModal: boolean
Expand Down
12 changes: 6 additions & 6 deletions app/frontend/components/pages/advanced/keys.tsx
@@ -1,7 +1,7 @@
import {Fragment, h} from 'preact'
import {connect} from '../../../libs/unistore/preact'
import actions from '../../../actions'
import {State, activeAccountState} from '../../../state'
import {State, getActiveAccountInfo} from '../../../state'
import {parsePath} from '../../../helpers/pathParser'
import {encode} from 'borc'
import {LinkIconToKey} from '../delegations/common'
Expand Down Expand Up @@ -56,11 +56,11 @@ const Keys = ({byronXpub, shelleyXpub, accountPubkeyHex, stakingKey, stakingAcco

export default connect(
(state: State) => ({
shelleyXpub: activeAccountState(state).shelleyAccountInfo.shelleyXpub,
byronXpub: activeAccountState(state).shelleyAccountInfo.byronXpub,
accountPubkeyHex: activeAccountState(state).shelleyAccountInfo.accountPubkeyHex,
stakingKey: activeAccountState(state).shelleyAccountInfo.stakingKey,
stakingAccountAddress: activeAccountState(state).shelleyAccountInfo.stakingAccountAddress,
shelleyXpub: getActiveAccountInfo(state).shelleyAccountInfo.shelleyXpub,
byronXpub: getActiveAccountInfo(state).shelleyAccountInfo.byronXpub,
accountPubkeyHex: getActiveAccountInfo(state).shelleyAccountInfo.accountPubkeyHex,
stakingKey: getActiveAccountInfo(state).shelleyAccountInfo.stakingKey,
stakingAccountAddress: getActiveAccountInfo(state).shelleyAccountInfo.stakingAccountAddress,
}),
actions
)(Keys)
Expand Up @@ -2,7 +2,7 @@ import {Fragment, h} from 'preact'
import {connect} from '../../../libs/unistore/preact'
import actions from '../../../actions'
import printAda from '../../../helpers/printAda'
import {Lovelace, State, activeAccountState} from '../../../state'
import {Lovelace, State, getActiveAccountInfo} from '../../../state'
import {LinkIconToPool} from './common'
import {EpochDateTime} from '../common'
import roundNumber from './../../../helpers/roundNumber'
Expand Down Expand Up @@ -109,11 +109,11 @@ const CurrentDelegationPage = ({

export default connect(
(state: State) => ({
pool: activeAccountState(state).shelleyAccountInfo.delegation,
pool: getActiveAccountInfo(state).shelleyAccountInfo.delegation,
delegationValidationError: state.delegationValidationError,
calculatingDelegationFee: state.calculatingDelegationFee,
nearestReward: activeAccountState(state).shelleyAccountInfo.rewardDetails.nearest,
currentDelegationReward: activeAccountState(state).shelleyAccountInfo.rewardDetails
nearestReward: getActiveAccountInfo(state).shelleyAccountInfo.rewardDetails.nearest,
currentDelegationReward: getActiveAccountInfo(state).shelleyAccountInfo.rewardDetails
.currentDelegation,
}),
actions
Expand Down
6 changes: 3 additions & 3 deletions app/frontend/components/pages/delegations/delegatePage.tsx
Expand Up @@ -6,7 +6,7 @@ import printAda from '../../../helpers/printAda'
import {AdaIcon} from '../../common/svg'
import {getTranslation} from '../../../translations'
import ConfirmTransactionDialog from '../../pages/sendAda/confirmTransactionDialog'
import {sourceAccountState, Lovelace, State} from '../../../state'
import {getSourceAccountInfo, Lovelace, State} from '../../../state'
import {ADALITE_CONFIG} from '../../../config'
import Accordion from '../../common/accordion'

Expand Down Expand Up @@ -240,8 +240,8 @@ export default connect(
txSuccessTab: state.txSuccessTab,
gettingPoolInfo: state.gettingPoolInfo,
isShelleyCompatible: state.isShelleyCompatible,
poolRecommendation: sourceAccountState(state).poolRecommendation,
pool: sourceAccountState(state).shelleyAccountInfo.delegation,
poolRecommendation: getSourceAccountInfo(state).poolRecommendation,
pool: getSourceAccountInfo(state).shelleyAccountInfo.delegation,
isBigDelegator: state.isBigDelegator,
}),
actions
Expand Down
12 changes: 6 additions & 6 deletions app/frontend/components/pages/delegations/shelleyBalances.tsx
Expand Up @@ -5,7 +5,7 @@ import actions from '../../../actions'
import {connect} from '../../../libs/unistore/preact'
import tooltip from '../../common/tooltip'
import toLocalDate from '../../../../frontend/helpers/toLocalDate'
import {activeAccountState, State} from '../../../state'
import {getActiveAccountInfo, State} from '../../../state'

const shelleyBalances = ({
stakingBalance,
Expand Down Expand Up @@ -132,14 +132,14 @@ const shelleyBalances = ({

export default connect(
(state: State) => ({
stakingBalance: activeAccountState(state).shelleyBalances.stakingBalance,
nonStakingBalance: activeAccountState(state).shelleyBalances.nonStakingBalance,
rewardsAccountBalance: activeAccountState(state).shelleyBalances.rewardsAccountBalance,
balance: activeAccountState(state).balance,
stakingBalance: getActiveAccountInfo(state).shelleyBalances.stakingBalance,
nonStakingBalance: getActiveAccountInfo(state).shelleyBalances.nonStakingBalance,
rewardsAccountBalance: getActiveAccountInfo(state).shelleyBalances.rewardsAccountBalance,
balance: getActiveAccountInfo(state).balance,
calculatingDelegationFee: state.calculatingDelegationFee,
hwWalletName: state.hwWalletName,
isShelleyCompatible: state.isShelleyCompatible,
nearestReward: activeAccountState(state).shelleyAccountInfo.rewardDetails.nearest,
nearestReward: getActiveAccountInfo(state).shelleyAccountInfo.rewardDetails.nearest,
}),
actions
)(shelleyBalances)
Expand Up @@ -2,7 +2,7 @@ import {h, Component} from 'preact'
import actions from '../../../actions'
import {connect} from '../../../libs/unistore/preact'
import {LinkIconToPool} from './common'
import {activeAccountState, Lovelace, State} from '../../../state'
import {getActiveAccountInfo, Lovelace, State} from '../../../state'
import printAda from '../../../helpers/printAda'
import CopyOnClick from '../../common/copyOnClick'
import {EpochDateTime} from '../common'
Expand Down Expand Up @@ -228,7 +228,7 @@ class StakingHistoryPage extends Component<Props> {

export default connect(
(state: State) => ({
stakingHistory: activeAccountState(state).stakingHistory,
stakingHistory: getActiveAccountInfo(state).stakingHistory,
}),
actions
)(StakingHistoryPage)
4 changes: 2 additions & 2 deletions app/frontend/components/pages/receiveAda/myAddresses.tsx
@@ -1,10 +1,10 @@
import {State, activeAccountState} from '../../../../frontend/state'
import {State, getActiveAccountInfo} from '../../../../frontend/state'
import {h} from 'preact'
import {useSelector} from '../../../helpers/connect'
import AddressItem from './addressItem'

const MyAddresses = () => {
const addresses = useSelector((state: State) => activeAccountState(state).visibleAddresses)
const addresses = useSelector((state: State) => getActiveAccountInfo(state).visibleAddresses)

return (
<div className="addresses card">
Expand Down
Expand Up @@ -89,11 +89,6 @@ class ConfirmTransactionDialogClass extends Component<Props, {}> {
{summary.plan.outputs[0].address}
<AddressVerification address={summary.plan.outputs[0].address} />
</div>
</Fragment>
)}

{txConfirmType === 'convert' && (
<Fragment>
<div className="ada-label">Amount</div>
<div className="review-amount">{printAda(totalAmount)}</div>
</Fragment>
Expand Down
4 changes: 2 additions & 2 deletions app/frontend/components/pages/sendAda/sendAdaPage.tsx
Expand Up @@ -15,7 +15,7 @@ import {toCoins} from '../../../helpers/adaConverters'

import tooltip from '../../common/tooltip'
import AccountDropdown from '../accounts/accountDropdown'
import {sourceAccountState, State} from '../../../state'
import {getSourceAccountInfo, State} from '../../../state'

const {ADALITE_MIN_DONATION_VALUE} = ADALITE_CONFIG

Expand Down Expand Up @@ -262,7 +262,7 @@ export default connect(
sendTransactionSummary: state.sendTransactionSummary,
transactionFee: state.transactionFee,
txSuccessTab: state.txSuccessTab,
balance: sourceAccountState(state).balance,
balance: getSourceAccountInfo(state).balance,
sourceAccountIndex: state.sourceAccountIndex,
targetAccountIndex: state.targetAccountIndex,
}),
Expand Down

0 comments on commit 8627201

Please sign in to comment.