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] - sort network list based on wormholescan volume #1027

Merged
merged 2 commits into from
Aug 20, 2024
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
84 changes: 4 additions & 80 deletions apps/connect/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,91 +1,15 @@
import type { WormholeConnectConfig } from "@wormhole-foundation/wormhole-connect";
import { ComponentProps, memo, useEffect, useMemo } from "react";
import customTheme from "./theme/connect";
import NavBar from "./components/atoms/NavBar";
import NewsBar from "./components/atoms/NewsBar";
import messageConfig from "./configs/messages";
import { useQueryParams } from "./hooks/useQueryParams";
import { useFormatAssetParam } from "./hooks/useFormatAssetParam";
import WormholeConnect from "@wormhole-foundation/wormhole-connect";
import { eventHandler, type WormholeConnectEvent } from "./providers/telemetry";

import { Route, Routes } from "react-router-dom";
import PrivacyPolicy from "./components/pages/PrivacyPolicy";
import { PrivacyPolicyPath, isPreview, isProduction } from "./utils/constants";
import Banner from "./components/atoms/Banner";
import { PrivacyPolicyPath } from "./utils/constants";
import { ENV } from "@env";
import { clearUrl, pushResumeUrl } from "./navs/navs";
import { validateTransfer } from "./utils/transferVerification";
//import { validateTransferHandler } from "./providers/sanctions"; // TO DO: Use this function

const defaultConfig: WormholeConnectConfig = {
...ENV.wormholeConnectConfig,

eventHandler: (e: WormholeConnectEvent) => {
if (isPreview || isProduction) {
// Send the event to Mixpanel
eventHandler(e);
}
// Update the URL when a transfer starts with a permlink
pushResumeUrl(e);
// Clear the URL when a transfer is successful
clearUrl(e);
},
// validateTransfer
validateTransferHandler: validateTransfer,
isRouteSupportedHandler: async (td: any) => {
// Disable manual NTT for Lido wstETH
if (
td.route === "nttManual" &&
td.fromToken.tokenId !== "native" &&
(td.fromToken.tokenId.address ===
"0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0" ||
td.fromToken.tokenId.address ===
"0x26c5e01524d2E6280A48F2c50fF6De7e52E9611C")
) {
return false;
}
return true;
},
};

const Connect = memo(
({ config }: Pick<ComponentProps<typeof WormholeConnect>, "config">) => {
return (
<>
<WormholeConnect config={config} theme={customTheme} />
<Banner />
</>
);
}
);
import { Connect } from "./components/atoms/Connect";

export default function Root() {
const { txHash, sourceChain, targetChain, asset, requiredNetwork, route } =
useQueryParams();
const token = useFormatAssetParam(asset);
const config: ComponentProps<typeof WormholeConnect>["config"] = useMemo(
() => ({
...defaultConfig,
//validateTransferHandler,
searchTx: {
...(txHash && { txHash }),
...(sourceChain && { chainName: sourceChain }),
},
bridgeDefaults: {
...(sourceChain && { fromNetwork: sourceChain }),
...(targetChain && { toNetwork: targetChain }),
...(token && { token }),
...(requiredNetwork && { requiredNetwork }),
},
...(route && { routes: [route] }),
}),
[txHash, sourceChain, targetChain, token, requiredNetwork, route]
);

const messages = Object.values(messageConfig);
useEffect(() => {
localStorage.setItem("Connect Config", JSON.stringify(config, null, 2));
}, [config]);

return (
<>
Expand All @@ -102,7 +26,7 @@ export default function Root() {
</div>
<Routes>
<Route path={PrivacyPolicyPath} element={<PrivacyPolicy />} />
<Route path="*" element={<Connect config={config} />} />
<Route path="*" element={<Connect />} />
</Routes>
</>
);
Expand Down
22 changes: 22 additions & 0 deletions apps/connect/src/components/atoms/Connect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { memo, useEffect } from "react";
import WormholeConnect from "@wormhole-foundation/wormhole-connect";
import customTheme from "../../theme/connect";
import Banner from "./Banner";
import { useConnectConfig } from "../../hooks/useConnectConfig";

export const Connect = memo(() => {
const config = useConnectConfig();

useEffect(() => {
if (config) {
localStorage.setItem("Connect Config", JSON.stringify(config, null, 2));
}
}, [config]);

return (
<>
{!!config && <WormholeConnect config={config} theme={customTheme} />}
<Banner />
</>
);
});
81 changes: 81 additions & 0 deletions apps/connect/src/hooks/useConnectConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type { WormholeConnectConfig } from "@wormhole-foundation/wormhole-connect";
import { ComponentProps, useEffect, useMemo, useState } from "react";

import { useQueryParams } from "./useQueryParams";
import { useFormatAssetParam } from "./useFormatAssetParam";
import WormholeConnect from "@wormhole-foundation/wormhole-connect";
import {
eventHandler,
type WormholeConnectEvent,
} from "../providers/telemetry";
import { isPreview, isProduction } from "../utils/constants";
import { ENV } from "@env";
import { clearUrl, pushResumeUrl } from "../navs/navs";
import { validateTransfer } from "../utils/transferVerification";
import { ChainName } from "@certusone/wormhole-sdk";
//import { validateTransferHandler } from "./providers/sanctions"; // TO DO: Use this function
import { getSortedChains } from "../utils/getSortedChains";

const defaultConfig: WormholeConnectConfig = {
...ENV.wormholeConnectConfig,
eventHandler: (e: WormholeConnectEvent) => {
if (isPreview || isProduction) {
// Send the event to Mixpanel
eventHandler(e);
}
// Update the URL when a transfer starts with a permlink
pushResumeUrl(e);
// Clear the URL when a transfer is successful
clearUrl(e);
},
// validateTransfer
validateTransferHandler: validateTransfer,
isRouteSupportedHandler: async (td: any) => {
// Disable manual NTT for Lido wstETHƒ
return !(
td.route === "nttManual" &&
td.fromToken.tokenId !== "native" &&
[
"0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0",
"0x26c5e01524d2E6280A48F2c50fF6De7e52E9611C",
].includes(td.fromToken.tokenId.address)
);
},
};

export const useConnectConfig = () => {
const [networks, setNetworks] = useState<ChainName[] | null>(null);
const { txHash, sourceChain, targetChain, asset, requiredNetwork, route } =
useQueryParams();
const token = useFormatAssetParam(asset);
const config: ComponentProps<typeof WormholeConnect>["config"] = useMemo(
() => ({
...defaultConfig,
networks: networks!,
//validateTransferHandler,
searchTx: {
...(txHash && { txHash }),
...(sourceChain && { chainName: sourceChain }),
},
bridgeDefaults: {
...(sourceChain && { fromNetwork: sourceChain }),
...(targetChain && { toNetwork: targetChain }),
...(token && { token }),
...(requiredNetwork && { requiredNetwork }),
},
...(route && { routes: [route] }),
}),
[txHash, sourceChain, targetChain, token, requiredNetwork, route, networks]
);

useEffect(() => {
const controller = new AbortController();
getSortedChains(
ENV.wormholeConnectConfig.networks as ChainName[],
controller.signal
).then((chains) => setNetworks(chains));
return () => controller.abort();
}, []);

return networks ? config : undefined;
};
2 changes: 1 addition & 1 deletion apps/connect/src/hooks/useMessages.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ describe("useMessages", () => {
beforeEach(() => {
global.fetch = jest
.fn()
.mockReturnValue({ status: 200, json: async () => [] });
.mockResolvedValue({ status: 200, json: async () => [] });
});

it("should get relevant parsed messages", async () => {
Expand Down
70 changes: 70 additions & 0 deletions apps/connect/src/utils/getSortedChains.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { ChainName } from "@certusone/wormhole-sdk";
import { getSortedChains } from "./getSortedChains";
import topSymbolsByVolume from "./top-symbols-by-volume.json";

describe("getSortedChains", () => {
let unsorted: ChainName[];
beforeEach(() => {
unsorted = [
"wormchain",
"osmosis",
"ethereum",
"sui",
"aptos",
"kujira",
"evmos",
"bsc",
"polygon",
"avalanche",
"fantom",
"celo",
"moonbeam",
"base",
"arbitrum",
"optimism",
"scroll",
"xlayer" as any,
"mantle",
"solana",
"injective",
"klaytn",
];
global.fetch = jest
.fn()
.mockResolvedValue({ status: 200, json: async () => topSymbolsByVolume });
});

it("should get sorted chains", async () => {
const result = await getSortedChains(unsorted);
expect(result).not.toBe(unsorted);
expect(result).toEqual([
"ethereum",
"solana",
"sui",
"arbitrum",
"moonbeam",
"bsc",
"avalanche",
"base",
"optimism",
"polygon",
"aptos",
"wormchain",
"klaytn",
"celo",
"fantom",
"scroll",
"injective",
"mantle",
"osmosis",
"kujira",
"evmos",
"xlayer",
]);
});

it("should get volume per chain when api fails", async () => {
global.fetch = jest.fn().mockRejectedValue({});
expect(await getSortedChains(unsorted)).toEqual(unsorted);
});
});
42 changes: 42 additions & 0 deletions apps/connect/src/utils/getSortedChains.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { ChainId, ChainName, CHAINS } from "@certusone/wormhole-sdk";

interface TopSymbolsByVolume {
symbols: {
tokens: {
emitter_chain: ChainId;
volume: string;
}[];
}[];
}

export const getSortedChains = async (
chains: ChainName[],
signal?: AbortSignal
): Promise<ChainName[]> => {
try {
const response: TopSymbolsByVolume = await fetch(
"https://api.wormholescan.io/api/v1/top-symbols-by-volume?timeSpan=30d",
{ signal, cache: "default" }
).then((r) => r.json());

const volumePerChain = response.symbols
.map(({ tokens }) => tokens)
.flat()
.reduce(
(total, curr) => ({
...total,
[curr.emitter_chain]: Math.floor(
(total[curr.emitter_chain] || 0) + Number(curr.volume)
),
}),
{} as Record<ChainId, number>
);

const getChainScore = (chainName: ChainName): number =>
volumePerChain[CHAINS[chainName]] || 0;

return [...chains].sort((a, b) => getChainScore(b) - getChainScore(a));
} catch {
return chains;
}
};
Loading
Loading