Skip to main content

Usage of Core Kit SFA Web 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 (called web3auth in our examples) returns the following functions:

  • connect() - Logs in the User using the verifier, verifierId & idToken, which are mandatory, while subVerifierInfoArray and serverTimeOffset are optional.
  • provider() - Returns the native provider that can be used to make different blockchain transactions.
  • sessionId() - Returns the sessionId of the user as a string.
  • authenticateUser() - Returns a promise of the UserAuthInfo object containing the idToken of the user.
  • addChain() - Add chain configuration to the web3auth instance.
  • switchChain() - Switches the chainId to one of the added chainIds.
  • getUserInfo() - Returns the user information.
  • logout() - Log out the user from the web3auth instance.

Logging in your User

connect(loginParams: LoginParams)

To log a user in the Web3Auth SFA Web SDK, you need to call the connect() function.

VariableDescription
loginParamsMandatory login Parameters

Returns

connect(loginParams: LoginParams): Promise<IProvider | null>

LoginParams

connect(loginParams: LoginParams)

On successful login, the connect() function returns a IProvider instance. This instance contains the corresponding provider for your selected blockchain. You can use this provider to connect your user to the blockchain and perform transactions.

On unsuccessful login, this function will return a null value.

LoginParams

ParameterDescription
verifierDetails of the verifier. It's a mandatory parameter as a string.
verifierIdVerifier ID's value, sub or email value present in the idToken. It's a mandatory parameter as a string.
idTokenA newly created JWT Token that has not already been sent to Web3Auth or a Duplicate Token error will be thrown. It's a mandatory parameter as a string.
subVerifierInfoArray?Sub verifier info. It's an optional parameter as a TorusSubVerifierInfo[].
serverTimeOffset?Server time offset. It's an optional parameter as a number.

TorusSubVerifierInfo

ParameterDescription
verifierDetails of the verifier (verifier type, ie. torus, metamask, openlogin etc.). It's a string mandatory parameter.
idTokenA newly created JWT Token that has not already been sent to Web3Auth or a Duplicate Token error will be thrown. It's a string mandatory parameter.

Usage

await web3auth.connect({
verifier: "verifier-name", // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId: "verifier-id-value", // e.g. `Yux1873xnibdui` or `name@email.com` replace with your verifier id(sub or email)'s value.
idToken: "JWT Token", // replace with your newly created unused JWT Token.
});

Get a native provider

provider()

Returns the native provider that can be used to make different blockchain transactions.

Returns

get provider(): IProvider | null;

Get sessionId

sessionId()

Returns the sessionId of the user as a string.

Returns

get sessionId(): string;

Authenticate the user

authenticateUser()

Returns a promise of the UserAuthInfo object containing the idToken of the user.

Returns

authenticateUser(): Promise<UserAuthInfo>;

UserAuthInfo

export type UserAuthInfo = {
idToken: string;
};

Add a new chain

addChain(chainConfig: CustomChainConfig)

Add chain configuration to the web3auth instance.

VariableDescription
chainConfigMandatory chain-specific configuration as a CustomChainConfig type.

CustomChainConfig

ParameterDescription
chainNamespaceNamespace of the chain. It's a mandatory parameter as a ChainNamespaceType type.
chainIdThe chain id of the chain. It's a mandatory parameter as a string.
rpcTargetRPC target URL for the chain. It's a mandatory parameter as a string.
wsTargetWeb socket target URL for the chain. It's an optional parameter as a string.
displayNameDisplay Name for the chain. It's an optional parameter as a string.
blockExplorerUrlURL of the block explorer. It's an optional parameter as a string.
tickerDefault currency ticker of the network (e.g: ETH). It's an optional parameter as a string.
tickerNameName for currency ticker (e.g: Ethereum). It's an optional parameter as a string.
decimalsNumber of decimals for the currency ticker (e.g: 18). It's an optional parameter as a number.
logoLogo for the token. It's an optional parameter as a string.
isTestnetWhether the network is testnet or not. It's an optional parameter as a boolean.

Switch the chain

switchChain(params: {chainId: string;})

Switch to one of the added chains

VariableDescription
chainIdId of the chain to switch to. It's a mandatory parameter as a string

Logging out the user

logout()

Logs out the user and clears the session.

Note

@web3auth/single-factor-auth SDK only works for users who have not enabled MFA.

MFA enabled users

For MFA enabled users, you'll see Error("User has already enabled mfa, please use the @webauth/webauth-web sdk for login with mfa");

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.

tip

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.

Example

Custom JWT Example

Custom JWT Example
import { Web3Auth } from "@web3auth/single-factor-auth";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import jwt from "jsonwebtoken";
import fs from "fs";

// Use "openssl genrsa -out privateKey.pem 2048" to generate a private key
// Also, use this private key to generate a public key using "openssl rsa -in privateKey.pem -pubout -out publicKey.pem"
// Convert PEM to JWKS and expose it on a public URL, and make a web3auth verifier using that.
// Check out https://web3auth.io/docs/auth-provider-setup/byo-jwt-provider/ for more details.
var privateKey = fs.readFileSync("privateKey.pem");

// Define the chain config according to the chain you want to connect to
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth",
displayName: "Ethereum Mainnet",
blockExplorerUrl: "https://etherscan.io",
ticker: "ETH",
tickerName: "Ethereum",
};

// Instantiate Ethereum Provider
const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });

// Instantiate Web3Auth SFA SDK
const web3authSfa = new Web3Auth({
clientId: "WEB3AUTH_CLIENT_ID", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // Replace with your network name
privateKeyProvider,
usePnPKey: false, // Setting this to true returns the same key as PnP Web SDK, By default, this SDK returns CoreKitKey.
});

// Initialize Web3Auth SFA SDK
await web3authSfa.init();

const user = {
id: "faj2720i2fdG7NsqznOKrthDvq43", // must be unique to each user
name: "Mohammad Shahbaz Alam",
email: "shahbaz@web3auth.io",
profileImage: "https://avatars.githubusercontent.com/u/46641595?v=4",
};

// Login the user
const web3authSfaprovider = await web3auth.connect({
verifier: "web3auth-sfa-verifier", // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId: user.id, // e.g. `Yux1873xnibdui` or `name@email.com` replace with your verifier id(sub or email)'s value.
idToken: jwt.sign(
{
sub: user.id, // must be unique to each user
name: user.name,
email: user.email,
picture: user.profileImage,
aud: "urn:my-resource-server", // -> to be used in Custom Authentication as JWT Field
iss: "https://my-authz-server", // -> to be used in Custom Authentication as JWT Field
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 60 * 60,
},
privateKey, // <-- privateKey to sign the JWT Token
{ algorithm: "RS256", keyid: "1bb9605c36e69386830202b2d" },
), // or replace it with your newly created unused JWT Token.
});

// Get the private key, The private key returned here is the CoreKit Key, since the usePnPKey is set to false.
const ethPrivateKey = await web3authSfaprovider.request({ method: "eth_private_key" });
const eth_accounts = await web3authSfaprovider.request({ method: "eth_accounts" });

console.log("ETH Private Key", ethPrivateKey);

Firebase JWT Example

Firebase JWT Example
import { Web3Auth, decodeToken } from "@web3auth/single-factor-auth";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import { GoogleAuthProvider, getAuth, signInWithPopup, UserCredential } from "firebase/auth";

// Define the chain config according to the chain you want to connect to
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth",
displayName: "Ethereum Mainnet",
blockExplorerUrl: "https://etherscan.io",
ticker: "ETH",
tickerName: "Ethereum",
};

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyB0nd9YsPLu-tpdCrsXn8wgsWVAiYEpQ_E",
authDomain: "web3auth-oauth-logins.firebaseapp.com",
projectId: "web3auth-oauth-logins",
storageBucket: "web3auth-oauth-logins.appspot.com",
messagingSenderId: "461819774167",
appId: "1:461819774167:web:e74addfb6cc88f3b5b9c92",
};

// Instantiate Ethereum Provider
const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });

// Instantiate Web3Auth SFA SDK
const web3authSfa = new Web3Auth({
clientId: "WEB3AUTH_CLIENT_ID", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // Replace with your network name
privateKeyProvider,
usePnPKey: false, // Setting this to true returns the same key as PnP Web SDK, By default, this SDK returns CoreKitKey.
});

// Initialize Web3Auth SFA SDK
await web3authSfa.init();

// Initialize Firebase and get idToken from Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
const res = await signInWithPopup(auth, googleProvider);
const idToken = await res.user.getIdToken(true);
// get sub value from firebase id token
const { payload } = decodeToken(token); // parseToken is a function that parses the token and returns the payload.

// Login the user
const web3authSfaprovider = await web3auth.connect({
verifier: "web3auth-sfa-verifier", // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId: (payload as any).sub, // e.g. `Yux1873xnibdui` or `name@email.com` replace with your verifier id(sub or email)'s value.
idToken: idToken, // or replace it with your newly created unused JWT Token.
});

// Get the private key, The private key returned here is the CoreKit Key, since the usePnPKey is set to false.
const ethPrivateKey = await web3authSfaprovider.request({ method: "eth_private_key" });
const eth_accounts = await web3authSfaprovider.request({ method: "eth_accounts" });

console.log("ETH Private Key", ethPrivateKey);