Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hub): update loading times of tokens for swaps and pools #266

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
16 changes: 16 additions & 0 deletions .scripts/set-local-install.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { execSync } = require("child_process");
const path = require("path");

try {
const scriptPath = path.resolve(__dirname, "vercel-local-install.sh");
console.log("Running local installation script...");

execSync(`bash ${scriptPath}`, {
stdio: "inherit",
});

console.log("Local installation completed successfully");
} catch (error) {
console.error("Error during local installation:", error.message);
process.exit(1);
}
BrownBrownBear marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 5 additions & 0 deletions .scripts/vercel-local-install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# if secrets folder exists, copy the static folder to the apps
if [ -d "secrets/static" ]; then
mkdir -p apps/hub/public/internal-env
cp -r secrets/static/* apps/hub/public/internal-env
fi
BrownBrownBear marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 3 additions & 0 deletions apps/hub/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ const config = {
"res.cloudinary.com",
"raw.githubusercontent.com",
"s3.amazonaws.com",
"assets.coingecko.com",
"artio-static-asset-public.s3.ap-southeast-1.amazonaws.com", // clean this up with new links
// Add google cdn here as well
],
},
};
Expand Down
35 changes: 26 additions & 9 deletions apps/hub/src/app/Providers.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
"use client";

import React, { useEffect, type PropsWithChildren } from "react";
import { BeraJsProvider, BlockTimeProvider } from "@bera/berajs";
import {
BeraJsProvider,
BlockTimeProvider,
SWRFallback,
formatTokenList,
} from "@bera/berajs";
import { chainId, tokenListUrl } from "@bera/config";
import { BeraWagmi } from "@bera/wagmi";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { unstable_serialize } from "swr";

import { ThemeProvider } from "~/components/theme-provider";

export default function Providers({ children }: PropsWithChildren<any>) {
export default function Providers({
children,
content,
}: PropsWithChildren<any>) {
useEffect(() => {
if (!process.env.NEXT_PUBLIC_POSTHOG_KEY) {
return;
Expand All @@ -24,14 +34,21 @@ export default function Providers({ children }: PropsWithChildren<any>) {
<BeraWagmi>
<BeraJsProvider configOverride={undefined}>
<BlockTimeProvider>
<ThemeProvider
attribute="class"
defaultTheme="dark"
forcedTheme="dark"
themes={["dark"]}
<SWRFallback
fallback={{
[unstable_serialize(["useTokens", tokenListUrl])]:
formatTokenList(content?.tokens ?? [], [], chainId),
}}
>
{children}
</ThemeProvider>
<ThemeProvider
attribute="class"
defaultTheme="dark"
forcedTheme="dark"
themes={["dark"]}
>
{children}
</ThemeProvider>
</SWRFallback>
</BlockTimeProvider>
</BeraJsProvider>
</BeraWagmi>
Expand Down
13 changes: 10 additions & 3 deletions apps/hub/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import "../styles/globals.css";
import { readFileSync } from "fs";
import path from "path";
import { Metadata } from "next";
import dynamic from "next/dynamic";
import { IBM_Plex_Sans } from "next/font/google";
import Script from "next/script";
import { hubName, hubUrl } from "@bera/config";
import { chainId, hubName, hubUrl, tokenListUrl } from "@bera/config";
import {
Footer,
Header,
Expand Down Expand Up @@ -35,7 +37,12 @@ const PostHogPageView = dynamic(() => import("./PostHogPageView"), {
ssr: false,
});

export default function RootLayout(props: { children: React.ReactNode }) {
export default async function RootLayout(props: { children: React.ReactNode }) {
const fileContent = readFileSync(
path.join(process.cwd(), `public/${tokenListUrl}`),
"utf8",
);
const fetchedTokenList = JSON.parse(fileContent);
BrownBrownBear marked this conversation as resolved.
Show resolved Hide resolved
return (
<html lang="en" className="bg-background">
<Script
Expand All @@ -52,7 +59,7 @@ export default function RootLayout(props: { children: React.ReactNode }) {
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');`,
}}
/>
<Providers>
<Providers content={fetchedTokenList}>
<body
className={cn(
"min-h-screen font-sans antialiased",
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
"check": "biome check .",
"prepare": "husky install",
"upsertenv": "node ./scripts/upsertVercelEnv.js",
"knip": "knip --exclude binaries"
"knip": "knip --exclude binaries",
"local-install": "node ./.scripts/set-local-install.js"
},
"dependencies": {
"@ianvs/prettier-plugin-sort-imports": "^3.7.2",
Expand Down
64 changes: 6 additions & 58 deletions packages/berajs/src/actions/dex/getTokens.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { chainId } from "@bera/config";
import { chainId, tokenListUrl } from "@bera/config";

import { BeraConfig } from "../../types";
import { Token } from "../../types/dex";
import { formatTokenList, tokenListToDict } from "../../utils/formatTokenList";

export interface GetTokensRequest {
externalList?: Token[];
config: BeraConfig;
}

export interface GetTokens {
Expand All @@ -15,22 +14,11 @@ export interface GetTokens {
featuredTokenList?: Token[] | undefined;
}

/**
* fetch and format the token list
*/
function tokenListToDict(list: Token[]): { [key: string]: Token } {
return list.reduce((acc, item) => {
// @ts-ignore
acc[item.address] = item;
return acc;
}, {});
}

export const getTokens = async ({
externalList,
config,
}: GetTokensRequest): Promise<GetTokens> => {
if (!config.endpoints?.tokenList) {
console.log("getting tokens", externalList);
if (!tokenListUrl) {
return {
tokenList: [],
customTokenList: [...(externalList ?? [])],
Expand All @@ -39,49 +27,9 @@ export const getTokens = async ({
};
}
try {
const tokenList = await fetch(config.endpoints?.tokenList);
const tokenList = await fetch(tokenListUrl);
const temp = await tokenList.json();
if (!temp.tokens)
return {
tokenList: externalList ?? [],
customTokenList: externalList ?? [],
featuredTokenList: [],
tokenDictionary: {},
};
const defaultList = temp.tokens
.filter(
(token: any) =>
!token.chainId || Number(token.chainId) === Number(chainId),
)
.map((token: any) => {
return { ...token, default: true };
});

const isFeatured = (tag: string) => tag === "featured";

const defaultFeaturedList = defaultList
.filter((token: any) => {
return token.tags.some(isFeatured);
})
.map((token: any) => {
return { ...token, default: true };
});

const list = [...defaultList, ...(externalList ?? [])];

const uniqueList = list.filter(
(item, index) =>
list.findIndex((i) => i.address === item.address) === index,
);

console.log({ uniqueList, temp, defaultList, defaultFeaturedList });

return {
tokenList: uniqueList,
customTokenList: [...(externalList ?? [])],
tokenDictionary: tokenListToDict(list),
featuredTokenList: defaultFeaturedList ?? [],
};
return formatTokenList(temp.tokens, externalList ?? [], chainId);
} catch (error) {
console.error("Error fetching token list", error);
return {
Expand Down
8 changes: 6 additions & 2 deletions packages/berajs/src/hooks/useTokens.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import useSWRImmutable from "swr/immutable";
import { useLocalStorage } from "usehooks-ts";
import { tokenListUrl } from "@bera/config";

import {
DefaultHookOptions,
Expand All @@ -24,12 +25,13 @@ export const useTokens = (options?: DefaultHookOptions): IUseTokens => {
Token[]
>(TOKEN_KEY, []);
const swrResponse = useSWRImmutable<GetTokens>(
["defaultTokenList", localStorageTokenList, config],
["useTokens", tokenListUrl],
async () => {
return getTokens({ externalList: localStorageTokenList, config });
return getTokens({ externalList: localStorageTokenList });
},
{
...options?.opts,
revalidateOnMount: true,
BrownBrownBear marked this conversation as resolved.
Show resolved Hide resolved
},
);

Expand All @@ -54,6 +56,7 @@ export const useTokens = (options?: DefaultHookOptions): IUseTokens => {
? [...localStorageTokenList]
: [...localStorageTokenList, acceptedToken as Token];
setLocalStorageTokenList(updatedData);
swrResponse?.mutate();
// Update config data and store it in localStorage
};

Expand All @@ -64,6 +67,7 @@ export const useTokens = (options?: DefaultHookOptions): IUseTokens => {

const updatedData = [...filteredList];
setLocalStorageTokenList(updatedData);
swrResponse?.mutate();
};

return {
Expand Down
1 change: 1 addition & 0 deletions packages/berajs/src/types/dex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type Token = {
usdValue?: string;
beraValue?: string;
weight?: number;
base64?: string;
};

export interface TokenWithAmount extends Token {
Expand Down
60 changes: 60 additions & 0 deletions packages/berajs/src/utils/formatTokenList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Token } from "../types";

/**
* fetch and format the token list
*/
function tokenListToDict(list: Token[]): { [key: string]: Token } {
return list.reduce((acc, item) => {
// @ts-ignore
acc[item.address] = item;
return acc;
}, {});
}

const formatTokenList = (
tokenList: Token[],
externalList: Token[],
chainId: number,
) => {
if (!tokenList)
return {
tokenList: externalList ?? [],
customTokenList: externalList ?? [],
featuredTokenList: [],
tokenDictionary: {},
};
const defaultList = tokenList
.filter(
(token: any) =>
!token.chainId || Number(token.chainId) === Number(chainId),
)
.map((token: any) => {
return { ...token, default: true };
});

const isFeatured = (tag: string) => tag === "featured";

const defaultFeaturedList = defaultList
.filter((token: any) => {
return token.tags.some(isFeatured);
})
.map((token: any) => {
return { ...token, default: true };
});

const list = [...defaultList, ...(externalList ?? [])];

const uniqueList = list.filter(
(item, index) =>
list.findIndex((i) => i.address === item.address) === index,
);

return {
tokenList: uniqueList,
customTokenList: [...(externalList ?? [])],
tokenDictionary: tokenListToDict(list),
featuredTokenList: defaultFeaturedList ?? [],
};
};

export { formatTokenList, tokenListToDict };
1 change: 1 addition & 0 deletions packages/berajs/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from "./formatNumber";
export * from "./formatTimestamps";
export * from "./tokenWrapping";
export * from "./errorMessages";
export * from "./formatTokenList";
Loading
Loading