Skip to content

Commit

Permalink
feat: remove old code, new way of fetching shared config, updates on …
Browse files Browse the repository at this point in the history
…renders
  • Loading branch information
wainola committed Feb 26, 2024
1 parent 5c5f238 commit af237f1
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 84 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"date-fns": "^2.30.0",
"dayjs": "^1.11.7",
"ethers": "^6.3.0",
"history": "^5.3.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-router-dom": "^6.14.2",
Expand Down Expand Up @@ -83,5 +84,6 @@
"last 1 firefox version",
"last 1 safari version"
]
}
},
"packageManager": "[email protected]"
}
20 changes: 5 additions & 15 deletions src/context/ExplorerContext.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React, { useEffect } from "react"

import type { ExplorerContextState, ExplorerContext as ExplorerContextType, ExplorerState, SharedConfig, SharedConfigDomain } from "../types"
import type { ExplorerContextState, ExplorerContext as ExplorerContextType, ExplorerState } from "../types"

import { getAccount, getChainId } from "./connection"
import { routes } from "./data"
import { reducer } from "./reducer"
import { useGetTransferData } from "./useGetTransferData"
import { useGetSharedConfig } from "./useGetSharedConfig"

const ExplorerCtx = React.createContext<ExplorerContextType | undefined>(undefined)

Expand All @@ -22,6 +23,7 @@ const ExplorerProvider = ({ children }: { children: React.ReactNode | React.Reac
transferDetails: undefined,
pillColorStatus: undefined,
account: undefined,
sharedConfig: [],
}

const [explorerContextState, explorerContextDispatcher] = React.useReducer(reducer, explorerPageContextState)
Expand All @@ -30,20 +32,12 @@ const ExplorerProvider = ({ children }: { children: React.ReactNode | React.Reac
const [account, setAccount] = React.useState<string | undefined>(undefined)
const [explorerUrls, setExplorerUrls] = React.useState<[] | ExplorerState["explorerUrls"]>([])

const [sharedConfig, setSharedConfig] = React.useState<SharedConfigDomain[] | []>([])

const getSharedConfig = async (): Promise<void> => {
const reponse = await fetch(import.meta.env.VITE_SHARED_CONFIG_URL as string)
const domainsData = (await reponse.json()) as SharedConfig

setSharedConfig(domainsData.domains)
localStorage.setItem("sharedConfig", JSON.stringify(domainsData))
}

const { search } = window.location
const urlParams = new URLSearchParams(search)
const page = urlParams.get("page")

useGetSharedConfig(explorerContextDispatcher)

useGetTransferData(routes(), explorerContextDispatcher, explorerContextState, Number(page))

useEffect(() => {
Expand All @@ -57,8 +51,6 @@ const ExplorerProvider = ({ children }: { children: React.ReactNode | React.Reac
})
}

void getSharedConfig()

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
setExplorerUrls(JSON.parse(import.meta.env.VITE_EXPLORER_URLS))

Expand All @@ -80,8 +72,6 @@ const ExplorerProvider = ({ children }: { children: React.ReactNode | React.Reac
chainId,
account,
routes: routes(),
sharedConfig,
setSharedConfig,
explorerUrls,
}}
>
Expand Down
5 changes: 5 additions & 0 deletions src/context/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export function reducer(state: ExplorerContextState, action: Actions): ExplorerC
...state,
error: action.payload,
}
case "fetch_shared_config":
return {
...state,
sharedConfig: action.payload,
}
default:
return state
}
Expand Down
18 changes: 18 additions & 0 deletions src/context/useGetSharedConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from "react"
import { Actions, SharedConfig } from "../types"

export function useGetSharedConfig(explorerContextDispatcher: React.Dispatch<Actions>): void {
const getSharedConfig = async (): Promise<void> => {
const reponse = await fetch(import.meta.env.VITE_SHARED_CONFIG_URL as string)
const domainsData = (await reponse.json()) as SharedConfig

explorerContextDispatcher({
type: "fetch_shared_config",
payload: domainsData.domains,
})
}

useEffect(() => {
void getSharedConfig()
}, [])
}
19 changes: 10 additions & 9 deletions src/pages/DetailView/DetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@ import useUpdateInterval from "./hooks/useUpdateInterval"

dayjs.extend(localizedFormat)

type Location = {
export type LocationT = {
state: { id: string; page: number; txHash: string }
}

export default function DetailView() {
const explorerContext = useExplorer()

const { sharedConfig, setSharedConfig, explorerUrls, routes } = explorerContext
const { explorerUrls, routes, explorerContextState } = explorerContext

const { classes } = useStyles()

const { state: data } = useLocation() as Location
const { state: data } = useLocation() as LocationT

const initState: DetailViewState = {
transferDetails: null,
Expand All @@ -51,20 +51,21 @@ export default function DetailView() {
delay: 5000,
fetchingStatus: "idle",
isLoading: "none",
fallbackPage: 1,
}

const [state, dispatcher] = useReducer(reducer, initState)

useClipboard(state, dispatcher)

useFetchTransfer(routes, sharedConfig, setSharedConfig, data.txHash, dispatcher)
useFetchTransfer(routes, data?.txHash, dispatcher)

useUpdateInterval(state, dispatcher, data.txHash, routes)
useUpdateInterval(state, dispatcher, data?.txHash, routes)

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const renderTransferDetails = (transfer: Transfer | null) => {
const fromDomainInfo = getDomainData(transfer?.fromDomainId!, sharedConfig)
const toDomainInfo = getDomainData(transfer?.toDomainId!, sharedConfig)
const fromDomainInfo = getDomainData(transfer?.fromDomainId!, explorerContextState.sharedConfig)
const toDomainInfo = getDomainData(transfer?.toDomainId!, explorerContextState.sharedConfig)

const { resource, usdValue } = transfer as Transfer

Expand Down Expand Up @@ -220,11 +221,11 @@ export default function DetailView() {
return (
<Container>
<Box className={classes.boxContainer}>
{state.isLoading === "done" && (
{state.isLoading === "done" && explorerContextState.sharedConfig.length && (
<section className={classes.sectionContainer}>
<span className={classes.backIcon}>
<Link
to={`/?page=${data.page}`}
to={`/?page=${data?.page || state.fallbackPage}`}
style={{
color: "black",
textDecoration: "none",
Expand Down
70 changes: 17 additions & 53 deletions src/pages/DetailView/hooks/useFetchTransfer.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { useEffect } from "react"
import { useParams } from "react-router-dom"
import history from "history/browser"
import { sanitizeTransferData } from "../../../utils/Helpers"
import { Routes, SharedConfig, SharedConfigDomain, Transfer } from "../../../types"
import { Routes, Transfer } from "../../../types"
import { DetailViewActions } from "../reducer"

export default function useFetchTransfer(
routes: Routes,
sharedConfig: SharedConfigDomain[] | [],
setSharedConfig: React.Dispatch<React.SetStateAction<SharedConfigDomain[] | []>>,
txHash: string,
dispatcher: React.Dispatch<DetailViewActions>,
): void {
const fetchTransfer = async (): Promise<void> => {
export default function useFetchTransfer(routes: Routes, txHash: string, dispatcher: React.Dispatch<DetailViewActions>): void {
const fetchTransfer = async (txHashFallback?: string): Promise<void> => {
dispatcher({
type: "fetch_transfer",
})

const transfer = await routes.transferByTransactionHash(txHash)
let transfer: Transfer | Transfer[]

if (txHashFallback) {
transfer = await routes.transferByTransactionHash(txHashFallback)
} else {
transfer = await routes.transferByTransactionHash(txHash)
}

const sanitizedTransfer = Array.isArray(transfer) ? sanitizeTransferData([...transfer]) : sanitizeTransferData([transfer])

Expand All @@ -36,50 +36,14 @@ export default function useFetchTransfer(
})
}

// fallback when you are opening the detail view on new tab
const params = useParams()

const getTransfersFromLocalStorage = (): void => {
const transfers = localStorage.getItem("transfers")
const { txHash } = params
const parsedTransfers = JSON.parse(transfers!) as Transfer[]
const transfer = parsedTransfers.find(transfer => transfer.deposit?.txHash === txHash)

if (transfer) {
dispatcher({
type: "set_transfer_details",
payload: transfer,
})

dispatcher({
type: "set_transfer_status",
payload: "completed",
})

dispatcher({
type: "update_fetching_status",
payload: "fetching",
})
}
}

const getSharedConfigFromLocalStorage = (): void => {
const sharedConfig = localStorage.getItem("sharedConfig")
const parsedSharedConfig = JSON.parse(sharedConfig!) as SharedConfig

setSharedConfig(parsedSharedConfig.domains)
}

useEffect(() => {
if (txHash !== null) {
if (txHash !== undefined) {
void fetchTransfer()
} else {
getTransfersFromLocalStorage()
}

// fallback because ExplorerState is new coming to a new tab
if (sharedConfig.length === 0) {
getSharedConfigFromLocalStorage()
const { pathname } = history.location
const txHashFallback = pathname.split("/").filter(Boolean)[1]
history.replace(history.location.pathname, { txHash, page: 1, id: "" })
void fetchTransfer(txHashFallback)
}
}, [])
}, [txHash])
}
1 change: 1 addition & 0 deletions src/pages/DetailView/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type DetailViewState = {
delay: number
fetchingStatus: "fetching" | "idle"
isLoading: "none" | "loading" | "done"
fallbackPage: number
}

export type DetailViewActions =
Expand Down
12 changes: 9 additions & 3 deletions src/pages/ExplorerPage/ExplorerPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useStyles } from "./styles"

const ExplorerPage = (): JSX.Element => {
const explorerContext = useExplorer()
const { explorerContextDispatcher, explorerContextState, sharedConfig } = explorerContext
const { explorerContextDispatcher, explorerContextState } = explorerContext

const { transfers } = explorerContextState

Expand Down Expand Up @@ -54,8 +54,14 @@ const ExplorerPage = (): JSX.Element => {
}}
>
<div className={transfers.length !== 0 ? classes.explorerTable : classes.errorMessage}>
{transfers.length !== 0 && sharedConfig.length !== 0 ? (
<ExplorerTable active={active} setActive={setActive} chains={chains} state={explorerContextState} sharedConfig={sharedConfig} />
{transfers.length !== 0 && explorerContextState.sharedConfig.length !== 0 ? (
<ExplorerTable
active={active}
setActive={setActive}
chains={chains}
state={explorerContextState}
sharedConfig={explorerContextState.sharedConfig}
/>
) : explorerContextState.account !== undefined ? (
<Alert severity="error">No transactions for the selected account!</Alert>
) : (
Expand Down
4 changes: 2 additions & 2 deletions src/types/explorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ export type ExplorerContextState = {
background: string
}
account: string | undefined
sharedConfig: SharedConfigDomain[] | []
}

export type Actions =
Expand All @@ -164,6 +165,7 @@ export type Actions =
| { type: "loading_done" }
| { type: "loading_transfers" }
| { type: "fetch_transfer_error"; payload: string }
| { type: "fetch_shared_config"; payload: SharedConfigDomain[] }

export type Routes = {
transfers: (page: string, limit: string, status?: string) => Promise<Transfer[]>
Expand All @@ -180,8 +182,6 @@ export type ExplorerContext = {
chainId: number | undefined
account: string | undefined
routes: Routes
sharedConfig: SharedConfigDomain[] | []
setSharedConfig: React.Dispatch<React.SetStateAction<SharedConfigDomain[] | []>>
explorerUrls: [] | ExplorerState["explorerUrls"]
}

Expand Down
9 changes: 8 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@
core-js-pure "^3.30.2"
regenerator-runtime "^0.14.0"

"@babel/runtime@^7.10.2", "@babel/runtime@^7.12.1", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.18.3", "@babel/runtime@^7.21.0", "@babel/runtime@^7.23.1", "@babel/runtime@^7.23.9", "@babel/runtime@^7.3.1", "@babel/runtime@^7.4.4", "@babel/runtime@^7.5.5", "@babel/runtime@^7.8.3", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2":
"@babel/runtime@^7.10.2", "@babel/runtime@^7.12.1", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.18.3", "@babel/runtime@^7.21.0", "@babel/runtime@^7.23.1", "@babel/runtime@^7.23.9", "@babel/runtime@^7.3.1", "@babel/runtime@^7.4.4", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.3", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2":
version "7.23.9"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.23.9.tgz#47791a15e4603bb5f905bc0753801cf21d6345f7"
integrity sha512-0CX6F+BI2s9dkUqr08KFrAIZgNFj75rdBU/DjCyYLIaV/quFjkk6T+EJ2LkZHyZTbEV4L5p97mNkUsHl2wLFAw==
Expand Down Expand Up @@ -3927,6 +3927,13 @@ hasown@^2.0.0, hasown@^2.0.1:
dependencies:
function-bind "^1.1.2"

history@^5.3.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b"
integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==
dependencies:
"@babel/runtime" "^7.7.6"

hmac-drbg@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1"
Expand Down

0 comments on commit af237f1

Please sign in to comment.