Initializing PnP Web Modal SDK
After Installation, the next step to use Web3Auth is to Initialize the SDK. However, the Initialization is a two-step process, with an additional two steps for customizations, i.e.
- Instantiation of Web3Auth
- Configuration of Adapters (optional)
- Configuration of Plugins (optional)
- Initialization of Modal
Please note that these are the most critical steps where you need to pass on different parameters according to the preference of your project. Additionally, If you wish to customize your Web3Auth Instance, Whitelabeling and Custom Authentication have to be configured within this step.
Instantiating Web3Auth
Import the Web3Auth
class from @web3auth/modal
import { Web3Auth } from "@web3auth/modal";
Assign the Web3Auth
class to a variable
const web3auth = new Web3Auth(Web3AuthOptions);
This Web3Auth constructor takes an object with Web3AuthOptions
as input.
Arguments
Web3AuthOptions
- Table
- Interface
Parameter | Type | Description | Mandatory | Default |
---|---|---|---|---|
chainConfig | Partial <CustomChainConfig> & Pick <CustomChainConfig, "chainNamespace"> | Custom configuration for your preferred blockchain. Read more about it here. | Yes | |
clientId | string | Client ID for web3auth. Obtain your clientId from the Web3Auth Developer Dashboard. | Yes | |
web3AuthNetwork? | OPENLOGIN_NETWORK_TYPE | Web3Auth Network to use for the session & the issued idToken | No | mainnet |
authMode? | enum - (DAPP , WALLET ) | Web3Auth instance provides different adapters for different type of usages. If you are a dApp and want to use external wallets like metamask, then you can use the DAPP authMode. If you are a wallet and only want to use you own wallet implementations, then you should use WALLET authMode. | No | DAPP |
uiConfig? | UIConfig | Configuration for whitelabeling the Modal UI display properties. Read more about it here | No | Predefined UIConfig used |
enableLogging? | boolean | Setting to true will enable logs | No | false |
storageKey? | enum - (session , local ) | Setting to "local" will persist social login session across browser tabs. | No | local |
sessionTime? | number | sessionTime (in seconds) for idToken issued by Web3Auth for server side verification. Note: max value can be 7 days (86400 * 7) and min can be 1 day (86400) | No | 86400 |
useCoreKitKey? | boolean | Use useCoreKitKey as true , if you're using this SDK with the Single Factor Auth Web SDK | No | false |
interface Web3AuthOptions extends Web3AuthNoModalOptions {
/**
* web3auth instance provides different adapters for different type of usages. If you are dapp and want to
* use external wallets like metamask, then you can use the `DAPP` authMode.
* If you are a wallet and only want to use you own wallet implementations along with openlogin,
* then you should use `WALLET` authMode.
*
* @defaultValue `DAPP`
*/
authMode?: "DAPP" | "WALLET";
/**
* Config for configuring modal ui display properties
*/
uiConfig?: Omit<UIConfig, "adapterListener">;
}
interface Web3AuthNoModalOptions {
/**
* Client id for web3auth.
* You can obtain your client id from the web3auth developer dashboard.
* You can set any random string for this on localhost.
*/
clientId: string;
/**
* custom chain configuration for chainNamespace
*
* @defaultValue mainnet config of provided chainNamespace
*/
chainConfig: Partial<CustomChainConfig> & Pick<CustomChainConfig, "chainNamespace">;
/**
* setting to true will enable logs
*
* @defaultValue false
*/
enableLogging?: boolean;
/**
* setting to "local" will persist social login session accross browser tabs.
*
* @defaultValue "local"
*/
storageKey?: "session" | "local";
/**
* sessionTime (in seconds) for idToken issued by Web3Auth for server side verification.
* @defaultValue 86400
*
* Note: max value can be 7 days (86400 * 7) and min can be 1 day (86400)
*/
sessionTime?: number;
/**
* Web3Auth Network to use for the session & the issued idToken
* @defaultValue mainnet
*/
web3AuthNetwork?: OPENLOGIN_NETWORK_TYPE;
/**
* Uses core-kit key with web3auth provider
* @defaultValue false
*/
useCoreKitKey?: boolean;
}
Adding a Custom Chain Configuration
chainConfig
- Table
- Type Declarations
Parameter | Type | Description | Optional |
---|---|---|---|
chainNamespace |
| The namespace of your preferred chain. Checkout Providers SDK Reference for understanding RPC Calls. | No |
chainId | string | The chain id of the selected blockchain in hex | No |
rpcTarget | string |
| No |
wsTarget | string | Web socket target URL for the chain | Yes |
displayName | string | Display Name for the chain | No |
blockExplorer | string | Blockchain's explorer URL. (eg: https://etherscan.io ) | No |
ticker | string | Default currency ticker of the network (e.g: ETH ) | No |
tickerName | string | Name for currency ticker (e.g: Ethereum ) | No |
decimals | number | Number of decimals for the currency ticker (e.g: 18 ) | Yes |
declare const CHAIN_NAMESPACES: {
readonly EIP155: "eip155";
readonly SOLANA: "solana";
readonly OTHER: "other";
};
declare type ChainNamespaceType = typeof CHAIN_NAMESPACES[keyof typeof CHAIN_NAMESPACES];
declare type CustomChainConfig = {
chainNamespace: ChainNamespaceType;
/**
* The chain id of the chain
*/
chainId: string;
/**
* RPC target Url for the chain
*/
rpcTarget: string;
/**
* web socket target Url for the chain
*/
wsTarget?: string;
/**
* Display Name for the chain
*/
displayName: string;
/**
* Url of the block explorer
*/
blockExplorer: 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;
};
Whitelabeling
Within the uiConfig
parameter, you can configure the Web3Auth Modal according to your application's requirements.
This is just one of the aspects of whitelabeling you can achieve with Web3Auth. To know more in-depth about how you can Whitelabel your application with Web3Auth Plug and Play Modal SDK, have a look at our Whitelabeling SDK Reference.
uiConfig
- Table
- Interface
Parameter | Type | Description | Mandatory | Default |
---|---|---|---|---|
loginMethodsOrder? | string[] | The list of login methods can be reordered with this parameter. Those methods specified will be first on the list. | No | ["google", "facebook", "twitter", "reddit", "discord", "twitch", "apple", "line", "github", "kakao", "linkedin", "weibo", "wechat", "email_passwordless"] |
modalZIndex? | string | Z-index of the modal and iframe | No | "99998" |
displayErrorsOnModal? | boolean | Whether to show errors on Web3Auth modal. | No | true |
loginGridCol? | 2 or 3 | Number of columns to display the Social Login buttons. | No | 3 |
primaryButton? | enum - (externalLogin , socialLogin or emailLogin ) | Decides which button will be displayed as primary button in modal. Only one button will be primary and other buttons in modal will be secondary. | No | socialLogin |
interface UIConfig extends WhiteLabelData {
/**
* order of how login methods are shown
*
* @defaultValue `["google", "facebook", "twitter", "reddit", "discord", "twitch", "apple", "line", "github", "kakao", "linkedin", "weibo", "wechat", "email_passwordless"]`
*/
loginMethodsOrder?: string[];
/**
* Z-index of the modal and iframe
* @defaultValue 99998
*/
modalZIndex?: string;
/**
* Whether to show errors on Web3Auth modal.
*
* @defaultValue `true`
*/
displayErrorsOnModal?: boolean;
/**
* number of columns to display the Social Login buttons
*
* @defaultValue `3`
*/
loginGridCol?: 2 | 3;
/**
* decides which button will be displayed as primary button in modal
* only one button will be primary and other buttons in modal will be secondary
*
* @defaultValue `socialLogin`
*/
primaryButton?: "externalLogin" | "socialLogin" | "emailLogin";
}
WhiteLabelData
whiteLabel?: WhiteLabelData;
The whitelabel parameter takes WhitelabelData
as input. The WhitelabelData
object takes the following parameters:
- Table
- Interface
WhiteLabelData
Parameter | Type | Description | Default | Mandatory |
---|---|---|---|---|
appName? | string | App name to be displayed in the User Flow Screens. | dApp's Website URL | No |
appUrl? | string | App URL to be displayed in the User Flow Screens. | dApp's Website URL | No |
logoLight? | string | App logo to be shown on the dark background (dark theme) | web3auth-logo.svg | No |
logoDark? | string | App logo to be shown on the light background (light theme) | web3auth-logo.svg | No |
defaultLanguage? | string | Default Language to use. Choose from:
| en - English | No |
mode? | string | Choose between auto , light or dark modes. | auto | No |
theme? | { [P in string]: string; } | Used to customize the theme of the login modal with the following options 'primary' - To customize the primary color of the modal's content | #0364FF | No |
tncLink? | Partial<Record<LANGUAGE_TYPE, string>> | Language specific link for terms and conditions on torus-website. See (examples/vue-app) to configure e.g. tncLink: {en: "http://example.com/tnc/en", ja: "http://example.com/tnc/ja"} | none | No |
privacyPolicy? | Partial<Record<LANGUAGE_TYPE, string>> | Language specific link for privacy policy on torus-website. See (examples/vue-app) to configure e.g. privacyPolicy: { en: "http://example.com/tnc/en", ja: "http://example.com/tnc/ja", } | none | No |
export type WhiteLabelData = {
/**
* App name to display in the UI
*/
appName?: string;
/**
* App url
*/
appUrl?: string;
/**
* App logo to use in light mode
*/
logoLight?: string;
/**
* App logo to use in dark mode
*/
logoDark?: string;
/**
* language which will be used by web3auth. app will use browser language if not specified. if language is not supported it will use "en"
* en: english
* de: german
* ja: japanese
* ko: korean
* zh: mandarin
* es: spanish
* fr: french
* pt: portuguese
* nl: dutch
*
* @defaultValue en
*/
defaultLanguage?: LANGUAGE_TYPE;
/**
theme
*
* @defaultValue auto
*/
mode?: THEME_MODE_TYPE;
/**
* Use logo loader
*
* @defaultValue false
*/
useLogoLoader?: boolean;
/**
* Used to customize theme of the login modal with following options
* `'primary'` - To customize primary color of modal's content.
*/
theme?: {
primary?: string;
gray?: string;
red?: string;
green?: string;
success?: string;
warning?: string;
error?: string;
info?: string;
white?: string;
};
/**
* Language specific link for terms and conditions on torus-website. See (examples/vue-app) to configure
* e.g.
* tncLink: {
* en: "http://example.com/tnc/en",
* ja: "http://example.com/tnc/ja",
* }
*/
tncLink?: Partial<Record<LANGUAGE_TYPE, string>>;
/**
* Language specific link for privacy policy on torus-website. See (examples/vue-app) to configure
* e.g.
* privacyPolicy: {
* en: "http://example.com/tnc/en",
* ja: "http://example.com/tnc/ja",
* }
*/
privacyPolicy?: Partial<Record<LANGUAGE_TYPE, string>>;
};
Returns
Object
: The web3auth instance with all its methods and events.
Example
- With Whitelabeling
- Without Whitelabeling
const web3auth = new Web3Auth({
clientId: "", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: "sapphire_mainnet",
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the mainnet RPC we have added, please pass on your own endpoint while creating an app
},
uiConfig: {
theme: "dark",
loginMethodsOrder: ["facebook", "google"],
appLogo: "https://web3auth.io/images/w3a-L-Favicon-1.svg", // Your App Logo Here
},
defaultLanguage: "en",
modalZIndex: "99998",
});
const web3auth = new Web3Auth({
clientId: "", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: "sapphire_mainnet",
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the mainnet RPC we have added, please pass on your own endpoint while creating an app
},
});
Configuring Adapters
An adapter is a pluggable package that implements IAdapter
interface for a wallet within Web3Auth. An adapter can be plugged in and out of web3auth
modal. Each adapter exposes the provider on successful user login which can be used to invoke RPC calls on the wallet and on the connected blockchain.
Web3Auth's modal UI supports a set of default adapters depending on the authMode
being used.
This step is generally optional. You don't have to configure any default adapter unless you want to override default configs for the adapter.
Only those adapters that are marked are nondefault in this table on the Adapters Documentation
are required to be configured always based on the authMode
you are using.
Configuring Openlogin Adapter
The default adapter of Web3Auth is the openlogin-adapter
. This adapter is a wrapper around the
openlogin
library from Web3Auth and enables the social login features. For customising features of the main
Web3Auth flow, like Whitelabel, Custom Authentication, etc. you need to customise
the Openlogin Adapter.
Checkout the openlogin-adapter
SDK Reference for more details on different configurations you can pass for
customisations.
Whitelabeling
whiteLabel
For customising the redirect screens while logging in and constructing the key, you need to pass on whiteLabel
configurations to the
adapterSettings
property of the openlogin-adapter
.
This is just one of the aspects of whitelabeling you can achieve with Web3Auth. To know more in depth about how you can Whitelabel your application with Web3Auth, have a look at our Whitelabeling SDK Reference.
Example
import OpenloginAdapter from "@web3auth/openlogin-adapter";
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId, //Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
network: "sapphire_mainnet", // Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
uxMode: "popup",
whiteLabel: {
appName: "W3A Heroes",
appUrl: "https://web3auth.io",
logoLight: "https://web3auth.io/images/w3a-L-Favicon-1.svg",
logoDark: "https://web3auth.io/images/w3a-D-Favicon-1.svg",
defaultLanguage: "en", // en, de, ja, ko, zh, es, fr, pt, nl
mode: "dark", // whether to enable dark mode. defaultValue: auto
theme: {
primary: "#00D1B2",
},
useLogoLoader: true,
},
},
privateKeyProvider,
});
web3auth.configureAdapter(openloginAdapter);
Custom Authentication
loginConfig
With Web3Auth, you have the option to configure logins using your own authentication services. For adding your own authentication, you have to first configure your verifiers in the Web3Auth Dashboard. Have a look at our Custom Authentication Documentation for configuring that first.
Custom Authentication in Web3Auth is supported by the Openlogin Adapter, which is the default adapter for the Web3Auth SDK. For this, you need to
configure the loginConfig
parameter in the adapterSettings
of the openlogin-adapter
package.
Refer to the Custom Authentication Documentation for more information.
Example
Since we're using the @web3auth/modal
, ie. the Plug and Play Modal SDK, the loginConfig
should correspond to the socials mentioned in the modal.
Here, we're customizing Google and Facebook to be custom verified, rest all other socials will be default. You can customize other social logins or
remove them using the whitelabeling option.
- Discord
- Twitch
import OpenloginAdapter from "@web3auth/openlogin-adapter";
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId, //Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
uxMode: "popup",
loginConfig: {
// Google login
google: {
verifier: "YOUR_GOOGLE_VERIFIER_NAME", // Please create a verifier on the developer dashboard and pass the name here
typeOfLogin: "google", // Pass on the login provider of the verifier you've created
clientId: "GOOGLE_CLIENT_ID.apps.googleusercontent.com", // Pass on the clientId of the login provider here - Please note this differs from the Web3Auth ClientID. This is the JWT Client ID
},
},
},
privateKeyProvider,
});
web3auth.configureAdapter(openloginAdapter);
import OpenloginAdapter from "@web3auth/openlogin-adapter";
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId, //Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
uxMode: "popup",
loginConfig: {
// Facebook login
facebook: {
verifier: "YOUR_FACEBOOK_VERIFIER_NAME", // Please create a verifier on the developer dashboard and pass the name here
typeOfLogin: "facebook", // Pass on the login provider of the verifier you've created
clientId: "FACEBOOK_CLIENT_ID_1234567890", // Pass on the clientId of the login provider here - Please note this differs from the Web3Auth ClientID. This is the JWT Client ID
},
},
},
privateKeyProvider,
});
web3auth.configureAdapter(openloginAdapter);
import OpenloginAdapter from "@web3auth/openlogin-adapter";
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId, //Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
uxMode: "popup",
loginConfig: {
// Discord login
discord: {
verifier: "YOUR_DISCORD_VERIFIER_NAME", // Please create a verifier on the developer dashboard and pass the name here
typeOfLogin: "discord", // Pass on the login provider of the verifier you've created
clientId: "DISCORD_CLIENT_ID_1234567890", //use your app client id you got from discord
},
},
},
privateKeyProvider,
});
web3auth.configureAdapter(openloginAdapter);
import OpenloginAdapter from "@web3auth/openlogin-adapter";
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId, //Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
uxMode: "popup",
loginConfig: {
// Facebook login
facebook: {
verifier: "YOUR_TWITCH_VERIFIER_NAME", // Please create a verifier on the developer dashboard and pass the name here
typeOfLogin: "twitch", // Pass on the login provider of the verifier you've created
clientId: "TWITCH_CLIENT_ID_1234567890", //use your app client id you got from twitch
},
},
},
privateKeyProvider,
});
web3auth.configureAdapter(openloginAdapter);
Configuring External Wallet Adapters
configureAdapter(ADAPTER)
To configure an adapter, create the instance of adapter by using its corresponding package and pass the returned adapter
instance in
configureAdapter
function.
Refer to the Adapters documentation to know more deeply about what adapters are available and how to configure them.
Example
If you want to configure the Torus EVM Wallet Adapter
- Import the
TorusWalletAdapter
from@web3auth/torus-evm-adapter
package - Create an instance of the adapter along with the configuration
- Pass the returned instance in to
web3auth.configureAdapter
import { TorusWalletAdapter } from "@web3auth/torus-evm-adapter";
const torusAdapter = new TorusWalletAdapter({
adapterSettings: {
clientId, //Optional - Provide only if you haven't provided it in the Web3Auth Instantiation Code
buttonPosition: "bottom-left",
},
loginSettings: {
verifier: "google",
},
initParams: {
buildEnv: "testing",
},
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth", // This is the mainnet RPC we have added, please pass on your own endpoint while creating an app
displayName: "Ethereum Mainnet",
blockExplorer: "https://etherscan.io/",
ticker: "ETH",
tickerName: "Ethereum",
},
});
web3auth.configureAdapter(torusAdapter);
Subscribing the Lifecycle Events
Subscribing to events help you trigger responses based on the status of the connection of the user. An adapter emits certain events like CONNECTED
,
CONNECTING
and DISCONNECTED
etc during login lifecycle of a user. For example, you can use this to show an error message, if the user is not
connected to the network. Generally, this is not a required step and should be done only if needed in particular cases.
This step is totally optional. If you don't want to use any plugins, feel free to skip this section.
If you're using the uxMode: "redirect"
option within your openlogin-adapter
configuration, you need to
subscribe to the 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 a lifecycle method to check this, one can easily handle the login status within the constructor function.
on(EVENT, CALLBACK)
Web3Auth provides the following lifecycle event to check the login status:
Adapter Events
- Table
- Type Declarations
Event | Trigger with @web3auth/base package | Trigger without package | Description |
---|---|---|---|
ADAPTER_DATA_UPDATED | ADAPTER_EVENTS.ADAPTER_DATA_UPDATED | "adapter_data_updated" | Adapter data is updated within the dApp |
NOT_READY | ADAPTER_EVENTS.NOT_READY | "not_ready" | Adapter is not yet ready for login |
READY | ADAPTER_EVENTS.READY | "ready" | Adapter is ready for login |
CONNECTING | ADAPTER_EVENTS.CONNECTING | "connecting" | User is connecting to the dApp/ login process is in progress |
CONNECTED | ADAPTER_EVENTS.CONNECTED | "connected" | User is logged in and connected with the dApp |
DISCONNECTED | ADAPTER_EVENTS.DISCONNECTED | "disconnected" | User is logged out and disconnected from the dApp |
ERRORED | ADAPTER_EVENTS.ERRORED | "errored" | There has been some error in connecting the user to the dApp |
declare const ADAPTER_EVENTS: {
readonly ADAPTER_DATA_UPDATED: "adapter_data_updated";
readonly NOT_READY: "not_ready";
readonly READY: "ready";
readonly CONNECTING: "connecting";
readonly CONNECTED: "connected";
readonly DISCONNECTED: "disconnected";
readonly ERRORED: "errored";
};
Example
import { ADAPTER_EVENTS } from "@web3auth/base";
// subscribe to lifecycle events emitted by web3auth
const subscribeAuthEvents = (web3auth: Web3Auth) => {
web3auth.on(ADAPTER_EVENTS.CONNECTED, (data: CONNECTED_EVENT_DATA) => {
console.log("connected to wallet", data);
// web3auth.provider will be available here after user is connected
});
web3auth.on(ADAPTER_EVENTS.CONNECTING, () => {
console.log("connecting");
});
web3auth.on(ADAPTER_EVENTS.DISCONNECTED, () => {
console.log("disconnected");
});
web3auth.on(ADAPTER_EVENTS.ERRORED, (error) => {
console.log("error", error);
});
web3auth.on(ADAPTER_EVENTS.ERRORED, (error) => {
console.log("error", error);
});
};
Login Modal Events
- Table
- Interface
Event | Trigger with @web3auth/ui package | Trigger without package | Description |
---|---|---|---|
INIT_EXTERNAL_WALLETS | LOGIN_MODAL_EVENTS.INIT_EXTERNAL_WALLETS | "INIT_EXTERNAL_WALLETS" | External Wallet are initialised |
LOGIN | LOGIN_MODAL_EVENTS.LOGIN | "LOGIN" | Login is triggered |
DISCONNECT | LOGIN_MODAL_EVENTS.DISCONNECT | "DISCONNECT" | Disconnection is triggered |
MODAL_VISIBILITY | LOGIN_MODAL_EVENTS.MODAL_VISIBILITY | "MODAL_VISIBILITY" | Indicates whether the modal is visible or not |
declare const LOGIN_MODAL_EVENTS: {
readonly INIT_EXTERNAL_WALLETS: "INIT_EXTERNAL_WALLETS";
readonly LOGIN: "LOGIN";
readonly DISCONNECT: "DISCONNECT";
readonly MODAL_VISIBILITY: "MODAL_VISIBILITY";
};
Example
import { LOGIN_MODAL_EVENTS } from "@web3auth/ui";
// subscribe to lifecycle events emitted by web3auth
const subscribeAuthEvents = (web3auth: Web3Auth) => {
// emitted when modal visibility changes.
web3auth.on(LOGIN_MODAL_EVENTS.MODAL_VISIBILITY, (isVisible) => {
console.log("is modal visible", isVisible);
});
};
Configuring Plugins
Plugins are essentially extensions to the core functionality of Web3Auth, allowing you to add additional features to your dApp. These features can be used to extend the UI functionalities, making your integration more interoperable, and a lot more, even having the functionality to be customised extremely and to your liking.
This step is totally optional. If you don't want to use any plugins, feel free to skip this section.
Currently Web3Auth supports the following two plugins:
Learn about adding plugins to your Web3Auth instance here.
showWalletConnectScanner()
Shows the Wallet Connect Scanner to connect with dApps having Wallet Connect login option.
Example
import { TorusWalletConnectorPlugin } from "@web3auth/torus-wallet-connector-plugin";
const torusPlugin = new TorusWalletConnectorPlugin({
torusWalletOpts: {},
walletInitOptions: {
whiteLabel: {
theme: { isDark: true, colors: { primary: "#00a8ff" } },
logoDark: "https://web3auth.io/images/w3a-L-Favicon-1.svg",
logoLight: "https://web3auth.io/images/w3a-D-Favicon-1.svg",
},
useWalletConnect: true, // make sure this is enabled before using the showWalletConnectScanner function
enableLogging: true,
},
});
await web3auth.addPlugin(torusPlugin); // add plugin to web3auth instance
await torusPlugin.showWalletConnectScanner();
initiateTopup()
Initiates the Top Up flow with selected provider.
Arguments
- Table
- Interface
Parameter | Type | Description | Mandatory |
---|---|---|---|
provider | PAYMENT_PROVIDER_TYPE ["moonpay" , "wyre" , "rampnetwork" , "xanpool" , "mercuryo" , "transak" , "banxa" ] | Payment Provider name | Yes |
params | PaymentParams | Payment Params object | Yes |
PaymentParams
Parameter | Type | Description | Mandatory |
---|---|---|---|
selectedAddress? | string | Address to send the funds to | No |
selectedCurrency? | string | Default fiat currency for the user to make the payment in | No |
fiatValue? | number | Amount to buy in the selectedCurrency | No |
selectedCryptoCurrency? | string | Cryptocurrency to buy | No |
chainNetwork? | SUPPORTED_PAYMENT_NETWORK_TYPE ["mainnet" , "matic" , "bsc_mainnet" , "avalanche_mainnet" , "xdai" ] | Chain Network to use | No |
async initiateTopup(provider: PAYMENT_PROVIDER_TYPE, params: PaymentParams): Promise<void> {
if (!this.torusWalletInstance.isLoggedIn) throw TorusWalletPluginError.web3AuthNotConnected();
await this.torusWalletInstance.initiateTopup(provider, params);
}
export interface PaymentParams {
/**
* Address to send the funds to
*/
selectedAddress?: string;
/**
* Default fiat currency for the user to make the payment in
*/
selectedCurrency?: string;
/**
* Amount to buy in the selectedCurrency
*/
fiatValue?: number;
/**
* Cryptocurrency to buy
*/
selectedCryptoCurrency?: string;
/**
* Chain Network to use
*/
chainNetwork?: SUPPORTED_PAYMENT_NETWORK_TYPE;
}
export const PAYMENT_PROVIDER = {
MOONPAY: "moonpay",
WYRE: "wyre",
RAMPNETWORK: "rampnetwork",
XANPOOL: "xanpool",
MERCURYO: "mercuryo",
TRANSAK: "transak",
BANXA: "banxa",
} as const;
export const SUPPORTED_PAYMENT_NETWORK = {
MAINNET: "mainnet",
MATIC: "matic",
BSC_MAINNET: "bsc_mainnet",
AVALANCHE_MAINNET: "avalanche_mainnet",
XDAI: "xdai",
} as const;
Example
import { TorusWalletConnectorPlugin } from "@web3auth/torus-wallet-connector-plugin";
const torusPlugin = new TorusWalletConnectorPlugin({
torusWalletOpts: {},
walletInitOptions: {
whiteLabel: {
theme: { isDark: true, colors: { primary: "#00a8ff" } },
logoDark: "https://web3auth.io/images/w3a-L-Favicon-1.svg",
logoLight: "https://web3auth.io/images/w3a-D-Favicon-1.svg",
},
useWalletConnect: true,
enableLogging: true,
},
});
await web3auth.addPlugin(torusPlugin); // add plugin to web3auth instance
await torusPlugin.initiateTopup("moonpay", {
selectedAddress: "wallet_address",
selectedCurrency: "USD", // Fiat currency
fiatValue: 100, // Fiat Value
selectedCryptoCurrency: "ETH", // Cryptocurreny `SOL`, `MATIC` etc.
chainNetwork: "mainnet", // Blockchain network
});
Initializing Modal
initModal()
The final step in the whole initialization process is the initialize the Modal from Web3Auth.
This is done by calling initModal
function of the web3auth
instance we created above.
await web3auth.initModal(params);
Arguments
The web3auth.initModal
takes an optional params
config object as input.
params?: {
modalConfig?: Record<WALLET_ADAPTER_TYPE, ModalConfig>;
}
This params
object further takes a modalConfig
object using which you can configure the visibility of each adapter within the modal. Each modal
config has the following configurations:
modalConfig
- Table
- Interface
modalConfig: { ADAPTER : { params } }
Parameter | Type | Description | Default | Mandatory |
---|---|---|---|---|
label | string | Label of the adapter you want to configure | NA - identifier for corresponding adapter | Yes |
showOnModal? | boolean | Whether to show an adapter in modal or not. | true | No |
showOnDesktop? | boolean | Whether to show an adapter in desktop or not. | true | No |
showOnMobile? | boolean | Whether to show an adapter in mobile or not. | true | No |
Additionally, to configure the Openlogin Adapter's each login method, we have the loginMethods?
parameter.
Parameter | Type | Description | Default | Mandatory |
---|---|---|---|---|
loginMethods? | LoginMethodConfig | To configure visibility of each social login method for the openlogin adapter. | Default LoginMethod for each social login | No |
initModal(params?: {
modalConfig?: Record<WALLET_ADAPTER_TYPE, ModalConfig>;
}): Promise<void>;
interface ModalConfig extends BaseAdapterConfig {
loginMethods?: LoginMethodConfig;
}
interface BaseAdapterConfig {
label: string;
showOnModal?: boolean;
showOnMobile?: boolean;
showOnDesktop?: boolean;
}
loginMethods: { label: { params } }
In loginMethods
, you can configure the visibility of each social login method for the openlogin adapter. The social login is corresponded by the
label
parameter. Below is the table indicating the different params
available for customization.
For labels
you can choose between these options: google
, facebook
, twitter
, reddit
, discord
, twitch
, apple
, line
, github
, kakao
,
linkedin
, weibo
, wechat
, email_passwordless
- Table
- Type Declaration
params
Parameter | Type | Description | Default | Mandatory |
---|---|---|---|---|
name | string | Display Name | Default for Openlogin App | No |
description? | string | Description for button. If provided, it renders as a full length button. else, icon button | Just an icon rendered | No |
logoHover? | string | Logo to be shown on mouse hover | web3auth-logo.svg | No |
logoLight? | string | Logo to be shown on dark background (dark theme) | web3auth-logo.svg | No |
logoDark? | string | Logo to be shown on light background (light theme) | web3auth-logo.svg | No |
mainOption? | boolean | Show login button on the main list | Default for Openlogin App | No |
showOnModal? | string | Whether to show the login button on modal or not | Default for Openlogin App | No |
showOnDesktop? | string | Whether to show the login button on desktop | Default for Openlogin App | No |
showOnMobile? | string | Whether to show the login button on mobile | Default for Openlogin App | No |
declare type LoginMethodConfig = Record<
string,
{
/**
* Display Name. If not provided, we use the default for openlogin app
*/
name: string;
/**
* Description for button. If provided, it renders as a full length button. else, icon button
*/
description?: string;
/**
* Logo to be shown on mouse hover. If not provided, we use the default for openlogin app
*/
logoHover?: string;
/**
* Logo to be shown on dark background (dark theme). If not provided, we use the default for openlogin app
*/
logoLight?: string;
/**
* Logo to be shown on light background (light theme). If not provided, we use the default for openlogin app
*/
logoDark?: string;
/**
* Show login button on the main list
*/
mainOption?: boolean;
/**
* Whether to show the login button on modal or not
*/
showOnModal?: boolean;
/**
* Whether to show the login button on desktop
*/
showOnDesktop?: boolean;
/**
* Whether to show the login button on mobile
*/
showOnMobile?: boolean;
}
>;
Example
- With Modal Configurations
- Without Modal Configurations
await web3auth.initModal({
modalConfig: {
[WALLET_ADAPTERS.OPENLOGIN]: {
label: "openlogin",
loginMethods: {
google: {
name: "google login",
logoDark: "url to your custom logo which will shown in dark mode",
},
facebook: {
// it will hide the facebook option from the Web3Auth modal.
name: "facebook login",
showOnModal: false,
},
},
// setting it to false will hide all social login methods from modal.
showOnModal: true,
},
},
});
await web3auth.initModal();