From 8388d55b45631bb51c97922473f08c9e736c60af Mon Sep 17 00:00:00 2001 From: snoopy1412 Date: Sat, 25 May 2024 22:51:38 +0800 Subject: [PATCH] Implement automatic Safe login via custom hook --- .gitignore | 3 ++- package.json | 2 +- src/components/header.tsx | 2 ++ src/hooks/useAppAutoConnect.ts | 34 +++++++++++++++++++++++++++++ src/providers/web3-app-provider.tsx | 2 +- 5 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 src/hooks/useAppAutoConnect.ts diff --git a/.gitignore b/.gitignore index 2bd78d4..4de3d5a 100644 --- a/.gitignore +++ b/.gitignore @@ -35,4 +35,5 @@ yarn-error.log* *.tsbuildinfo next-env.d.ts -/.vscode \ No newline at end of file +/.vscode +certificates \ No newline at end of file diff --git a/package.json b/package.json index a5df2ee..8fc81fa 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": true, "scripts": { - "dev": "next dev --turbo", + "dev": "next dev --turbo --experimental-https", "build": "next build", "start": "next start", "lint": "next lint" diff --git a/src/components/header.tsx b/src/components/header.tsx index 001a7bd..916efe7 100644 --- a/src/components/header.tsx +++ b/src/components/header.tsx @@ -2,8 +2,10 @@ import Image from 'next/image'; import Link from 'next/link'; import ConnectButton from '@/components/connect-button'; +import { useAppAutoConnect } from '@/hooks/useAppAutoConnect'; const Header = () => { + useAppAutoConnect(); return (
diff --git a/src/hooks/useAppAutoConnect.ts b/src/hooks/useAppAutoConnect.ts new file mode 100644 index 0000000..d654f69 --- /dev/null +++ b/src/hooks/useAppAutoConnect.ts @@ -0,0 +1,34 @@ +import { useConnect, useReconnect } from 'wagmi'; +import { useEffect } from 'react'; +import { Connector } from 'wagmi'; + +interface AppConnector extends Connector { + rkDetails?: { + installed: boolean; + isRainbowKitConnector: boolean; + }; +} + +function useAppAutoConnect() { + const { connect, connectors } = useConnect(); + const { reconnect } = useReconnect(); + + useEffect(() => { + if (window.self !== window.top) { + const appConnector = connectors.find( + (connector: AppConnector) => + connector.id === 'safe' && + connector.rkDetails?.installed && + connector.rkDetails?.isRainbowKitConnector + ) as AppConnector; + + if (appConnector) { + connect({ connector: appConnector }); + return; + } + } + reconnect(); + }, [connect, connectors, reconnect]); +} + +export { useAppAutoConnect }; diff --git a/src/providers/web3-app-provider.tsx b/src/providers/web3-app-provider.tsx index 81c77ed..0a9f7e4 100644 --- a/src/providers/web3-app-provider.tsx +++ b/src/providers/web3-app-provider.tsx @@ -46,7 +46,7 @@ const queryClient = new QueryClient(); export function Web3AppProvider({ children }: React.PropsWithChildren<{}>) { return ( - + {children}