Skip to content

Commit

Permalink
move wallet state to contect, walletHook only for reading
Browse files Browse the repository at this point in the history
  • Loading branch information
anyxem committed Apr 7, 2024
1 parent 56d49eb commit 44bfd68
Show file tree
Hide file tree
Showing 10 changed files with 166 additions and 134 deletions.
7 changes: 6 additions & 1 deletion src/components/composed/Header/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import { ReactComponent as ExpandImg } from '@Assets/images/icon-expand.svg'
import { ReactComponent as SettingsImg } from '@Assets/images/settings.svg'

import { Button, Logo, Tooltip } from '@BasicComponents'
import { AccountContext } from '@Contexts'
import { AccountContext, NetworkContext } from '@Contexts'

import './Header.css'

const Header = ({ customBackAction, noBackButton = false }) => {
const network = useContext(NetworkContext)
const [unlocked, setUnlocked] = useState(false)
const [tooltipVisible, setTooltipVisible] = useState(false)
const tooltipMessage = 'Expand view'
Expand Down Expand Up @@ -60,6 +61,10 @@ const Header = ({ customBackAction, noBackButton = false }) => {

return (
<header data-testid="header-container">
<pre style={{ position: 'absolute', top: 1, left: 1 }}>
{JSON.stringify(network)}
</pre>

{!noBackButton && (
<Button
alternate
Expand Down
114 changes: 114 additions & 0 deletions src/contexts/NetworkProvider/NetworkProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import React, { createContext, useContext, useEffect, useState } from 'react'
import {
getAddressData,
getChainTip,
getTransactionData,
} from '../../services/API/Mintlayer/Mintlayer'
import { AccountContext, SettingsContext } from '@Contexts'
import { AppInfo } from '@Constants'
import { ML_ATOMS_PER_COIN } from '../../utils/Constants/AppInfo/AppInfo'
import { ML } from '@Helpers'

const NetworkContext = createContext()

const REFRESH_INTERVAL = 1000

const NetworkProvider = ({ value: propValue, children }) => {
const { addresses } = useContext(AccountContext)
const { networkType } = useContext(SettingsContext)

const currentMlAddresses =
networkType === AppInfo.NETWORK_TYPES.MAINNET
? addresses.mlMainnetAddress
: addresses.mlTestnetAddresses

const [onlineHeight, setOnlineHeight] = useState(0)
const [currentHeight, setCurrentHeight] = useState(0)
const [balance, setBalance] = useState(0)
const [lockedBalance, setLockedBalance] = useState(0)
// const [addresses, setAddresses] = useState({})
// const [utxos, setUtxos] = useState({})
const [transactions, setTransactions] = useState([])

useEffect(() => {
if (onlineHeight > currentHeight) {
console.log('fetch data')
setCurrentHeight(onlineHeight)
// fetch addresses, utxos, transactions
const getData = async () => {
// fetch address data
const addressList = [
...currentMlAddresses.mlReceivingAddresses,
...currentMlAddresses.mlChangeAddresses,
]
const addresses = addressList.map((address) => getAddressData(address))
const addresses_data = await Promise.all(addresses)
let available_balance = BigInt(0)
let locked_balance = BigInt(0)
const transaction_ids = []
addresses_data.forEach((address_data) => {
const { coin_balance, locked_coin_balance, transaction_history } =
JSON.parse(address_data)
console.log('===', coin_balance, transaction_history)
available_balance = coin_balance
? available_balance + BigInt(coin_balance.atoms)
: available_balance
locked_balance = locked_coin_balance
? locked_balance + BigInt(locked_coin_balance.atoms)
: locked_balance
transaction_ids.push(...transaction_history)
})
console.log('available_balance===', available_balance.toString())
setBalance(Number(available_balance) / ML_ATOMS_PER_COIN)
setLockedBalance(Number(locked_balance) / ML_ATOMS_PER_COIN)

// fetch transactions data
const transactions = transaction_ids.map((txid) =>
getTransactionData(txid),
)
const transactions_data = await Promise.all(transactions)
console.log('transactions_data', transactions_data)

const parsedTransactions = ML.getParsedTransactions(
transactions_data,
addressList,
)
console.log(parsedTransactions)
setTransactions(parsedTransactions)
}
getData()
}
}, [onlineHeight, currentHeight])

useEffect(() => {
const data = setInterval(() => {
// fetch current network height
const getData = async () => {
const result = await getChainTip()
const { block_height } = JSON.parse(result)
setOnlineHeight(block_height)
}
getData()
}, REFRESH_INTERVAL)

return () => clearInterval(data)
}, [])

const value = {
balance,
lockedBalance,
// addresses,
// utxos,
transactions,
currentHeight,
onlineHeight,
}

return (
<NetworkContext.Provider value={propValue || value}>
{children}
</NetworkContext.Provider>
)
}

export { NetworkContext, NetworkProvider }
7 changes: 7 additions & 0 deletions src/contexts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,18 @@ import {
TransactionProvider,
} from './TransactionProvider/TransactionProvider'

import {
NetworkContext,
NetworkProvider,
} from './NetworkProvider/NetworkProvider'

export {
AccountContext,
AccountProvider,
SettingsContext,
SettingsProvider,
TransactionContext,
TransactionProvider,
NetworkContext,
NetworkProvider,
}
85 changes: 9 additions & 76 deletions src/hooks/UseWalletInfo/useMlWalletInfo.js
Original file line number Diff line number Diff line change
@@ -1,84 +1,21 @@
import { useEffect, useState, useRef, useCallback, useContext } from 'react'
import { Mintlayer } from '@APIs'
import { Format, ML } from '@Helpers'
import { AccountContext, TransactionContext } from '@Contexts'
import { AccountContext, NetworkContext, TransactionContext } from '@Contexts'

const useMlWalletInfo = (addresses) => {
// const isWalletPage = location.pathname === '/wallet'
const { walletType, setBalanceLoading } = useContext(AccountContext)
const { setTransactionsLoading, setDelegationsLoading } =
useContext(TransactionContext)
const { walletType } = useContext(AccountContext)
const { setDelegationsLoading } = useContext(TransactionContext)
const {
balance: mlBalance,
lockedBalance: mlBalanceLocked,
transactions: mlTransactionsList,
} = useContext(NetworkContext)
const effectCalled = useRef(false)
const [mlTransactionsList, setMlTransactionsList] = useState([])
const [mlDelegationList, setMlDelegationList] = useState([])
const [mlDelegationsBalance, setMlDelegationsBalance] = useState(0)
const [mlBalance, setMlBalance] = useState(0)
const [mlBalanceLocked, setMlBalanceLocked] = useState(0)
const [mlUnformattedBalance, setMlUnformattedBalance] = useState(0)
const [mlUnformattedBalanceLocked, setMlUnformattedBalanceLocked] =
useState(0)
const isMintlayer = walletType.name === 'Mintlayer'

const getTransactions = useCallback(async () => {
try {
if (!addresses || !isMintlayer) return
setTransactionsLoading(true)
const addressList = [
...addresses.mlReceivingAddresses,
...addresses.mlChangeAddresses,
]
const transactions = await Mintlayer.getWalletTransactions(addressList)

const parsedTransactions = ML.getParsedTransactions(
transactions,
addressList,
)
setMlTransactionsList(parsedTransactions)
setTransactionsLoading(false)
} catch (error) {
console.error(error)
setTransactionsLoading(false)
}
}, [addresses, setTransactionsLoading, isMintlayer])

const getBalance = useCallback(async () => {
try {
if (!addresses) return
setBalanceLoading(true)
const addressList = [
...addresses.mlReceivingAddresses,
...addresses.mlChangeAddresses,
]

const balanceResult = await Mintlayer.getWalletBalance(addressList)

const balance = balanceResult.totalBalance
const balanceLocked = balanceResult.lockedBalance
const balanceInCoins = ML.getAmountInCoins(balance.balanceInAtoms)
const balanceLockedInCoins = ML.getAmountInCoins(
balanceLocked.balanceInAtoms,
)
const formattedBalance = Format.BTCValue(balanceInCoins)
const formattedBalanceLocked = Format.BTCValue(balanceLockedInCoins)

if (balance) {
setMlBalance(formattedBalance)
setMlUnformattedBalance(balance)
} else setMlBalance(0)

if (balanceLocked) {
setMlBalanceLocked(formattedBalanceLocked)
setMlUnformattedBalanceLocked(formattedBalanceLocked)
} else setMlBalanceLocked(0)
setBalanceLoading(false)
} catch (error) {
console.error(error)
setMlBalance(0)
setBalanceLoading(false)
return
}
}, [addresses, setBalanceLoading])

const getDelegations = useCallback(async () => {
try {
if (!addresses || !isMintlayer) return
Expand Down Expand Up @@ -133,19 +70,15 @@ const useMlWalletInfo = (addresses) => {
// getTransactions()
// getDelegations()
// getBalance()
}, [getBalance, getTransactions, getDelegations])
}, [getDelegations])

return {
mlTransactionsList,
mlDelegationList,
mlBalance,
mlBalanceLocked,
mlUnformattedBalance,
mlUnformattedBalanceLocked,
mlDelegationsBalance,
getDelegations,
getTransactions,
getBalance,
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
AccountProvider,
SettingsProvider,
TransactionProvider,
NetworkProvider,
} from '@Contexts'
import { ML } from '@Cryptos'
import { LocalStorageService } from '@Storage'
Expand Down Expand Up @@ -208,11 +209,13 @@ root.render(
<React.StrictMode>
<AccountProvider>
<SettingsProvider>
<TransactionProvider>
<MemoryRouter>
<App />
</MemoryRouter>
</TransactionProvider>
<NetworkProvider>
<TransactionProvider>
<MemoryRouter>
<App />
</MemoryRouter>
</TransactionProvider>
</NetworkProvider>
</SettingsProvider>
</AccountProvider>
</React.StrictMode>,
Expand Down
12 changes: 2 additions & 10 deletions src/pages/Dashboard/Dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import useOneDayAgoHist from 'src/hooks/UseOneDayAgoHist/useOneDayAgoHist'
import { useNavigate } from 'react-router-dom'
import { BTC } from '@Helpers'
import { AppInfo } from '@Constants'
import { useEffectOnce } from 'src/hooks/etc/useEffectOnce'

const DashboardPage = () => {
const { addresses, accountName, setWalletType, accountID } =
Expand All @@ -28,17 +27,14 @@ const DashboardPage = () => {
networkType === AppInfo.NETWORK_TYPES.MAINNET
? addresses.btcMainnetAddress
: addresses.btcTestnetAddress
const currentMlAddresses =
networkType === AppInfo.NETWORK_TYPES.MAINNET
? addresses.mlMainnetAddress
: addresses.mlTestnetAddresses

const [openConnectConfirmation, setOpenConnectConfirmation] = useState(false)
const [allowClosing, setAllowClosing] = useState(true)
const [account, setAccount] = useState(null)

const [connectedWalletType, setConnectedWalletType] = useState('')
const { btcBalance } = useBtcWalletInfo(currentBtcAddress)
const { mlBalance, getBalance } = useMlWalletInfo(currentMlAddresses)
const { mlBalance } = useMlWalletInfo()
const { exchangeRate: btcExchangeRate } = useExchangeRates('btc', 'usd')
const { exchangeRate: mlExchangeRate } = useExchangeRates('ml', 'usd')
const { yesterdayExchangeRate: btcYesterdayExchangeRate } =
Expand Down Expand Up @@ -173,10 +169,6 @@ const DashboardPage = () => {
getCurrentAccount(accountID).then((account) => setAccount(account))
}, [accountID])

useEffectOnce(() => {
getBalance()
}, [])

return (
<>
<Header noBackButton />
Expand Down
7 changes: 1 addition & 6 deletions src/pages/SendTransaction/SendTransaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import { ML } from '@Cryptos'
import { Mintlayer } from '@APIs'

import './SendTransaction.css'
import { useEffectOnce } from '../../hooks/etc/useEffectOnce'

const SendTransactionPage = () => {
const { addresses, accountID, walletType } = useContext(AccountContext)
Expand Down Expand Up @@ -50,11 +49,7 @@ const SendTransactionPage = () => {

const { exchangeRate } = useExchangeRates(tokenName, fiatName)
const { btcBalance } = useBtcWalletInfo(currentBtcAddress)
const { mlBalance, getBalance } = useMlWalletInfo(currentMlAddresses)

useEffectOnce(() => {
getBalance()
})
const { mlBalance } = useMlWalletInfo(currentMlAddresses)

const maxValueToken = walletType.name === 'Mintlayer' ? mlBalance : btcBalance

Expand Down
Loading

0 comments on commit 44bfd68

Please sign in to comment.