Skip to content

Commit

Permalink
feat: auto-switch address page when connected in Ledger Live or iFram…
Browse files Browse the repository at this point in the history
…e context
  • Loading branch information
rkalis committed Dec 18, 2024
1 parent 9390685 commit ab3419f
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions lib/hooks/ethereum/EthereumProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const EthereumProvider = ({ children }: Props) => {

const EthereumProviderChild = ({ children }: Props) => {
const { connectAsync, connectors } = useConnect();
const { connector } = useAccount();
const { connector, address } = useAccount();
const router = useCsrRouter();
const pathName = usePathname();

Expand All @@ -59,7 +59,7 @@ const EthereumProviderChild = ({ children }: Props) => {
// biome-ignore lint/correctness/useExhaustiveDependencies: this hook was checked manually to ensure relevant dependencies are included
useEffect(() => {
// Only supported in an iFrame context
if (typeof window === 'undefined' || window?.parent === window) return;
if (!isIframe()) return;

const safeConnector = connectors?.find((connector) => connector.id === 'safe');
if (!safeConnector || connector === safeConnector) return;
Expand All @@ -77,7 +77,7 @@ const EthereumProviderChild = ({ children }: Props) => {
// (if another connector auto-connects (or user disconnects), we still override it with the Ledger Live connector)
// biome-ignore lint/correctness/useExhaustiveDependencies: this hook was checked manually to ensure relevant dependencies are included
useEffect(() => {
if (typeof window === 'undefined' || !window?.ethereum?.isLedgerLive) return;
if (!isLedgerLive()) return;

const injectedConnector = connectors?.find((connector) => connector.id === 'injected');
if (!injectedConnector || connector === injectedConnector) return;
Expand All @@ -91,5 +91,24 @@ const EthereumProviderChild = ({ children }: Props) => {
.catch(console.error);
}, [connectors, connector]);

// If connected through Ledger or iFrame, then we automatically redirect to the right address page when address changes
// biome-ignore lint/correctness/useExhaustiveDependencies: this hook was checked manually to ensure relevant dependencies are included
useEffect(() => {
if (!isIframe() && !isLedgerLive()) return;
if (!address) return;

if (pathName.startsWith('/address/') && !pathName.includes(address)) {
router.push(`/address/${address}`, { retainSearchParams: ['chainId'] });
}
}, [address]);

return <>{children}</>;
};

const isIframe = () => {
return typeof window !== 'undefined' && window?.parent !== window;
};

const isLedgerLive = () => {
return typeof window !== 'undefined' && window?.ethereum?.isLedgerLive;
};

0 comments on commit ab3419f

Please sign in to comment.