Skip to content

Commit

Permalink
feat: create reusable chains package
Browse files Browse the repository at this point in the history
  • Loading branch information
therealemjy committed Dec 3, 2024
1 parent 88a3ac6 commit 5bb2836
Show file tree
Hide file tree
Showing 36 changed files with 295 additions and 140 deletions.
5 changes: 5 additions & 0 deletions .changeset/thirty-spies-wink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@venusprotocol/evm": minor
---

create reusable chains package
13 changes: 2 additions & 11 deletions apps/evm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"generate-subgraph-types": "npm-run-all --parallel generate-subgraph-types:isolated-pools generate-subgraph-types:governance",
"generate-contracts": "rimraf src/libs/contracts/generated/getters && rimraf src/libs/contracts/generated/infos && src/libs/contracts/scripts/generateContractRecords/index.ts && yarn biome format --vcs-use-ignore-file=false --write src/libs/contracts/generated",
"generate-pancake-swap-tokens": "src/libs/tokens/scripts/generatePancakeSwapTokenRecords/index.ts && yarn biome format --vcs-use-ignore-file=false --write src/libs/tokens/generated/pancakeSwapTokens/bscMainnet.ts",
"generate-token-accent-colors": "src/libs/tokens/scripts/generateTokenAccentColors/index.ts && yarn biome format --vcs-use-ignore-file=false --write src/libs/tokens/generated/tokenAccentColors.ts",
"generate-version-files": "genversion --es6 --semi src/constants/version.ts && src/scripts/generatePublicVersionFile.ts && yarn biome format --vcs-use-ignore-file=false --write public/version.json",
"generate": "npm-run-all --parallel generate-version-files generate-contracts generate-subgraph-types && yarn generate-pancake-swap-tokens",
"storybook": "storybook dev -p 6006",
Expand Down Expand Up @@ -157,15 +156,7 @@
"whatwg-fetch": "^3.6.18"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
"production": [">0.2%", "not dead", "not op_mini all"],
"development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"]
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { type QueryObserverOptions, useQuery } from '@tanstack/react-query';

import { chainMetadata } from '@venusprotocol/chains';
import getProposal from 'clients/api/queries/getProposal';
import type { GetProposalInput, GetProposalOutput } from 'clients/api/queries/getProposal/types';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { DEFAULT_REFETCH_INTERVAL_MS } from 'constants/defaultRefetchInterval';
import FunctionKey from 'constants/functionKey';
import { governanceChain } from 'libs/wallet';
Expand All @@ -18,7 +18,7 @@ type Options = QueryObserverOptions<
>;

const useGetProposal = (params: GetProposalInput, options?: Partial<Options>) => {
const { blockTimeMs } = CHAIN_METADATA[governanceChain.id];
const { blockTimeMs } = chainMetadata[governanceChain.id];

return useQuery({
queryKey: [FunctionKey.GET_PROPOSAL, params],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { type QueryObserverOptions, useQuery } from '@tanstack/react-query';

import { chainMetadata } from '@venusprotocol/chains';
import useGetBlockNumber from 'clients/api/queries/getBlockNumber/useGetBlockNumber';
import { useGetProposalMinQuorumVotes } from 'clients/api/queries/getProposalMinQuorumVotes/useGetProposalMinQuorumVotes';
import {
type GetProposalPreviewsInput,
type GetProposalPreviewsOutput,
getProposalPreviews,
} from 'clients/api/queries/getProposalPreviews';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { DEFAULT_REFETCH_INTERVAL_MS } from 'constants/defaultRefetchInterval';
import FunctionKey from 'constants/functionKey';
import { governanceChain } from 'libs/wallet';
Expand Down Expand Up @@ -45,7 +45,7 @@ export const useGetProposalPreviews = (
});
const currentBlockNumber = getBlockNumberData?.blockNumber;

const { blockTimeMs, proposalExecutionGracePeriodMs } = CHAIN_METADATA[governanceChain.id];
const { blockTimeMs, proposalExecutionGracePeriodMs } = chainMetadata[governanceChain.id];

const sanitizedInput: TrimmedGetProposalPreviewsInput = {
...input,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { type QueryObserverOptions, useQuery } from '@tanstack/react-query';

import { chainMetadata } from '@venusprotocol/chains';
import getProposalState, {
type GetProposalStateInput,
type GetProposalStateOutput,
} from 'clients/api/queries/getProposalState';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { DEFAULT_REFETCH_INTERVAL_MS } from 'constants/defaultRefetchInterval';
import FunctionKey from 'constants/functionKey';
import { useGetGovernorBravoDelegateContract } from 'libs/contracts';
Expand All @@ -22,7 +22,7 @@ type Options = QueryObserverOptions<
>;

const useGetProposalState = (input: TrimmedGetProposalStateInput, options?: Partial<Options>) => {
const { blockTimeMs } = CHAIN_METADATA[governanceChain.id];
const { blockTimeMs } = chainMetadata[governanceChain.id];
const governorBravoDelegateContract = useGetGovernorBravoDelegateContract({
chainId: governanceChain.id,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BigNumber from 'bignumber.js';
import { BigNumber as BN } from 'ethers';

import { CHAIN_METADATA } from 'constants/chainMetadata';
import { chainMetadata } from '@venusprotocol/chains';
import type { LegacyPoolComptroller } from 'libs/contracts';
import { ChainId } from 'types';

Expand All @@ -25,7 +25,7 @@ describe('api/queries/getVenusVaiVaultDailyRate', () => {
expect(venusVaiVaultRateMock).toHaveBeenCalledTimes(1);
expect(response).toEqual({
dailyRateMantissa: new BigNumber(fakeOutput.toString()).times(
CHAIN_METADATA[ChainId.BSC_TESTNET].blocksPerDay!,
chainMetadata[ChainId.BSC_TESTNET].blocksPerDay!,
),
});
});
Expand Down
10 changes: 5 additions & 5 deletions apps/evm/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { chainMetadata } from '@venusprotocol/chains';
import { apiUrls } from 'constants/api';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { ChainId, type Environment, type Network } from 'types';
import { extractEnumValues } from 'utilities/extractEnumValues';

Expand Down Expand Up @@ -34,26 +34,26 @@ const chainIds = extractEnumValues(ChainId);
const { rpcUrls, marketsSubgraphUrls, governanceSubgraphUrls } = chainIds.reduce(
(acc, chainId) => {
const chainKey = ChainId[chainId];
const chainMetadata = CHAIN_METADATA[chainId];
const chain = chainMetadata[chainId];

return {
rpcUrls: {
...acc.rpcUrls,
[chainId]:
ENV_VARIABLES[`VITE_RPC_HTTP_URL_${chainKey}` as keyof typeof ENV_VARIABLES] ||
chainMetadata.rpcUrl,
chain.rpcUrl,
},
marketsSubgraphUrls: {
...acc.marketsSubgraphUrls,
[chainId]:
ENV_VARIABLES[`VITE_SUBGRAPH_MARKETS_URL_${chainKey}` as keyof typeof ENV_VARIABLES] ||
chainMetadata.marketsSubgraphUrl,
chain.marketsSubgraphUrl,
},
governanceSubgraphUrls: {
...acc.governanceSubgraphUrls,
[chainId]:
ENV_VARIABLES[`VITE_SUBGRAPH_GOVERNANCE_URL_${chainKey}` as keyof typeof ENV_VARIABLES] ||
chainMetadata.governanceSubgraphUrl,
chain.governanceSubgraphUrl,
},
};
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { chainMetadata } from '@venusprotocol/chains';
import { Select, type SelectOption, type SelectProps } from 'components';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { useUserChainSettings } from 'hooks/useUserChainSettings';
import { useTranslation } from 'libs/translations';
import { chains, useChainId, useSwitchChain } from 'libs/wallet';
Expand All @@ -16,7 +16,7 @@ const getOptions = ({
}: { isGaslessTransactionsSettingEnabled: boolean }) =>
chains.map<SelectOption<ChainId>>(chain => ({
label: ({ isRenderedInButton }) => {
const metadata = CHAIN_METADATA[chain.id as ChainId];
const metadata = chainMetadata[chain.id as ChainId];
return (
<div className="flex items-center">
<img src={metadata.logoSrc} alt={metadata.name} className="w-5 max-w-none flex-none" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type Vi from 'vitest';

import { renderHook } from 'testUtils/render';

import { CHAIN_METADATA } from 'constants/chainMetadata';
import { chainMetadata } from '@venusprotocol/chains';
import { useChainId } from 'libs/wallet';
import { ChainId } from 'types';

Expand All @@ -16,6 +16,6 @@ describe('useGetChainMetadata', () => {

const { result } = renderHook(() => useGetChainMetadata());

expect(result.current).toBe(CHAIN_METADATA[ChainId.BSC_TESTNET]);
expect(result.current).toBe(chainMetadata[ChainId.BSC_TESTNET]);
});
});
4 changes: 2 additions & 2 deletions apps/evm/src/hooks/useGetChainMetadata/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { chainMetadata } from '@venusprotocol/chains';
import { useChainId } from 'libs/wallet';

export const useGetChainMetadata = () => {
const { chainId } = useChainId();
return CHAIN_METADATA[chainId];
return chainMetadata[chainId];
};
4 changes: 2 additions & 2 deletions apps/evm/src/libs/wallet/Web3Wrapper/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { http, createConfig } from 'wagmi';

import localConfig from 'config';
import type { ChainId } from 'types';
import type { Transport } from 'viem';
import type { Chain, Transport } from 'viem';
import { chains } from '../chains';
import { WALLET_CONNECT_PROJECT_ID } from '../constants';

const connectKitConfig = getDefaultConfig({
chains,
chains: chains as [Chain, ...Chain[]],
transports: chains.reduce((acc, chain) => {
const url = localConfig.rpcUrls[chain.id as ChainId];

Expand Down
42 changes: 28 additions & 14 deletions apps/evm/src/libs/wallet/chains.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ChainId, MainnetChainId, TestnetChainId } from '@venusprotocol/chains';
import {
type Chain,
arbitrum as arbitrumOne,
Expand All @@ -15,23 +16,36 @@ import {
} from 'wagmi/chains';

import localConfig from 'config';
import { extractEnumValues } from 'utilities/extractEnumValues';

const getSupportedChains = (): [Chain, ...Chain[]] => {
if (localConfig.network === 'testnet') {
return [
bscTestnet,
opBNBTestnet,
sepolia,
arbitrumSepolia,
zksyncSepoliaTestnet,
optimismSepolia,
];
}

return [bscMainnet, ethereum, opBNBMainnet, arbitrumOne, zksyncMainnet, optimismMainnet];
const chainMapping = {
[ChainId.BSC_MAINNET]: bscMainnet,
[ChainId.BSC_TESTNET]: bscTestnet,
[ChainId.ETHEREUM]: ethereum,
[ChainId.SEPOLIA]: sepolia,
[ChainId.OPBNB_MAINNET]: opBNBMainnet,
[ChainId.OPBNB_TESTNET]: opBNBTestnet,
[ChainId.ARBITRUM_ONE]: arbitrumOne,
[ChainId.ARBITRUM_SEPOLIA]: arbitrumSepolia,
[ChainId.ZKSYNC_MAINNET]: zksyncMainnet,
[ChainId.ZKSYNC_SEPOLIA]: zksyncSepoliaTestnet,
[ChainId.OPTIMISM_MAINNET]: optimismMainnet,
[ChainId.OPTIMISM_SEPOLIA]: optimismSepolia,
} as const satisfies Record<ChainId, Chain>;

const getSupportedChains = () => {
const chainIds =
localConfig.network === 'testnet'
? extractEnumValues(TestnetChainId)
: extractEnumValues(MainnetChainId);

const chains: Chain[] = chainIds.map(chainId => chainMapping[chainId]);

return chains;
};

export const governanceChain = localConfig.network === 'testnet' ? bscTestnet : bscMainnet;
export const governanceChain =
chainMapping[localConfig.network === 'testnet' ? ChainId.BSC_TESTNET : ChainId.BSC_MAINNET];

export const chains = getSupportedChains();

Expand Down
12 changes: 7 additions & 5 deletions apps/evm/src/pages/Account/Settings/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { Card, Icon, Toggle } from 'components';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { useGetChainMetadata } from 'hooks/useGetChainMetadata';
import { useIsFeatureEnabled } from 'hooks/useIsFeatureEnabled';
import { useUserChainSettings } from 'hooks/useUserChainSettings';
import { useTranslation } from 'libs/translations';
import { useChainId } from 'libs/wallet';
import Section from '../Section';

export const Settings: React.FC = () => {
const { t } = useTranslation();
const { chainId } = useChainId();
const { name: chainName } = CHAIN_METADATA[chainId];
const chainMetadata = useGetChainMetadata();
const isGaslessTransactionsFeatureEnabled = useIsFeatureEnabled({ name: 'gaslessTransactions' });

const [{ gaslessTransactions }, setUserChainSettings] = useUserChainSettings();
Expand All @@ -31,7 +29,11 @@ export const Settings: React.FC = () => {
</div>

<div className="flex grow items-center justify-between md:justify-normal gap-3">
<p>{t('account.settings.gaslessTransactions.switchLabel', { chainName })}</p>
<p>
{t('account.settings.gaslessTransactions.switchLabel', {
chainName: chainMetadata.name,
})}
</p>

<Toggle onChange={toggleGaslessTransactions} value={gaslessTransactions} isLight />
</div>
Expand Down
4 changes: 2 additions & 2 deletions apps/evm/src/pages/Bridge/ChainSelect/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { forwardRef } from 'react';

import { chainMetadata } from '@venusprotocol/chains';
import { Select, type SelectOption, type SelectProps } from 'components';
import { CHAIN_METADATA } from 'constants/chainMetadata';
import { chains } from 'libs/wallet';
import type { ChainId } from 'types';

export const getOptionsFromChainsList = (chainsList: typeof chains) =>
chainsList.map(chain => {
const metadata = CHAIN_METADATA[chain.id as ChainId];
const metadata = chainMetadata[chain.id as ChainId];
const option: SelectOption<ChainId> = {
label: (
<div className="flex items-center">
Expand Down
14 changes: 7 additions & 7 deletions apps/evm/src/pages/Bridge/__tests__/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ describe('Bridge', () => {

await waitFor(() =>
expect((getByTestId(TEST_IDS.toChainIdSelect) as HTMLInputElement).value).toEqual(
String(ChainId.OPBNB_TESTNET),
String(ChainId.SEPOLIA),
),
);

Expand Down Expand Up @@ -160,21 +160,21 @@ describe('Bridge', () => {
),
);
expect((getByTestId(TEST_IDS.toChainIdSelect) as HTMLInputElement).value).toEqual(
String(ChainId.OPBNB_TESTNET),
String(ChainId.SEPOLIA),
);

// Click on switch button
fireEvent.click(getByTestId(TEST_IDS.switchChainsButton));

await waitFor(() => expect(switchChainMock).toHaveBeenCalledTimes(1));
expect(switchChainMock).toHaveBeenCalledWith({
chainId: ChainId.OPBNB_TESTNET,
chainId: ChainId.SEPOLIA,
callback: expect.any(Function),
});

await waitFor(() =>
expect((getByTestId(TEST_IDS.fromChainIdSelect) as HTMLInputElement).value).toEqual(
String(ChainId.OPBNB_TESTNET),
String(ChainId.SEPOLIA),
),
);
expect((getByTestId(TEST_IDS.toChainIdSelect) as HTMLInputElement).value).toEqual(
Expand Down Expand Up @@ -204,7 +204,7 @@ describe('Bridge', () => {
const fakeBridgeXvsParams = {
accountAddress: fakeAccountAddress,
amountMantissa: fakeBalanceMantissa,
destinationChainId: ChainId.OPBNB_TESTNET,
destinationChainId: ChainId.SEPOLIA,
nativeCurrencyFeeMantissa: fakeBridgeFeeMantissa,
};

Expand Down Expand Up @@ -262,7 +262,7 @@ describe('Bridge', () => {
// Check the warning shown to the user
await waitFor(() =>
expect(getByTestId(TEST_IDS.notice).textContent).toMatchInlineSnapshot(
'"You cannot bridge more than 0 XVS ($0) on the destination chain in a single transaction"',
`"You cannot bridge more than 0 XVS ($0) on the destination chain in a single transaction"`,
),
);

Expand Down Expand Up @@ -306,7 +306,7 @@ describe('Bridge', () => {
// Check the warning shown to the user
await waitFor(() =>
expect(getByTestId(TEST_IDS.notice).textContent).toMatchInlineSnapshot(
'"You cannot bridge more than 0 XVS ($0) on the destination chain due to the 24-hour limit. This limit will be reset on 13 Jan 2024 12:00 PM"',
`"You cannot bridge more than 0 XVS ($0) on the destination chain due to the 24-hour limit. This limit will be reset on 13 Jan 2024 12:00 PM"`,
),
);

Expand Down
Loading

0 comments on commit 5bb2836

Please sign in to comment.