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

Add settings, onlyTestnet, routeConfig, filter props #386

Merged
merged 22 commits into from
Oct 29, 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
37 changes: 37 additions & 0 deletions packages/widget-v2/src/components/EvmDisclaimer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { skipChainsAtom } from "@/state/skipClient";
import { useAtomValue } from "jotai";
import { useMemo } from "react";
import styled, { useTheme } from "styled-components";
import { SmallText } from "./Typography";
import { RouteResponse } from "@skip-go/client";

export const EvmDisclaimer = ({ route }: { route?: RouteResponse } = {}) => {
const theme = useTheme();
const { data: chains } = useAtomValue(skipChainsAtom);

const usesEvmInOperations = useMemo(() => {
return route?.requiredChainAddresses?.find(
(chainId) => {
const chainType = chains?.find(chain => chain.chainID === chainId)?.chainType;
return chainType === "evm";
}
);
}, [chains, route?.requiredChainAddresses]);

if (usesEvmInOperations) {
return (
<StyledEvmWarningMessage>
<SmallText color={theme.warning.text}>
This swap contains at least one EVM chain, so it might take longer.
<br /> Read more about common finality times.
</SmallText>
</StyledEvmWarningMessage>
);
}
};

const StyledEvmWarningMessage = styled.div`
padding: 12px;
border-radius: 5px;
background-color: ${({ theme }) => theme.warning.background};
`;
33 changes: 25 additions & 8 deletions packages/widget-v2/src/devMode/loadWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,33 @@ const DevMode = () => {
};
return (
<Row gap={20}>
<Widget theme={theme} defaultRoute={{
amountIn: 5,
srcChainId: "osmosis-1",
srcAssetDenom: "uosmo",
destChainId: "cosmoshub-4",
destAssetDenom: "uatom",
}}
<Widget
theme={theme}
defaultRoute={{
amountIn: 5,
srcChainId: "osmosis-1",
srcAssetDenom: "uosmo",
destChainId: "cosmoshub-4",
destAssetDenom: "uatom",
}}
settings={{
slippage: 5,
}}
filter={{
source: {
"cosmoshub-4": undefined,
"osmosis-1": undefined,
},
destination: {
"cosmoshub-4": ["uatom"],
"osmosis-1": undefined,
}
}}
/>
<Column>
<button onClick={() => toggleTheme()}> Toggle theme (current theme: {theme})</button>
<button onClick={() => toggleTheme()}>
Toggle theme (current theme: {theme})
</button>
</Column>
</Row>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import {
isGroupedAsset,
} from "./TokenAndChainSelectorModalRowItem";
import { TokenAndChainSelectorModalSearchInput } from "./TokenAndChainSelectorModalSearchInput";
import { matchSorter } from "match-sorter";
import { useGetBalance } from "@/hooks/useGetBalance";
import { Chain } from "@skip-go/client";
import { convertTokenAmountToHumanReadableAmount } from "@/utils/crypto";
import { useFilteredChains } from "./useFilteredChains";
import { useFilteredAssets } from "./useFilteredAssets";
import { useGroupedAssetByRecommendedSymbol } from "./useGroupedAssetsByRecommendedSymbol";

export type GroupedAsset = {
id: string;
Expand All @@ -41,20 +41,18 @@ export type SelectorContext = "source" | "destination";
export type TokenAndChainSelectorModalProps = ModalProps & {
onSelect: (token: ClientAsset | null) => void;
selectedAsset?: ClientAsset;
networkSelection?: boolean;
context: SelectorContext
selectChain?: boolean;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename prop to selectChain, I think it's best to be consistent and always use the same word when referring to chains

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to refactor/change the name of this Modal to AssetsAndChainSelectorModal for the same reason, but I will do it in a separate PR to not mess with the diff

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

context: SelectorContext;
};

export const TokenAndChainSelectorModal = createModal(
(modalProps: TokenAndChainSelectorModalProps) => {
const modal = useModal();
const { onSelect: _onSelect, selectedAsset, networkSelection } = modalProps;
const { onSelect: _onSelect, selectedAsset, selectChain, context } = modalProps;
const { data: assets, isLoading: isAssetsLoading } =
useAtomValue(skipAssetsAtom);
const { data: chains } = useAtomValue(skipChainsAtom);
const { isLoading: isChainsLoading } = useAtomValue(skipChainsAtom);
const isLoading = isAssetsLoading || isChainsLoading;
const getBalance = useGetBalance();

const [showSkeleton, setShowSkeleton] = useState(true);
const [searchQuery, setSearchQuery] = useState<string>("");
Expand Down Expand Up @@ -83,67 +81,7 @@ export const TokenAndChainSelectorModal = createModal(
[_onSelect]
);

const groupedAssetsByRecommendedSymbol = useMemo(() => {
if (!assets) return;
const groupedAssets: GroupedAsset[] = [];

const calculateBalanceSummary = (assets: ClientAsset[]) => {
return assets.reduce(
(accumulator, asset) => {
const balance = getBalance(asset.chainID, asset.denom);
if (balance) {
accumulator.totalAmount += Number(
convertTokenAmountToHumanReadableAmount(
balance.amount,
balance.decimals
)
);
if (Number(balance.valueUSD)) {
accumulator.totalUsd += Number(balance.valueUSD);
}
}
return accumulator;
},
{ totalAmount: 0, totalUsd: 0 }
);
};

assets.forEach((asset) => {
const foundGroup = groupedAssets.find(
(group) => group.id === asset.recommendedSymbol
);
if (foundGroup) {
foundGroup.assets.push(asset);
foundGroup.chains.push({
chainID: asset.chainID,
chainName: asset.chainName,
originChainID: asset.originChainID,
});
} else {
groupedAssets.push({
id: asset.recommendedSymbol || asset.symbol || asset.denom,
chains: [
{
chainID: asset.chainID,
chainName: asset.chainName,
originChainID: asset.originChainID,
},
],
assets: [asset],
totalAmount: 0,
totalUsd: 0,
});
}
});

groupedAssets.forEach((group) => {
const balanceSummary = calculateBalanceSummary(group.assets);
group.totalAmount = balanceSummary.totalAmount;
group.totalUsd = balanceSummary.totalUsd;
});

return groupedAssets;
}, [assets, getBalance]);
const groupedAssetsByRecommendedSymbol = useGroupedAssetByRecommendedSymbol({ context });

const selectedGroup = useMemo(() => {
const asset = groupedAssetSelected?.assets[0] || selectedAsset;
Expand All @@ -157,76 +95,8 @@ export const TokenAndChainSelectorModal = createModal(
groupedAssetsByRecommendedSymbol,
]);

const filteredAssets = useMemo(() => {
if (!groupedAssetsByRecommendedSymbol) return;
return matchSorter(groupedAssetsByRecommendedSymbol, searchQuery, {
keys: ["id"],
}).sort((itemA, itemB) => {
const PRIVILEGED_ASSETS = ["ATOM", "USDC", "USDT", "ETH", "TIA", "OSMO", "NTRN", "INJ"];
if (itemA.totalUsd === 0 && itemB.totalUsd === 0) {
const indexA = PRIVILEGED_ASSETS.indexOf(itemA.id);
const indexB = PRIVILEGED_ASSETS.indexOf(itemB.id);

if (indexA !== -1 && indexB !== -1) {
return indexA - indexB;
}

if (indexA !== -1) return -1;
if (indexB !== -1) return 1;
}

if (itemA.totalUsd < itemB.totalUsd) {
return 1;
}
if (itemA.totalUsd > itemB.totalUsd) {
return -1;
}
return 0;
});
}, [groupedAssetsByRecommendedSymbol, searchQuery]);

const filteredChains = useMemo(() => {
if (!selectedGroup || !chains) return;
const resChains = selectedGroup.assets
.map((asset) => {
const c = chains.find((c) => c.chainID === asset.chainID);
return {
...c,
asset,
};
})
.filter((c) => c) as ChainWithAsset[];
return matchSorter(resChains, searchQuery, {
keys: ["prettyName", "chainName", "chainID"],
}).sort((assetA, assetB) => {
const balanceA = getBalance(
assetA.chainID,
assetA.asset.denom
);
const balanceB = getBalance(
assetB.chainID,
assetB.asset.denom
);

if (Number(balanceA?.valueUSD ?? 0) < Number(balanceB?.valueUSD ?? 0)) {
return 1;
}

if (Number(balanceA?.valueUSD ?? 0) > Number(balanceB?.valueUSD ?? 0)) {
return -1;
}

if (assetB.asset.originChainID === assetB.chainID) {
return 1;
}

if (assetA.asset.originChainID === assetA.chainID) {
return -1;
}

return 0;
});
}, [chains, getBalance, searchQuery, selectedGroup]);
const filteredAssets = useFilteredAssets({ groupedAssetsByRecommendedSymbol, searchQuery });
const filteredChains = useFilteredChains({ selectedGroup, searchQuery, context });

useEffect(() => {
if (!isLoading && assets) {
Expand Down Expand Up @@ -254,28 +124,19 @@ export const TokenAndChainSelectorModal = createModal(
index={index}
onSelect={onSelect}
skeleton={<Skeleton />}
context={modalProps.context}
context={context}
/>
);
},
[modalProps.context, onSelect]
[context, onSelect]
);
const list = useMemo(() => {
if (!networkSelection) {
if (groupedAssetSelected) {
if (modalProps.context === "source") {
return filteredChains?.filter(c => !c.chainID.includes("penumbra"));
}
return filteredChains;
}
return filteredAssets;
}
if (modalProps.context === "source") {
return filteredChains?.filter(c => !c.chainID.includes("penumbra"));
}
return filteredChains;
}, [filteredAssets, filteredChains, groupedAssetSelected, modalProps.context, networkSelection]);

const listOfAssetsOrChains = useMemo(() => {
if (selectChain || groupedAssetSelected) {
return filteredChains;
}
return filteredAssets;
}, [filteredAssets, filteredChains, groupedAssetSelected, selectChain]);
Comment on lines +134 to +139
Copy link
Collaborator Author

@toddkao toddkao Oct 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

simplify logic, moved penumbra filtering to useFilteredChains.ts


const onClickBack = () => {
if (groupedAssetSelected === null) {
Expand Down Expand Up @@ -308,7 +169,7 @@ export const TokenAndChainSelectorModal = createModal(
</Column>
) : (
<VirtualList
listItems={list ?? []}
listItems={listOfAssetsOrChains ?? []}
height={530}
itemHeight={70}
itemKey={(item) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useGetBalance } from "@/hooks/useGetBalance";
import { convertTokenAmountToHumanReadableAmount } from "@/utils/crypto";
import { formatUSD } from "@/utils/intl";
import { ChainWithAsset, GroupedAsset, SelectorContext } from "./TokenAndChainSelectorModal";
import { useFilteredChains } from "./useFilteredChains";

export const isGroupedAsset = (
item: GroupedAsset | ClientAsset | ChainWithAsset
Expand Down Expand Up @@ -105,17 +106,7 @@ const TokenAndChainSelectorModalRowItemLeftContent = ({
item: GroupedAsset;
context: SelectorContext;
}) => {
const { data: chains } = useAtomValue(skipChainsAtom);
const _chainList = item.chains
.map((chain) => {
const _chain = chains?.find((c) => c.chainID === chain.chainID);
return {
chainName: _chain?.prettyName || chain.chainID,
};
})
.sort((a, b) => a.chainName.localeCompare(b.chainName));

const chainList = context === "source" ? _chainList.filter(c => !c.chainName.toLowerCase().includes("penumbra")) : _chainList;
const filteredChains = useFilteredChains({ selectedGroup: item, context }) ?? [];
// prioritize logoURI from raw.githubusercontent over coingecko
const logoURI = item.assets.find((asset) => asset.logoURI?.includes("raw.githubusercontent"))?.logoURI ?? item.assets[0].logoURI;

Expand All @@ -129,10 +120,10 @@ const TokenAndChainSelectorModalRowItemLeftContent = ({
/>
<Row align="end" gap={8}>
<Text>{item.assets[0].recommendedSymbol}</Text>
{chainList.length > 1 ? (
<SmallText>{`${chainList.length} networks`}</SmallText>
{filteredChains.length > 1 ? (
<SmallText>{`${filteredChains.length} networks`}</SmallText>
) : (
chainList.map((chain, index) => (
filteredChains.map((chain, index) => (
<Row key={index} align="center" gap={6}>
{<SmallText>{chain.chainName}</SmallText>}
</Row>
Expand Down
Loading
Loading