Skip to content

Commit

Permalink
v7.1.2 (#272)
Browse files Browse the repository at this point in the history
* fix: receive page bug on desktop (#264)

* Feat/loading optimizations (#267)

* Fix network validation requests

* Add page loader during validation

---------

Co-authored-by: Alessandro Candeago <[email protected]>

* hard coded stakes alliance tokens to 100 dollars (#269)

---------

Co-authored-by: Alessandro Candeago <[email protected]>
Co-authored-by: Joshua Brigati <[email protected]>
  • Loading branch information
3 people authored Feb 13, 2023
1 parent c4ff877 commit b4306a1
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 129 deletions.
49 changes: 20 additions & 29 deletions src/app/InitChains.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,31 @@ import axios from "axios"
import { ASSETS, STATION_ASSETS } from "config/constants"
import { WhitelistProvider, WhitelistData } from "data/queries/chains"
import { PropsWithChildren, useEffect, useState } from "react"
import NetworkLoading from "./NetworkLoading"

const InitChains = ({ children }: PropsWithChildren<{}>) => {
const [data, setData] = useState<WhitelistData>()
useEffect(() => {
;(async () => {
const [whitelist, ibcDenoms, legacyWhitelist] = await Promise.all([
(async () => {
const { data } = await axios.get("/coins.json", {
baseURL: STATION_ASSETS,
})
return data
})(),
(async () => {
const { data } = await axios.get("/ibc_denoms.json", {
baseURL: STATION_ASSETS,
})
return data
})(),
(async () => {
const { data } = await axios.get("/station/coins.json", {
baseURL: ASSETS,
})
return data
})(),
])
const [whitelist, setWhitelist] = useState<WhitelistData["whitelist"]>()
const [ibcDenoms, setIbcDenoms] = useState<WhitelistData["ibcDenoms"]>()
const [legacyWhitelist, setLegacyWhitelist] =
useState<WhitelistData["legacyWhitelist"]>()

setData({ whitelist, ibcDenoms, legacyWhitelist })
})()
useEffect(() => {
axios
.get("/coins.json", { baseURL: STATION_ASSETS })
.then(({ data }) => setWhitelist(data))
axios
.get("/ibc_denoms.json", { baseURL: STATION_ASSETS })
.then(({ data }) => setIbcDenoms(data))
axios
.get("/station/coins.json", { baseURL: ASSETS })
.then(({ data }) => setLegacyWhitelist(data))
}, [])

if (!data) return <NetworkLoading />

return <WhitelistProvider value={data}>{children}</WhitelistProvider>
if (!(whitelist && ibcDenoms && legacyWhitelist)) return null
return (
<WhitelistProvider value={{ whitelist, ibcDenoms, legacyWhitelist }}>
{children}
</WhitelistProvider>
)
}

export default InitChains
113 changes: 42 additions & 71 deletions src/app/InitNetworks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { PropsWithChildren, useEffect, useState } from "react"
import axios from "axios"
import { STATION_ASSETS } from "config/constants"
import createContext from "utils/createContext"
import NetworkLoading from "./NetworkLoading"
import { randomAddress } from "utils/bech32"
import { useCustomLCDs } from "utils/localStorage"
import { useValidNetworks } from "data/queries/tendermint"
import { WithFetching } from "components/feedback"
import { combineState } from "data/query"

type TokenFilter = <T>(network: Record<string, T>) => Record<string, T>

Expand All @@ -16,7 +17,6 @@ export const [useNetworks, NetworksProvider] = createContext<{

const InitNetworks = ({ children }: PropsWithChildren<{}>) => {
const [networks, setNetworks] = useState<InterchainNetworks>()
const [enabledNetworks, setEnabledNetworks] = useState<string[]>([])
const { customLCDs } = useCustomLCDs()

useEffect(() => {
Expand All @@ -27,88 +27,59 @@ const InitNetworks = ({ children }: PropsWithChildren<{}>) => {
baseURL: STATION_ASSETS,
}
)

setNetworks(chains)
}

fetchChains()
}, [])

useEffect(() => {
const testChains = async () => {
if (!networks) return
const testBase = {
const testBase = networks
? Object.values({
...networks.mainnet,
...networks.testnet,
...networks.classic,
//...networks.localterra,
}

const stored = localStorage.getItem("enabledNetworks")
const cached = stored && JSON.parse(stored)

if (cached && cached.time > Date.now() - 10 * 60 * 1000) {
setEnabledNetworks(cached.networks)
return
}

const result = await Promise.all(
Object.values(testBase).map(async (network) => {
if (network.prefix === "terra") return network.chainID
try {
const { data } = await axios.get(
`/cosmos/bank/v1beta1/balances/${randomAddress(network.prefix)}`,
{
baseURL: customLCDs[network.chainID] || network.lcd,
timeout: 3_000,
}
)
return Array.isArray(data.balances) && network.chainID
} catch (e) {
console.error(e)
return null
}
})
)
}).map((chain) => {
const lcd = customLCDs[chain.chainID] ?? chain.lcd
return { ...chain, lcd }
})
: []

localStorage.setItem(
"enabledNetworks",
JSON.stringify({
time: Date.now(),
networks: result.filter((r) => typeof r === "string") as string[],
})
)
setEnabledNetworks(
result.filter((r) => typeof r === "string") as string[]
)
}
const validationResult = useValidNetworks(testBase)

testChains()
}, [networks]) // eslint-disable-line
const validNetworks = validationResult.reduce(
(acc, { data }) => (data ? [...acc, data] : acc),
[] as string[]
)
const validationState = combineState(...validationResult)

if (!networks || !enabledNetworks.length) return <NetworkLoading />
if (!networks) return null

return (
<NetworksProvider
value={{
networks,
filterEnabledNetworks: (networks) =>
Object.fromEntries(
Object.entries(networks).filter(
([chainID]) =>
chainID === "localterra" || enabledNetworks.includes(chainID)
)
),
filterDisabledNetworks: (networks) =>
Object.fromEntries(
Object.entries(networks).filter(
([chainID]) => !enabledNetworks.includes(chainID)
)
),
}}
>
{children}
</NetworksProvider>
<WithFetching {...validationState} height={2}>
{(progress) => (
<NetworksProvider
value={{
networks,
filterEnabledNetworks: (networks) =>
Object.fromEntries(
Object.entries(networks).filter(
([chainID]) =>
chainID === "localterra" || validNetworks.includes(chainID)
)
),
filterDisabledNetworks: (networks) =>
Object.fromEntries(
Object.entries(networks).filter(
([chainID]) => !validNetworks.includes(chainID)
)
),
}}
>
{progress}
{children}
</NetworksProvider>
)}
</WithFetching>
)
}

Expand Down
25 changes: 25 additions & 0 deletions src/app/InitQueryClient.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useNetworkName } from "data/wallet"
import { PropsWithChildren, useMemo } from "react"
import { QueryClient, QueryClientProvider } from "react-query"

const InitQueryClient = ({ children }: PropsWithChildren<{}>) => {
const queryClient = useQueryClient()
const networkName = useNetworkName()

return (
<QueryClientProvider client={queryClient} key={networkName}>
{children}
</QueryClientProvider>
)
}

const useQueryClient = () => {
const name = useNetworkName()

return useMemo(() => {
if (!name) throw new Error()
return new QueryClient()
}, [name])
}

export default InitQueryClient
19 changes: 3 additions & 16 deletions src/app/InitWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { PropsWithChildren, useEffect, useMemo } from "react"
import { QueryClient, QueryClientProvider } from "react-query"
import { PropsWithChildren, useEffect } from "react"
import { WalletStatus } from "@terra-money/wallet-types"
import { useWallet } from "@terra-money/use-wallet"
import { useNetworkName } from "data/wallet"
import { isWallet, useAuth } from "auth"
import Online from "./containers/Online"
import NetworkLoading from "./NetworkLoading"
Expand All @@ -11,8 +9,6 @@ import { sandbox } from "auth/scripts/env"
const InitWallet = ({ children }: PropsWithChildren<{}>) => {
useOnNetworkChange()
const { status } = useWallet()
const queryClient = useQueryClient()
const networkName = useNetworkName()

return status === WalletStatus.INITIALIZING && !sandbox ? (
<NetworkLoading
Expand All @@ -25,10 +21,10 @@ const InitWallet = ({ children }: PropsWithChildren<{}>) => {
}}
/>
) : (
<QueryClientProvider client={queryClient} key={networkName}>
<>
{children}
<Online />
</QueryClientProvider>
</>
)
}

Expand All @@ -44,12 +40,3 @@ const useOnNetworkChange = () => {
if (shouldDisconnect) disconnect()
}, [disconnect, shouldDisconnect])
}

const useQueryClient = () => {
const name = useNetworkName()

return useMemo(() => {
if (!name) throw new Error()
return new QueryClient()
}, [name])
}
2 changes: 1 addition & 1 deletion src/app/sections/LCDSetting.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useNetworkName, useNetworkOptions } from "data/wallet"
import { useForm } from "react-hook-form"
import { Form, FormItem, Input, Select } from "components/form"
import { Form, FormItem, Input } from "components/form"
import { useTranslation } from "react-i18next"
import { useNetworks } from "app/InitNetworks"
import ChainSelector from "components/form/ChainSelector"
Expand Down
2 changes: 2 additions & 0 deletions src/config/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,5 @@ export const TERRASWAP_COMMISSION_RATE = 0.003
export const SAMPLE_ADDRESS = "terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v"

export const CURRENCY_KEY = "e484bb7eb1a1cb1471fd5ee925e9b1bc"

export const VALIDATION_TIMEOUT = 3_000
16 changes: 16 additions & 0 deletions src/data/queries/coingecko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ const AXELAR_TOKENS: Record<string, string> = {
"ibc/CBF67A2BCF6CAE343FDF251E510C8E18C361FC02B23430C121116E0811835DEF":
"uusdt",
}
const STAKED_TOKENS: Record<string, string> = {
terra1jltsv4zjps5veugu6xc0gkurrjx33klhyxse80hy8pszzvhslx0s2n7jkk: "sORD",
terra1lertn5hx2gpw940a0sspds6kydja3c07x0mfg0xu66gvu9p4l30q7ttd2p: "sCOR",
terra15rqy5xh7sclu3yltuz8ndl8lzudcqcv3laldxxsxaph085v6mdpqdjrucv: "sATR",
terra14y9aa87v4mjvpf0vu8xm7nvldvjvk4h3wly2240u0586j4l6qm2q7ngp7t: "sHAR",
}

export const useExchangeRates = () => {
const currency = useCurrency()
Expand Down Expand Up @@ -104,6 +110,16 @@ export const useExchangeRates = () => {
}
})

// add staked tokens and set price to 100
Object.entries(STAKED_TOKENS).forEach(([key]) => {
if (!priceObject[key]) {
priceObject[key] = {
price: 100,
change: 0,
}
}
})

return priceObject
},
{ ...RefetchOptions.DEFAULT }
Expand Down
34 changes: 33 additions & 1 deletion src/data/queries/tendermint.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useQuery } from "react-query"
import { useQueries, useQuery } from "react-query"
import axios from "axios"
import { queryKey, RefetchOptions } from "../query"
import { useNetworks } from "app/InitNetworks"
import { VALIDATION_TIMEOUT } from "config/constants"
import { randomAddress } from "utils/bech32"

export const useLocalNodeInfo = (chainID: string) => {
const { networks } = useNetworks()
Expand Down Expand Up @@ -67,3 +69,33 @@ export const useValidateLCD = (
{ ...RefetchOptions.INFINITY, enabled }
)
}

interface Network {
chainID: string
prefix: string
lcd: string
}

export const useValidNetworks = (networks: Network[]) => {
return useQueries(
networks.map(({ chainID, prefix, lcd }) => {
return {
queryKey: [queryKey.tendermint.nodeInfo, lcd],
queryFn: async () => {
if (prefix === "terra") return chainID

const { data } = await axios.get(
`/cosmos/bank/v1beta1/balances/${randomAddress(prefix)}`,
{
baseURL: lcd, // TODO: pass custom lcd to the function
timeout: VALIDATION_TIMEOUT,
}
)

if (Array.isArray(data.balances)) return chainID
},
...RefetchOptions.INFINITY,
}
})
)
}
Loading

0 comments on commit b4306a1

Please sign in to comment.