Skip to content

Commit

Permalink
Merge pull request #1780 from Web3Auth/feat/react-hooks
Browse files Browse the repository at this point in the history
adds react hooks
  • Loading branch information
chaitanyapotti authored Apr 9, 2024
2 parents 670958f + 111742f commit 4784a9e
Show file tree
Hide file tree
Showing 11 changed files with 2,264 additions and 0 deletions.
Empty file.
2,038 changes: 2,038 additions & 0 deletions packages/hooks/modal-react-hooks/package-lock.json

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions packages/hooks/modal-react-hooks/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"name": "@web3auth/modal-react-hooks",
"version": "8.0.1",
"description": "React hooks to simplify integration with web3Auth modal SDK.",
"keywords": [
"web3Auth/modal-react-hooks",
"web3Auth",
"blockchain",
"react hooks",
"web3Auth hooks",
"web3Auth modal react hooks"
],
"main": "dist/modalReactHooks.cjs.js",
"module": "dist/modalReactHooks.esm.js",
"unpkg": "dist/modalReactHooks.umd.min.js",
"jsdelivr": "dist/modalReactHooks.umd.min.js",
"types": "dist/types/index.d.ts",
"author": "Torus Labs",
"homepage": "https://github.com/Web3Auth/Web3Auth/tree/master/packages/hooks/modal-react-hooks#readme",
"license": "ISC",
"scripts": {
"test": "mocha --config ../../../.mocharc.json test/**.ts",
"test-debugger": "mocha --config ../../../.mocharc.json --inspect-brk test/**.ts",
"dev": "torus-scripts start",
"build": "torus-scripts build",
"lint": "eslint --fix 'src/**/*.ts'",
"prepack": "npm run build",
"pre-commit": "lint-staged --cwd ."
},
"files": [
"dist",
"src"
],
"devDependencies": {
"@web3auth/openlogin-adapter": "^8.0.1"
},
"dependencies": {
"@web3auth/base": "^8.0.0",
"@web3auth/base-plugin": "^8.0.1"
},
"peerDependencies": {
"@babel/runtime": "^7.x",
"@web3auth/base-plugin": "^8.x",
"@web3auth/modal": "^8.x",
"@web3auth/openlogin-adapter": "^8.x",
"react": "^18.x"
},
"lint-staged": {
"!(*d).ts": [
"eslint --cache --fix",
"prettier --write"
]
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Web3Auth/Web3Auth.git"
},
"bugs": {
"url": "https://github.com/Web3Auth/Web3Auth/issues"
},
"engines": {
"node": ">=18.x",
"npm": ">=9.x"
}
}
32 changes: 32 additions & 0 deletions packages/hooks/modal-react-hooks/src/Web3AuthProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { IAdapter } from "@web3auth/base";
import type { IPlugin } from "@web3auth/base-plugin";
import { Web3Auth, Web3AuthOptions } from "@web3auth/modal";
import { createContext, createElement, PropsWithChildren, useEffect, useState } from "react";

export type Web3AuthContextConfig = {
web3AuthOptions: Web3AuthOptions;
adapters?: IAdapter<unknown>[];
plugins?: IPlugin[];
};

export const Web3AuthContext = createContext<Web3Auth | null>(null);

interface Web3AuthProviderProps {
config: Web3AuthContextConfig;
}

export function Web3AuthProvider(params: PropsWithChildren<Web3AuthProviderProps>) {
const { children, config } = params;
const [web3Auth, setWeb3Auth] = useState<Web3Auth | null>(null);

useEffect(() => {
const { web3AuthOptions, adapters = [], plugins = [] } = config;
const web3Instance = new Web3Auth(web3AuthOptions);
if (adapters.length) adapters.map((adapter) => web3Instance.configureAdapter(adapter));
if (plugins.length) plugins.map((plugin) => web3Instance.addPlugin(plugin));
setWeb3Auth(web3Instance);
}, []);

const props = { value: web3Auth };
return createElement(Web3AuthContext.Provider, props, children);
}
2 changes: 2 additions & 0 deletions packages/hooks/modal-react-hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { useWeb3Auth } from "./useWeb3auth";
export { Web3AuthProvider } from "./Web3AuthProvider";
99 changes: 99 additions & 0 deletions packages/hooks/modal-react-hooks/src/useWeb3auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { ADAPTER_EVENTS, CustomChainConfig, type IProvider, WALLET_ADAPTERS } from "@web3auth/base";
import { type ModalConfig } from "@web3auth/modal";
import { type LoginParams, type OpenloginAdapter, type OpenloginUserInfo } from "@web3auth/openlogin-adapter";
import { useContext, useEffect, useState } from "react";

import { Web3AuthContext } from "./Web3AuthProvider";

const WAIT_FOR_INIT_MSG = "Wait for web3auth to be ready first";

export const useWeb3Auth = () => {
const web3auth = useContext(Web3AuthContext);

const [isConnected, setConnected] = useState<boolean>(false);
const [provider, setProvider] = useState<IProvider | null>(null);
const [userInfo, setUserInfo] = useState<Partial<OpenloginUserInfo> | null>(null);
const [isMFAEnabled, setIsMFAEnabled] = useState<boolean>(false);

useEffect(() => {
const addState = async () => {
setProvider(web3auth.provider);
const userState = await web3auth.getUserInfo();
setUserInfo(userState);
setIsMFAEnabled(userState?.isMfaEnabled || false);
};

const resetState = () => {
setProvider(null);
setUserInfo(null);
setIsMFAEnabled(false);
};

if (web3auth) {
if (isConnected) addState();
else resetState();
}
}, [web3auth, isConnected]);

const initModal = async (params: { modalConfig?: Record<string, ModalConfig> } = {}) => {
if (!web3auth) throw new Error(WAIT_FOR_INIT_MSG);

await web3auth.initModal(params);
};

useEffect(() => {
if (web3auth) {
web3auth.on(ADAPTER_EVENTS.CONNECTED, () => setConnected(true));
web3auth.on(ADAPTER_EVENTS.DISCONNECTED, () => setConnected(false));
}
}, [web3auth]);

async function enableMFA(params: Partial<LoginParams> = {}) {
if (!web3auth) throw new Error(WAIT_FOR_INIT_MSG);
if (!isConnected) throw new Error("Connect to a wallet first");
if (web3auth.connectedAdapterName !== WALLET_ADAPTERS.OPENLOGIN) throw new Error("Enable MFA is only supported for OpenLogin.");

if (web3auth.connectedAdapterName === WALLET_ADAPTERS.OPENLOGIN) {
await (web3auth.walletAdapters[WALLET_ADAPTERS.OPENLOGIN] as OpenloginAdapter).openloginInstance?.enableMFA(params);
setIsMFAEnabled(userInfo?.isMfaEnabled || false);
}
}

async function logout(params: { cleanup: boolean } = { cleanup: false }) {
if (!web3auth) throw new Error(WAIT_FOR_INIT_MSG);
if (!isConnected) throw new Error("Connect to a wallet first");

await web3auth.logout(params);
}

async function connect(): Promise<IProvider | null> {
if (!web3auth) throw new Error(WAIT_FOR_INIT_MSG);

const localProvider = await web3auth.connect();
return localProvider;
}

async function addAndSwitchChain(chainConfig: CustomChainConfig) {
if (!web3auth) throw new Error(WAIT_FOR_INIT_MSG);
await web3auth.addChain(chainConfig);

await web3auth.switchChain({ chainId: chainConfig.chainId });
}

return {
web3auth,
isConnected,
provider,
userInfo,
isMFAEnabled,
initModal,
connect,
enableMFA,
logout,
addAndSwitchChain,
addChain: web3auth?.addChain.bind(web3auth),
addPlugin: web3auth?.addPlugin.bind(web3auth),
authenticateUser: web3auth?.authenticateUser.bind(web3auth),
switchChain: web3auth?.switchChain.bind(web3auth),
};
};
1 change: 1 addition & 0 deletions packages/hooks/modal-react-hooks/torus.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require("../../../torus.config");
3 changes: 3 additions & 0 deletions packages/hooks/modal-react-hooks/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"include": ["src"]
}
5 changes: 5 additions & 0 deletions packages/hooks/modal-react-hooks/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../../tsconfig.json",
"include": ["src","test"],
}

15 changes: 15 additions & 0 deletions packages/hooks/modal-react-hooks/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require("path");
const generateWebpackConfig = require("../../../webpack.config");

const pkg = require("./package.json");

const currentPath = path.resolve(".");

const config = generateWebpackConfig({
currentPath,
pkg,
alias: {},
});

module.exports = config;
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@web3auth/*-provider": ["./packages/providers/*-provider"],
"@web3auth/*": ["./packages/*"],
"@web3auth/*-plugin": ["./packages/plugins/*-plugin"],
"@web3auth/*-hooks": ["./packages/hooks/*-hooks"],
},
},
}

0 comments on commit 4784a9e

Please sign in to comment.