Using PnP Web Modal SDK
Once you've installed and successfully initialized Web3Auth, you can use it to authenticate your users. Further, you can use the native provider given by Web3Auth to connect the users to the respective blockchain network.
Natively, the instance of Web3Auth
(referred to as web3auth
in our examples) returns the
following functions:
connect()
- Showing the Modal and Logging in the UsergetUserInfo()
- Getting the User's InformationenableMFA()
- Enable Multi Factor Authentication for the userauthenticateUser()
- Getting the idToken from Web3AuthaddChain()
- Add chain config details to the connected adapter.switchChain()
- Switch chain as per chainId already added to chain config.logout()
- Logging out the User
Additionally the following methods are available to get information about the current state of the instance:
connected
- Returnstrue
orfalse
depending on whether the user is connected or not.status
- Returns the current status of the web3auth instance.provider
- Returns the currently connected provider to the web3auth instance.connectedAdapterName
- Returns the currently connected provider to the web3auth instance.
Finally, with the Wallet Services Plugin, you can enable additional functionalities like:
showCheckout()
- Initiate Topup for the user.showWalletConnectScanner()
- Show WalletConnect QR Code Scanner.showWalletUI()
- Show Embedded Wallet UI.
Logging in the User
You can show the modal in the browser by calling connect()
function on web3auth
instance. Your
user can choose their preferred login method and access your application.
await web3auth.connect();
Returns
connect(): Promise<IProvider | null>;
- On successful login, the
connect()
function returns aIProvider
instance. This instance contains the respective provider corresponding to your selected blockchain. You can use this provider to connect your user to the blockchain and make transactions. - On unsuccessful login, this function will return a
null
value.
Read more about connecting your users with the selected blockchain in the Providers SDK Reference.
Check if the user is connected
connected
You can check if the user is connected to the blockchain by calling the connected
method on the
web3auth
instance. This property method a boolean
value.
const isConnected = web3auth.connected;
Returns
connected: boolean;
If you're using the uxMode: "redirect"
option within your configuration, you need to check this
event to handle the logging in implicitly. This is because, when redirected to a different
application, the app state is not updated as per the login status.
Using this method, you can check if the user is connected and update the app state accordingly within the constructor.
Check which adapter is connected
connectedAdapterName
This function gives you the name of the connected adapter. This can be used to check which adapter is connected to the user.
const adapter = web3auth.connectedAdapterName;
Returns
connectedAdapterName: WALLET_ADAPTER_TYPE | null;
export type WALLET_ADAPTER_TYPE = (typeof WALLET_ADAPTERS)[keyof typeof WALLET_ADAPTERS];
export declare const WALLET_ADAPTERS: {
AUTH: string;
WALLET_CONNECT_V2: string;
SFA: string;
TORUS_SOLANA: string;
TORUS_EVM: string;
COINBASE: string;
};
- If a user is connected, it will return the name of the adapter via which the login has happened.
- If connecting via MIPD (EIP6163) in default evm/ solana adapters, it will return the name of the wallet connected.
- If no user is connected, this function will return a
null
value.
Get the connected provider
provider
Returns the private key provider connected to the web3auth
instance.
Returns
provider: IProvider | null;
- If a user is connected, it will return the provider instance connected to the user.
- If no user is connected, however, the initialisation of the
web3auth
instance is done, it will return the provider instance, however the provider cannot be used for any operations. - If no user is connected and the
web3auth
instance is not initialised, it will return anull
value.
To know more in-depth about providers, have a look at the Providers reference.
Know the current status of the instance
status
Returns the current status of the web3auth
instance.
const status = web3auth.status;
An adapter emits certain events like CONNECTED
, CONNECTING
and DISCONNECTED
etc during login
lifecycle of a user. Knowing to events help you trigger responses based on the status of the
connection of the user. For example, you can use this to show an error message, if the user is not
connected to the network.
Web3Auth provides the following lifecycle event to check the login status:
- Table
- Type Declarations
Event | Description |
---|---|
NOT_READY | Triggered when the adapter is not ready. |
READY | Triggered when the adapter is ready. |
CONNECTING | Triggered when the user is connecting to the wallet. |
CONNECTED | Triggered when the user is connected to the wallet. |
ERRORED | Triggered when an error occurs during the login lifecycle. |
export declare const ADAPTER_STATUS: {
readonly NOT_READY: "not_ready";
readonly READY: "ready";
readonly CONNECTING: "connecting";
readonly CONNECTED: "connected";
readonly ERRORED: "errored";
};
Get User's Information
getUserInfo()
You can get the information about connected user by calling getUserInfo()
function.
This function will only return information based on the connected adapter. These details are not stored anywhere and are fetched from the adapter during the connection and remain in the session.
await web3auth.getUserInfo();
Returns
- Table
- Type Declarations
Variable | Type | Description |
---|---|---|
email | string | Email of the user. |
name | string | Name of the user. |
profileImage | string | Profile image of the user. |
aggregateVerifier | string | Aggregate verifier of the user. |
verifier | string | Verifier of the user. |
verifierId | string | Verifier ID of the user. |
typeOfLogin | string | Type of login provider. |
dappShare | string | Dapp share of the user. |
idToken | string | Token issued by Web3Auth. |
oAuthIdToken | string | Token issued by OAuth provider. Will be available only if you are using custom verifiers. |
oAuthAccessToken | string | Access Token issued by OAuth provider. Will be available only if you are using custom verifiers. |
appState | string | App state of the user. |
touchIDPreference | string | Touch ID preference of the user. |
isMfaEnabled | boolean | Whether Multi Factor Authentication is enabled for the user. |
getUserInfo(): Promise<Partial<AuthUserInfo>>;
declare type UserInfo = AuthUserInfo;
export type AuthUserInfo = {
email?: string;
name?: string;
profileImage?: string;
aggregateVerifier?: string;
verifier: string;
verifierId: string;
typeOfLogin: LOGIN_PROVIDER_TYPE | CUSTOM_LOGIN_PROVIDER_TYPE;
dappShare?: string;
/**
* Token issued by Web3Auth.
*/
idToken?: string;
/**
* Token issued by OAuth provider. Will be available only if you are using
* custom verifiers.
*/
oAuthIdToken?: string;
/**
* Access Token issued by OAuth provider. Will be available only if you are using
* custom verifiers.
*/
oAuthAccessToken?: string;
appState?: string;
touchIDPreference?: string;
isMfaEnabled?: boolean;
};
Sample Response
{
"email": "john@gmail.com",
"name": "John Dash",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"aggregateVerifier": "tkey-google-lrc",
"verifier": "torus",
"verifierId": "john@gmail.com",
"typeOfLogin": "google",
"dappShare": "<24 words seed phrase>", // will be sent only incase of custom verifiers
"idToken": "<jwtToken issued by Web3Auth>",
"oAuthIdToken": "<jwtToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"oAuthAccessToken": "<accessToken issued by OAuth Provider>" // will be sent only incase of custom verifiers
}
Enable Multi Factor Authentication (MFA)
enableMFA()
You can enable Multi Factor Authentication for the user by calling the enableMFA()
function. This
function will trigger a redirect to the MFA setup page, where the user will be asked to login again
and set up the MFA Methods according to the configuration set in the web3auth
instance.
await web3auth.enableMFA();
Interface
enableMFA<T>(loginParams?: T): Promise<void>;
Get idToken for Backend Verification
authenticateUser()
You can get the idToken
from Web3Auth by calling authenticateUser()
function.
This function will only return information based on the connected adapter. These details are not stored anywhere and are fetched from the adapter during the connection and remain in the session.
await web3auth.authenticateUser();
Returns
- Social Login
- External Wallet
- Table
- Type Declarations
Parameter | Type | Description |
---|---|---|
iat | number | The "iat" (issued at) claim identifies the time at which the JWT was issued. |
aud | string | The "aud" (audience) claim identifies the recipients that the JWT is intended for. (Here, it's the dapp client_id ) |
iss | string | The "iss" (issuer) claim identifies who issued the JWT. (Here, it's Web3Auth https://api.openlogin.com/ ) |
email | string | The email address of the user (optional) |
name | string | The name of the user (optional) |
profileImage | string | The profile image of the user (optional) |
verifier | string | Web3auth's verifier used while user login |
verifierId | string | Unique user id given by OAuth login provider |
aggregateVerifier | string | Name of the verifier if you are using a single id verifier (aggregateVerifier) (optional) |
exp | number | The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. |
wallets | array | list of wallets for which this token is issued:
|
authenticateUser(): Promise<UserAuthInfo>
export type UserAuthInfo = { idToken: string };
Sample Response
{
"iat": 1655835494,
"aud": "BCtbnOamqh0cJFEUYA0NB5YkvBECZ3HLZsKfvSRBvew2EiiKW3UxpyQASSR0artjQkiUOCHeZ_ZeygXpYpxZjOs",
"iss": "https://api.openlogin.com/",
"email": "xyz@xyz.com",
"name": "John Doe",
"profileImage": "https://lh3.googleusercontent.com/a/AATXAJx3lnGmHiM4K97uLo9Rb0AxOceH-dQCBSRqGbck=s96-c",
"verifier": "torus",
"verifierId": "xyz@xyz.com",
"aggregateVerifier": "tkey-google-lrc",
"exp": 1655921894,
"wallets": [
{
"public_key": "035143318b83eb5d31611f8c03582ab1200494f66f5e11a67c34f5581f48c1b70b",
"type": "web3auth_key",
"curve": "secp256k1"
}
]
}
- Table
- Type Declarations
Parameter | Type | Description |
---|---|---|
iat | number | The "iat" (issued at) claim identifies the time at which the JWT was issued. |
aud | string | The "audience" claim identifies the recipients that the JWT is intended for. (Here, it's website's url ) |
iss | string | The "issuer" claim identifies who issued the JWT. Here, issuer could be torus-evm , torus-solana , metamask , phantom , walletconnect-v1 , coinbase , solflare |
wallets | array | list of wallets for which this token is issued:
|
authenticateUser(): Promise<UserAuthInfo>
export type UserAuthInfo = { idToken: string };
Sample Response
{
"iat": 1661158877,
"issuer": "<issuer-name>",
"audience": "https://requesting.website",
"wallets": [
{
"address": "0x809d4310d578649d8539e718030ee11e603ee8f3",
"type": "ethereum"
}
],
"exp": 1661245277
}
Add EVM Blockchain to Instance
addChain()
To add a chain config to a connected adapter, you need to call addChain()
function. This function
helps you add the chain config by taking the following parameter:
- Table
- Function Definition
Variable | Description |
---|---|
chainConfig | CustomChainConfig for the chain you want to add. |
async addChain(chainConfig: CustomChainConfig): Promise<void> {
if (this.status !== ADAPTER_STATUS.CONNECTED || !this.connectedAdapterName) throw WalletLoginError.notConnectedError(`No wallet is connected`);
return this.walletAdapters[this.connectedAdapterName].addChain(chainConfig);
}
export type CustomChainConfig = {
chainNamespace: ChainNamespaceType;
/**
* The chain id of the chain
*/
chainId: string;
/**
* RPC target Url for the chain
*/
rpcTarget: string;
/**
* Display Name for the chain
*/
displayName: string;
/**
* Url of the block explorer
*/
blockExplorerUrl: string;
/**
* Default currency ticker of the network (e.g: ETH)
*/
ticker: string;
/**
* Name for currency ticker (e.g: `Ethereum`)
*/
tickerName: string;
/**
* Number of decimals for the currency ticker (e.g: 18)
*/
decimals?: number;
/**
* Logo for the chain
*/
logo: string;
/**
* Whether the network is testnet or not
*/
isTestnet?: boolean;
};
await web3auth.addChain({
chainId: "0xaa36a7",
displayName: "Ethereum Sepolia",
chainNamespace: CHAIN_NAMESPACES.EIP155,
tickerName: "Sepolia",
ticker: "ETH",
decimals: 18,
rpcTarget: "https://rpc.ankr.com/eth_sepolia",
blockExplorerUrl: "https://sepolia.etherscan.io",
logo: "https://images.toruswallet.io/eth.svg",
isTestnet: true,
});
Switch to an EVM Blockchain
switchChain()
To switch the Chain to the added chain config, you need to call switchChain()
function. This
function takes the following parameter:
- Table
- Function Definition
Variable | Description |
---|---|
{ chainId: "0xaa36a7" } | chainId of the added chain config, e.g { chainId: "0xaa36a7" } |
async switchChain(params: { chainId: string }): Promise<void> {
if (this.status !== ADAPTER_STATUS.CONNECTED || !this.connectedAdapterName) throw WalletLoginError.notConnectedError(`No wallet is connected`);
return this.walletAdapters[this.connectedAdapterName].switchChain(params);
}
await web3auth.switchChain({ chainId: "0xaa36a7" });
Logging out the User
web3auth.logout()
You can disconnect from connected wallet using logout
function.
await web3auth.logout();
Type Reference
logout(options?: { cleanup: boolean; }): Promise<void>;
Connecting to a Blockchain
For Connecting to Blockchain and making RPC calls within your dApp, you can use the IProvider
instance returned while logging in the user. This instance gives you the respective provider for
your selection of blockchain. This provider can be used to interact with the connected chain using
exposed functions within the provider.
Web3Auth is chain agnostic, ie. be it any chain you're connecting to, you can use Web3Auth to
connect to it. You can use the EVM
or Solana
provider, that contain the native functions to
connect to the blockchain or use the private key directly to connecting to the respective
blockchain.
Currently web3auth supports providers for both EVM and Solana chains. For other chains, one can easily get the private key from the base provider from Web3Auth.
Wallet Services Plugin Methods
You can use the Wallet Services Plugin to enable additional functionalities like showing the Wallet UI Screen, Wallet Connect Scanner, and initiating topup for the user.
Learn more about the Wallet Services Plugin in the Wallet Services SDK Reference.
Show WalletConnect Scanner
You can use the showWalletConnectScanner
function to show the Wallet Connect Scanner, and connect
with dApps having Wallet Connect login option. This is useful for interoperability with dApps having
Wallet Connect login option.
Learn more about showWalletConnectScanner
.
Fiat On Ramp
You can use the showCheckout
function to show the TopUp modal, allowing users to select their
local currency and specify the token to top up their wallet.
Learn more about showCheckout
.
Embedded Wallet UI
You can use the showWalletUI
function to show the templated wallet UI services.
Learn more about showWalletUI
.
Transaction Confirmatons Screen
You can use the wallet services provider to integrate prebuilt transaction confirmation screens into your application. Upon successful completion, you can retrieve the signature for the request. Learn more about transaction confirmation screens.