Skip to content

Commit

Permalink
Merge pull request #212 from polymorpher/state_refactor
Browse files Browse the repository at this point in the history
State refactor #2
  • Loading branch information
polymorpher committed Dec 17, 2021
2 parents 176a935 + 708f9be commit eba481f
Show file tree
Hide file tree
Showing 36 changed files with 247 additions and 193 deletions.
6 changes: 3 additions & 3 deletions code/client/src/api/flow.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import WalletConstants from '../constants/wallet'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'
import { EotpBuilders, SecureFlows, Flows, SmartFlows } from '../../../lib/api/flow'
import { api } from '../../../lib/api'

Expand All @@ -13,7 +13,7 @@ export const Chaining = {
WalletConstants.fetchDelaysAfterTransfer.forEach(t => {
setTimeout(() => {
addresses.forEach(address => {
dispatch(walletActions.fetchBalance({ address }))
dispatch(balanceActions.fetchBalance({ address }))
})
}, t)
})
Expand All @@ -23,7 +23,7 @@ export const Chaining = {
const { tokenType, contractAddress, tokenId, key } = token
WalletConstants.fetchDelaysAfterTransfer.forEach(t => {
setTimeout(() => {
dispatch(walletActions.fetchTokenBalance({ address, contractAddress, tokenType, tokenId, key }))
dispatch(balanceActions.fetchTokenBalance({ address, contractAddress, tokenType, tokenId, key }))
}, t)
})
},
Expand Down
10 changes: 5 additions & 5 deletions code/client/src/components/ERC20Grid.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Card, Image, Row, Space, Typography, Col, Divider, Button } from 'antd'
import { unionWith, isNull, isUndefined, uniqBy } from 'lodash'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'

import { CloseOutlined, PlusCircleOutlined } from '@ant-design/icons'
import React, { useState, useEffect, useRef, useCallback } from 'react'
Expand Down Expand Up @@ -34,7 +35,7 @@ export const handleTrackNewToken = async ({ newContractAddress, currentTrackedTo
try {
const tt = { tokenType: ONEConstants.TokenType.ERC20, tokenId: 0, contractAddress }
const key = ONEUtil.hexView(ONE.computeTokenKey(tt).hash)
dispatch(walletActions.fetchTokenBalance({ address, ...tt, key }))
dispatch(balanceActions.fetchTokenBalance({ address, ...tt, key }))
tt.key = key
try {
const { name, symbol, decimals } = await api.blockchain.getTokenMetadata(tt)
Expand Down Expand Up @@ -140,11 +141,10 @@ export const ERC20Grid = ({ address }) => {
const wallet = useSelector(state => state.wallet.wallets[address])
const network = useSelector(state => state.wallet.network)
const { selectedToken } = wallet
const tokenBalances = wallet.tokenBalances || {}
const trackedTokens = (wallet.trackedTokens || []).filter(e => e.tokenType === ONEConstants.TokenType.ERC20)
const untrackedTokenKeys = (wallet.untrackedTokens || [])
const balances = useSelector(state => state.wallet.balances)
const balance = balances[address] || 0
const balances = useSelector(state => state.balance)
const { balance = 0, tokenBalances = {} } = balances[address]
const { formatted } = util.computeBalance(balance)
const walletOutdated = !util.canWalletSupportToken(wallet)
const defaultTrackedTokens = withKeys(DefaultTrackedERC20(network))
Expand Down Expand Up @@ -209,7 +209,7 @@ export const ERC20Grid = ({ address }) => {
useEffect(() => {
(currentTrackedTokens || []).forEach(tt => {
const { tokenType, tokenId, contractAddress, key } = tt
dispatch(walletActions.fetchTokenBalance({ address, tokenType, tokenId, contractAddress, key }))
dispatch(balanceActions.fetchTokenBalance({ address, tokenType, tokenId, contractAddress, key }))
})
const newTokens = currentTrackedTokens.filter(e =>
defaultTrackedTokens.find(dt => dt.key === e.key) === undefined &&
Expand Down
8 changes: 5 additions & 3 deletions code/client/src/components/NFTGrid.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Card, Image, Row, Space, Typography, Col, Button, Carousel, Popconfirm, Spin } from 'antd'
import { Card, Image, Row, Space, Typography, Col, Button, Carousel, Spin } from 'antd'
import message from '../message'
import { unionWith, differenceBy } from 'lodash'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'
import React, { useState, useEffect } from 'react'
import { AverageRow, TallRow } from './Grid'
import { api } from '../../../lib/api'
Expand Down Expand Up @@ -285,7 +286,7 @@ export const useTokenBalanceTracker = ({ tokens, address }) => {
}
(tokens || []).forEach(tt => {
const { tokenType, tokenId, contractAddress, key } = tt
dispatch(walletActions.fetchTokenBalance({ address, tokenType, tokenId, contractAddress, key }))
dispatch(balanceActions.fetchTokenBalance({ address, tokenType, tokenId, contractAddress, key }))
})
}, [tokens, address])
}
Expand All @@ -294,8 +295,9 @@ export const NFTGrid = ({ address, onTrackNew }) => {
const history = useHistory()
const dispatch = useDispatch()
const wallet = useSelector(state => state.wallet.wallets[address])
const walletBalance = useSelector(state => state.balance[address] || {})
const selectedToken = util.isNFT(wallet.selectedToken) && wallet.selectedToken
const tokenBalances = wallet.tokenBalances || {}
const tokenBalances = walletBalance.tokenBalances || {}
const trackedTokens = (wallet.trackedTokens || []).filter(util.isNFT)
const [showTrackNew, setShowTrackNew] = useState(false)

Expand Down
5 changes: 3 additions & 2 deletions code/client/src/components/TrackNewNFT.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import BN from 'bn.js'
import ONEUtil from '../../../lib/util'
import ONE from '../../../lib/onewallet'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance/actions'
import { api } from '../../../lib/api'
import { TallRow } from './Grid'
import { Heading, Hint, InputBox, Label, LabeledRow } from './Text'
import { Heading, InputBox, LabeledRow } from './Text'

const TrackNewNFT = ({ onClose, onTracked, address }) => {
const dispatch = useDispatch()
Expand Down Expand Up @@ -63,7 +64,7 @@ const TrackNewNFT = ({ onClose, onTracked, address }) => {
const tokenType = tokenTypeInput.value
const tt = { tokenType, tokenId, contractAddress }
const key = ONEUtil.hexView(ONE.computeTokenKey(tt).hash)
dispatch(walletActions.fetchTokenBalance({ address, ...tt, key }))
dispatch(balanceActions.fetchTokenBalance({ address, ...tt, key }))
tt.key = key
try {
if (tt) {
Expand Down
4 changes: 2 additions & 2 deletions code/client/src/components/WalletTitle.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ const WalletTitle = ({ address, onQrCodeClick, onScanClick, noWarning }) => {
const [domain, setDomain] = useState(wallet.domain)
const [doubleLinked, setDoubleLinked] = useState(null)
const hasDomainName = domain && domain !== ''
const balances = useSelector(state => state.wallet.balances)
const balance = new BN(balances[address] || 0)
const balances = useSelector(state => state.balance)
const balance = new BN(balances[address]?.balance || 0)
useEffect(() => {
const f = async () => {
setDoubleLinked(null)
Expand Down
4 changes: 2 additions & 2 deletions code/client/src/integration/RequestCall.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import { WALLET_OUTDATED_DISABLED_TEXT, WalletSelector } from './Common'
const { Title, Paragraph } = Typography
const RequestCall = ({ caller, callback, dest, calldata: calldataB64Encoded, amount, from, verbose }) => {
dest = util.safeNormalizedAddress(dest)
const balances = useSelector(state => state.wallet.balances)
const price = useSelector(state => state.wallet.price)
const balances = useSelector(state => state.balance)
const price = useSelector(state => state.global.price)
const { isMobile } = useWindowDimensions()
const [selectedAddress, setSelectedAddress] = useState({})
const { formatted: amountFormatted, fiatFormatted: amountFiatFormatted } = util.computeBalance(amount || 0, price)
Expand Down
4 changes: 2 additions & 2 deletions code/client/src/integration/RequestPayment.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import { WalletSelector } from './Common'
const { Title, Paragraph } = Typography
const RequestPayment = ({ caller, callback, amount, dest, from }) => {
dest = util.safeNormalizedAddress(dest)
const balances = useSelector(state => state.wallet.balances)
const price = useSelector(state => state.wallet.price)
const balances = useSelector(state => state.balance)
const price = useSelector(state => state.global.price)
const [selectedAddress, setSelectedAddress] = useState({})
const { formatted: amountFormatted, fiatFormatted: amountFiatFormatted } = util.computeBalance(amount, price)

Expand Down
5 changes: 3 additions & 2 deletions code/client/src/pages/Create.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import AnimatedSection from '../components/AnimatedSection'
import qrcode from 'qrcode'
import storage from '../storage'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'
import cacheActions from '../state/modules/cache/actions'
import WalletConstants from '../constants/wallet'
import util, { useWindowDimensions, OSType, generateOtpSeed } from '../util'
Expand Down Expand Up @@ -309,7 +310,7 @@ const Create = ({ expertMode, showRecovery }) => {
await storeLayers()
await storeInnerLayers()
dispatch(walletActions.updateWallet(wallet))
dispatch(walletActions.fetchBalanceSuccess({ address, balance: 0 }))
dispatch(balanceActions.fetchBalanceSuccess({ address, balance: 0 }))
setAddress(address)
setDeploying(false)
setDeployed(true)
Expand Down Expand Up @@ -483,7 +484,7 @@ const Create = ({ expertMode, showRecovery }) => {
<TallRow>
{(deploying || !root) && <Space><Text>Working on your 1wallet...</Text><LoadingOutlined /></Space>}
{(!deploying && root && deployed) && <Text>Your 1wallet is ready!</Text>}
{(!deploying && root && deployed === false) && <Text>There was an issue deploying your 1wallet. <Button type='link' onClick={() => location.href = Paths.create}>Try again</Button>?</Text>}
{(!deploying && root && deployed === false) && <Text>There was an issue deploying your 1wallet. <Button type='link' onClick={() => (location.href = Paths.create)}>Try again</Button>?</Text>}
</TallRow>}
{!expertMode && <Hint>In beta, you can only spend {WalletConstants.defaultSpendingLimit} ONE per day</Hint>}
{!expertMode && <Button type='link' onClick={() => enableExpertMode(true)} style={{ padding: 0 }}>I want to create a higher limit wallet instead</Button>}
Expand Down
15 changes: 8 additions & 7 deletions code/client/src/pages/List.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'
import { values, omit } from 'lodash'
import { Card, Row, Space, Typography, Col, Tag } from 'antd'
import message from '../message'
Expand Down Expand Up @@ -30,13 +31,13 @@ const WalletCard = ({ wallet }) => {
const { address, name } = wallet
const oneAddress = getAddress(address).bech32
const dispatch = useDispatch()
const balance = useSelector(state => state.wallet.balances[address])
const price = useSelector(state => state.wallet.price)
const { formatted, fiatFormatted } = util.computeBalance(balance, price)
const walletBalance = useSelector(state => state.balance[address] || {})
const price = useSelector(state => state.global.price)
const { formatted, fiatFormatted } = util.computeBalance(walletBalance.balance || 0, price)
const walletOutdated = util.isWalletOutdated(wallet)

useEffect(() => {
dispatch(walletActions.fetchBalance({ address }))
dispatch(balanceActions.fetchBalance({ address }))
dispatch(walletActions.fetchWallet({ address }))
}, [location.pathname])

Expand Down Expand Up @@ -80,14 +81,14 @@ const WalletCard = ({ wallet }) => {
const List = () => {
const { isMobile } = useWindowDimensions()
const wallets = useSelector(state => state.wallet.wallets)
const balances = useSelector(state => state.wallet.balances)
const price = useSelector(state => state.wallet.price)
const balances = useSelector(state => state.balance)
const price = useSelector(state => state.global.price)
const network = useSelector(state => state.wallet.network)
const dispatch = useDispatch()
const totalBalance = Object.keys(balances)
.filter(a => wallets[a] && wallets[a].network === network && !wallets[a].temp)
.map(a => balances[a])
.reduce((a, b) => a.add(new BN(b, 10)), new BN(0)).toString()
.reduce((a, b) => a.add(new BN(b?.balance || 0, 10)), new BN(0)).toString()
const { formatted, fiatFormatted } = util.computeBalance(totalBalance, price)
const titleLevel = isMobile ? 4 : 3
const [purged, setPurged] = useState(false)
Expand Down
7 changes: 3 additions & 4 deletions code/client/src/pages/Restore.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import React, { useState, useEffect } from 'react'
import { useHistory } from 'react-router'
import { Heading, Hint } from '../components/Text'
import AnimatedSection from '../components/AnimatedSection'
import { Space, Progress, Col, Button, Typography, Divider } from 'antd'
import { Space, Progress, Button, Divider } from 'antd'
import message from '../message'
import api from '../api'
import ONEUtil from '../../../lib/util'
import WalletConstants from '../constants/wallet'
import storage from '../storage'
import { useDispatch, useSelector } from 'react-redux'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'
import util, { useWindowDimensions } from '../util'
import { handleAddressError } from '../handler'
import Paths from '../constants/paths'
Expand All @@ -19,12 +20,10 @@ import QrCodeScanner from '../components/QrCodeScanner'
import ScanGASteps from '../components/ScanGASteps'
import { parseOAuthOTP, parseMigrationPayload, parseAuthAccountName } from '../components/OtpTools'
import WalletCreateProgress from '../components/WalletCreateProgress'
import { AverageRow } from '../components/Grid'
import RestoreByCodes from './Restore/RestoreByCodes'
import SyncRecoveryFile from './Restore/SyncRecoveryFile'
import SetupNewCode from './Restore/SetupNewCode'
import LocalImport from '../components/LocalImport'
const { Title } = Typography

const Sections = {
Choose: 0,
Expand Down Expand Up @@ -176,7 +175,7 @@ const Restore = () => {
...securityParameters,
}
dispatch(walletActions.updateWallet(wallet))
dispatch(walletActions.fetchBalance({ address }))
dispatch(balanceActions.fetchBalance({ address }))
console.log('Completed wallet restoration', wallet)
message.success(`Wallet ${name} (${address}) is restored!`)
setTimeout(() => history.push(Paths.showAddress(address)), 1500)
Expand Down
3 changes: 2 additions & 1 deletion code/client/src/pages/Show.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useHistory, useRouteMatch, Redirect, useLocation, matchPath } from 'rea
import Paths from '../constants/paths'
import WalletConstants from '../constants/wallet'
import walletActions from '../state/modules/wallet/actions'
import { balanceActions } from '../state/modules/balance'
import util from '../util'
import ONEConstants from '../../../lib/constants'

Expand Down Expand Up @@ -73,7 +74,7 @@ const Show = () => {
if (address && (address !== selectedAddress)) {
dispatch(walletActions.selectWallet(address))
}
const fetch = () => dispatch(walletActions.fetchBalance({ address }))
const fetch = () => dispatch(balanceActions.fetchBalance({ address }))
fetch()
const handler = setInterval(() => {
if (!document.hidden) { fetch() }
Expand Down
2 changes: 1 addition & 1 deletion code/client/src/pages/Show/About.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const About = ({ address }) => {
const wallet = wallets[address] || {}
const backlinks = wallet.backlinks || []
const { spendingLimit, spendingInterval } = wallet
const price = useSelector(state => state.wallet.price)
const price = useSelector(state => state.global.price)
const { formatted: spendingLimitFormatted, fiatFormatted: spendingLimitFiatFormatted } = util.computeBalance(spendingLimit, price)
const [selectedLink, setSelectedLink] = useState()
const [inspecting, setInspecting] = useState()
Expand Down
8 changes: 4 additions & 4 deletions code/client/src/pages/Show/Balance.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ const Balance = ({ address }) => {
const wallets = useSelector(state => state.wallet.wallets)
const wallet = wallets[address] || {}
const network = useSelector(state => state.wallet.network)
const balances = useSelector(state => state.wallet.balances)
const price = useSelector(state => state.wallet.price)
const tokenBalances = wallet.tokenBalances || []
const balances = useSelector(state => state.balance)
const price = useSelector(state => state.global.price)
const { balance = 0, tokenBalances = {} } = balances[address]
const selectedToken = wallet?.selectedToken || HarmonyONE
const selectedTokenBech32Address = util.safeOneAddress(selectedToken.contractAddress)
const selectedTokenBalance = selectedToken.key === 'one' ? (balances[address] || 0) : (tokenBalances[selectedToken.key] || 0)
const selectedTokenBalance = selectedToken.key === 'one' ? balance : (tokenBalances[selectedToken.key] || 0)
const selectedTokenDecimals = selectedToken.decimals
const { formatted, fiatFormatted } = util.computeBalance(selectedTokenBalance, price, selectedTokenDecimals)
const { isMobile } = useWindowDimensions()
Expand Down
2 changes: 1 addition & 1 deletion code/client/src/pages/Show/BuyDaVinci.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const BuyDaVinci = ({ address, onSuccess, onClose }) => {
const { isMobile } = useWindowDimensions()
const [url, setUrl] = useState('')
const [pendingToken, setPendingToken] = useState(null)
const price = useSelector(state => state.wallet.price)
const price = useSelector(state => state.global.price)
const { formatted, fiatFormatted } = util.computeBalance(pendingToken?.price?.toString() || 0, price)

const { state: otpState } = useOtpState()
Expand Down
8 changes: 4 additions & 4 deletions code/client/src/pages/Show/Call.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState } from 'react'
import { Button, Row, Space, Typography, Input, Col } from 'antd'
import { Button, Space, Typography, Input, Col } from 'antd'
import message from '../../message'
import { CloseOutlined } from '@ant-design/icons'
import { Hint, InputBox, Label, Warning } from '../../components/Text'
Expand Down Expand Up @@ -50,9 +50,9 @@ const Call = ({

const { resetWorker, recoverRandomness } = useRandomWorker()

const balances = useSelector(state => state.wallet.balances)
const price = useSelector(state => state.wallet.price)
const { balance, formatted } = util.computeBalance(balances[address] || 0, price)
const balances = useSelector(state => state.balance)
const price = useSelector(state => state.global.price)
const { balance, formatted } = util.computeBalance(balances[address]?.balance || 0, price)

const [transferTo, setTransferTo] = useState({ value: prefillDest || '', label: prefillDest ? util.oneAddress(prefillDest) : '' })
const [inputAmount, setInputAmount] = useState(prefillAmount || '')
Expand Down
5 changes: 3 additions & 2 deletions code/client/src/pages/Show/Gift.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,10 @@ const Gift = ({
prefilledClaimInterval // int, non-zero
}) => {
const { isMobile } = useWindowDimensions()
const price = useSelector(state => state.wallet.price)
const price = useSelector(state => state.global.price)
const network = useSelector(state => state.wallet.network)
const wallets = useSelector(state => state.wallet.wallets)
const balances = useSelector(state => state.balance)
const wallet = wallets[address] || {}
const [stage, setStage] = useState(-1)
const doubleOtp = wallet.doubleOtp
Expand All @@ -104,7 +105,7 @@ const Gift = ({
const [editingSetting, setEditingSetting] = useState(false)
const [randomFactor, setRandomFactor] = useState(2)
const [message, setMessage] = useState()
const tokenBalances = wallet.tokenBalances || {}
const { tokenBalances = {} } = balances[address]

const [totalAmountInput, setTotalAmountInput] = useState(prefilledTotalAmount || 3) // ONEs, string
const [claimLimitInput, setClaimLimitInput] = useState(prefilledClaimLimit || 1) // ONEs, string
Expand Down
6 changes: 3 additions & 3 deletions code/client/src/pages/Show/PurchaseDomain.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,19 @@ const { balance: PAYMENT_EXCESS_BUFFER } = util.toBalance(0.1)
*/
const PurchaseDomain = ({ show, address, onClose }) => {
const dispatch = useDispatch()
const balances = useSelector(state => state.wallet.balances)
const balances = useSelector(state => state.balance)
const wallets = useSelector(state => state.wallet.wallets)
const wallet = wallets[address] || {}
const network = useSelector(state => state.wallet.network)
const oneBalance = balances[address] || 0
const oneBalance = balances[address]?.balance || 0
const [subdomain, setSubdomain] = useState(prepareName(wallet.name))
const [purchaseOnePrice, setPurchaseOnePrice] = useState({ value: '', formatted: '' })
const [domainFiatPrice, setDomainFiatPrice] = useState(0)
const [available, setAvailable] = useState(false)
const [enoughBalance, setEnoughBalance] = useState(false)
const [domainAvailable, setDomainAvailable] = useState(false)
const [checkingAvailability, setCheckingAvailability] = useState(true)
const price = useSelector(state => state.wallet.price)
const price = useSelector(state => state.global.price)
const validatedSubdomain = validateSubdomain(subdomain)

const [stage, setStage] = useState(-1)
Expand Down
Loading

0 comments on commit eba481f

Please sign in to comment.