Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 20 additions & 36 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { styled } from "@mui/material";
import { Box } from "@mui/system";
import { createContext, useEffect } from "react";
import { useEffect } from "react";
import { APP_GRID, ROUTES } from "consts";
import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom";
import { DeployerPage, Jetton } from "pages";
Expand All @@ -9,7 +9,6 @@ import { Footer } from "components/footer";
import { Header } from "components/header";
import { useResetJettonLogoOnPathChange } from "hooks/useJettonLogo";
import useNotification from "hooks/useNotification";
import { useNetwork } from "lib/hooks/useNetwork";

analytics.init();

Expand Down Expand Up @@ -50,11 +49,6 @@ const FlexibleBox = styled(Box)(({ theme }) => ({
},
}));

export const EnvContext = createContext({
isSandbox: false,
isTestnet: false,
});

const PageNotFound = () => {
const { showNotification } = useNotification();

Expand All @@ -80,41 +74,31 @@ const ContentWrapper = ({ children }: ContentWrapperProps) => {

const App = () => {
const location = useLocation();
const { network } = useNetwork();

useResetJettonLogoOnPathChange(location.pathname);

const isSandbox = window.location.search.includes("sandbox");
const isTestnet = network === "testnet";

return (
<AppWrapper>
<EnvContext.Provider
value={{
isSandbox: isSandbox,
isTestnet: isTestnet,
}}>
<ScreensWrapper>
<Routes>
<Route
path="*"
element={
<>
<Header />
<Navigate to={{ pathname: "/", search: location.search }} />
<PageNotFound />
</>
}
/>
<Route path="/" element={<Header />}>
<Route path="/" element={<ContentWrapper />}>
<Route path={ROUTES.deployer} element={<DeployerPage />} />
<Route path={ROUTES.jettonId} element={<Jetton />} />
</Route>
<ScreensWrapper>
<Routes>
<Route
path="*"
element={
<>
<Header />
<Navigate to={{ pathname: "/", search: location.search }} />
<PageNotFound />
</>
}
/>
<Route path="/" element={<Header />}>
<Route path="/" element={<ContentWrapper />}>
<Route path={ROUTES.deployer} element={<DeployerPage />} />
<Route path={ROUTES.jettonId} element={<Jetton />} />
</Route>
</Routes>
</ScreensWrapper>
</EnvContext.Provider>
</Route>
</Routes>
</ScreensWrapper>
<FooterBox mt={5}>
<Footer />
</FooterBox>
Expand Down
5 changes: 1 addition & 4 deletions src/components/AddressLink.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { Box, IconButton, Link, styled } from "@mui/material";
import CopyToClipboard from "react-copy-to-clipboard";
import useNotification from "hooks/useNotification";
import CopyImg from "assets/icons/copy.svg";
import { useContext } from "react";
import { EnvContext } from "App";
import { scannerUrl } from "utils";
import theme from "theme";
import { useNetwork } from "lib/hooks/useNetwork";
Expand Down Expand Up @@ -48,7 +46,6 @@ const AddressLink: React.FC<AddressLinkProps> = ({
regularAddress,
}) => {
const { showNotification } = useNotification();
const { isSandbox } = useContext(EnvContext);
const { network } = useNetwork();

const onCopy = () => {
Expand All @@ -58,7 +55,7 @@ const AddressLink: React.FC<AddressLinkProps> = ({
return (
<StyledContainer className="address-link">
<StyledLink>
<Link target="_blank" href={`${scannerUrl(network, isSandbox, regularAddress)}/${address}`}>
<Link target="_blank" href={`${scannerUrl(network, regularAddress)}/${address}`}>
{value || "-"}
</Link>
</StyledLink>
Expand Down
44 changes: 44 additions & 0 deletions src/components/PendingDeployLink.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { act, render, screen } from "@testing-library/react";
import { Address } from "ton";
import { formatAddress, Network, NETWORK_CONFIG } from "lib/network";
import { PendingDeployLink } from "./PendingDeployLink";

const address = Address.parseRaw(`0:${"ab".repeat(32)}`);
const fetchMock = jest.spyOn(global, "fetch");
afterEach(() => fetchMock.mockReset());
afterAll(() => fetchMock.mockRestore());

test.each<[Network, boolean]>([
["mainnet", false],
["testnet", false],
["testnet", true],
])(
"pending deployment uses Toncenter's format on %s (bounceable %s)",
async (network, bounceable) => {
const friendly = formatAddress(address, network, bounceable);
const response = {
ok: true,
json: async () => ({
[address.toString()]: { user_friendly: friendly },
}),
} as Response;
let resolveResponse!: (response: Response) => void;
fetchMock.mockReturnValueOnce(
new Promise<Response>((resolve) => {
resolveResponse = resolve;
}),
);
render(<PendingDeployLink address={formatAddress(address, network)} network={network} />);
expect(screen.getByRole("link", { name: "explorer" })).toHaveAttribute(
"href",
`${NETWORK_CONFIG[network].explorer}/address/${formatAddress(address, network)}`,
);
await act(async () => {
resolveResponse(response);
});
expect(screen.getByRole("link", { name: "explorer" })).toHaveAttribute(
"href",
`${NETWORK_CONFIG[network].explorer}/address/${friendly}`,
);
},
);
16 changes: 16 additions & 0 deletions src/components/PendingDeployLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Link } from "@mui/material";
import { useDisplayAddresses } from "hooks/useDisplayAddresses";
import { formatAddress, Network, NETWORK_CONFIG } from "lib/network";

export function PendingDeployLink({ address, network }: { address: string; network: Network }) {
const [displayAddress] = useDisplayAddresses([address], network);
return (
<Link
href={`${NETWORK_CONFIG[network].explorer}/address/${
displayAddress || formatAddress(address, network)
}`}
target="_blank">
explorer
</Link>
);
}
27 changes: 22 additions & 5 deletions src/components/header/headerSearchResults/HeaderSearchResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import recentSearch from "assets/icons/recent-search.svg";
import { IconButton, Typography } from "@mui/material";
import close from "assets/icons/close.svg";
import { AppButton } from "components/appButton";
import { useDisplayAddresses } from "hooks/useDisplayAddresses";
import { useNetwork } from "lib/hooks/useNetwork";
import LoadingContainer from "components/LoadingContainer";

interface HeaderSearchResultsProps {
searchResults: string[];
Expand All @@ -22,17 +25,31 @@ export const HeaderSearchResults: React.FC<HeaderSearchResultsProps> = ({
onItemDelete,
onHistoryClear,
}) => {
const { network } = useNetwork();
const displayAddresses = useDisplayAddresses(searchResults, network);
const loading = displayAddresses.length !== searchResults.length;

return (
<SearchResultsWrapper>
{searchResults.map((result) => (
<SearchResultsItem key={result} onClick={() => onItemClick(result)}>
<CenteringWrapper>
{searchResults.map((result, index) => (
<SearchResultsItem
key={result}
onClick={loading ? undefined : () => onItemClick(result)}
aria-disabled={loading}
sx={
loading ? { "&:hover": { cursor: "default", background: "transparent" } } : undefined
}>
<CenteringWrapper flex={1}>
<CenteringWrapper mr={1.5}>
<img width={18} height={18} src={recentSearch} alt="Search Icon" />
</CenteringWrapper>
<Typography>{result}</Typography>
<Typography sx={{ flex: 1 }} aria-busy={loading}>
<LoadingContainer loading={loading}>{displayAddresses[index]}</LoadingContainer>
</Typography>
</CenteringWrapper>
<IconButton onClick={(e) => onItemDelete(e, result)}>
<IconButton
sx={{ visibility: loading ? "hidden" : "visible" }}
onClick={(e) => onItemDelete(e, result)}>
<img src={close} alt="Close Icon" width={18} height={18} />
</IconButton>
</SearchResultsItem>
Expand Down
69 changes: 69 additions & 0 deletions src/hooks/useAddressHistory.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { act, renderHook } from "@testing-library/react";
import { useEffect } from "react";
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { RecoilRoot } from "recoil";
import { Address } from "ton";
import { formatAddress } from "lib/network";
import { useAddressHistory } from "./useAddressHistory";

jest.mock("hooks/useNotification", () => () => ({ showNotification: jest.fn() }));
const account = Address.parseRaw(`0:${"ab".repeat(32)}`);
const other = Address.parseRaw(`0:${"cd".repeat(32)}`);

beforeEach(() => localStorage.clear());

test("selecting the current token from raw history keeps its canonical route", () => {
const path = `/jetton/${formatAddress(account, "testnet")}?testnet=true#anchor`;
const visitedPaths: string[] = [];
const { result } = renderHook(
() => {
const history = useAddressHistory();
const location = useLocation();
useEffect(() => {
visitedPaths.push(location.pathname);
}, [location.pathname]);
return { history, location };
},
{
wrapper: ({ children }) => (
<RecoilRoot>
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/jetton/:id" element={children} />
</Routes>
</MemoryRouter>
</RecoilRoot>
),
},
);
const { pathname, search, hash } = result.current.location;
expect(result.current.history.addresses).toEqual([account.toString()]);
act(() => result.current.history.onAddressClick(account.toString()));
expect(result.current.location).toMatchObject({ pathname, search, hash });
expect(visitedPaths).toEqual([pathname]);
});

test("deduplicates accounts, separates networks and clears only the current network", () => {
const { result } = renderHook(() => ({ history: useAddressHistory(), navigate: useNavigate() }), {
wrapper: ({ children }) => (
<RecoilRoot>
<MemoryRouter>{children}</MemoryRouter>
</RecoilRoot>
),
});
act(() => result.current.history.onSubmit(formatAddress(account, "mainnet", false)));
act(() => result.current.history.onSubmit(formatAddress(account, "mainnet", true)));
expect(result.current.history.addresses).toEqual([account.toString()]);

act(() => result.current.navigate("/?testnet=true"));
expect(result.current.history.addresses).toEqual([]);
act(() => result.current.history.onSubmit(formatAddress(other, "testnet", false)));
expect(result.current.history.addresses).toEqual([other.toString()]);

act(() => result.current.history.resetAddresses());
expect(result.current.history.addresses).toEqual([]);
act(() => result.current.navigate("/"));
expect(result.current.history.addresses).toEqual([account.toString()]);
act(() => result.current.history.removeAddress(formatAddress(account, "mainnet", false)));
expect(result.current.history.addresses).toEqual([]);
});
45 changes: 32 additions & 13 deletions src/hooks/useAddressHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,53 +5,72 @@ import useNotification from "hooks/useNotification";
import { ROUTES } from "consts";
import { recoilPersist } from "recoil-persist";
import { Address } from "ton";
import { useCallback, useEffect } from "react";
import { useCallback, useEffect, useMemo } from "react";
import { useJettonAddress } from "hooks/useJettonAddress";
import { useNavigatePreserveQuery } from "lib/hooks/useNavigatePreserveQuery";
import { useNetwork } from "lib/hooks/useNetwork";
import { formatAddress } from "lib/network";
import {
ADDRESS_HISTORY_LIMIT,
AddressHistory,
normalizeAddressHistory,
} from "lib/address-history";

const { persistAtom } = recoilPersist({
key: "addressHistory",
});

const addressHistoryState = atom({
const addressHistoryState = atom<AddressHistory | string[]>({
key: "addressHistory",
default: [] as string[],
default: { mainnet: [], testnet: [] },
effects_UNSTABLE: [persistAtom],
});

export function useAddressHistory() {
const [addresses, setAddresses] = useRecoilState(addressHistoryState);
const [history, setHistory] = useRecoilState(addressHistoryState);
const { setActive, setValue, addressInput } = useAddressInput();
const navigate = useNavigatePreserveQuery();
const { showNotification } = useNotification();
const { jettonAddress } = useJettonAddress();
const { network } = useNetwork();
const addresses = useMemo(() => normalizeAddressHistory(history)[network], [history, network]);

const addAddress = useCallback(
(address: string) =>
setAddresses((prev: string[]) =>
[address, ...prev.filter((a) => a !== address)].slice(0, 20),
),
[setAddresses],
(address: string) => {
const raw = Address.parse(address).toString();
setHistory((prev) => {
const next = normalizeAddressHistory(prev);
if (next[network][0] === raw && !Array.isArray(prev)) return prev;
next[network] = [raw, ...next[network].filter((a) => a !== raw)].slice(
0,
ADDRESS_HISTORY_LIMIT,
);
return next;
});
},
[network, setHistory],
);

const resetAddresses = () => {
setAddresses([]);
setHistory((prev) => ({ ...normalizeAddressHistory(prev), [network]: [] }));
setActive(false);
};

const removeAddress = (address: string) =>
setAddresses((prev: string[]) => [...prev.filter((a) => a !== address)]);
const removeAddress = (address: string) => {
const raw = Address.parse(address).toString();
setHistory((prev) => {
const next = normalizeAddressHistory(prev);
return { ...next, [network]: next[network].filter((a) => a !== raw) };
});
};

const onAddressClick = (address: string) => {
setActive(false);
setValue("");

addAddress(address);

navigate(`${ROUTES.jetton}/${address}`);
navigate(`${ROUTES.jetton}/${formatAddress(address, network)}`);
};

const onSubmit = (address: string) => {
Expand Down
Loading
Loading