Skip to content

Commit

Permalink
feat: add getSupportedChainIdsFromWalletConnectSession (#855)
Browse files Browse the repository at this point in the history
  • Loading branch information
albertfolch-redeemeum authored Nov 22, 2024
1 parent eac5be2 commit 6863857
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
CoreProtocolConfig
} from "@bosonprotocol/core-sdk";
import { SvgImage } from "../../ui/SvgImage";
import { getSupportedChainIdsFromWalletConnectSession } from "./getSupportedChainIdsFromWalletConnectSession";

const IconAndChevron = styled.div<{
$isOpen: boolean;
Expand Down Expand Up @@ -71,8 +72,6 @@ function useWalletSupportedChains({

switch (connectionType) {
case ConnectionType.WALLET_CONNECT_V2:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return getSupportedChainIdsFromWalletConnectSession(
(connector as WalletConnectV2).provider?.session
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { SessionTypes } from "@walletconnect/types";
import { ChainId } from "@uniswap/sdk-core";

// Helper function to extract chainId from string in format 'eip155:{chainId}'
function getChainIdFromFormattedString(item: string): number | null {
const splitItem = item.startsWith("eip155:") ? item.split(":") : [];
return splitItem.length > 1 && !isNaN(Number(splitItem[1]))
? Number(splitItem[1])
: null;
}

export function getSupportedChainIdsFromWalletConnectSession(
session?: SessionTypes.Struct
): ChainId[] {
if (!session?.namespaces) return [];

const eip155Keys = Object.keys(session.namespaces);
const namespaces = Object.values(session.namespaces);

// Collect all arrays into one for unified processing
const allItems = [
...eip155Keys,
...namespaces.flatMap((namespace) => namespace.chains),
...namespaces.flatMap((namespace) => namespace.accounts)
];

// Process all items to extract chainIds
const allChainIds = allItems
.map((item) => {
if (typeof item === "string") {
return getChainIdFromFormattedString(item);
}
// Check if the item is a number
return isNaN(Number(item)) ? null : Number(item);
})
.filter((item) => item !== null); // Filter out any null values

return Array.from(new Set(allChainIds)) as ChainId[];
}

0 comments on commit 6863857

Please sign in to comment.