Usage of MPC Core Kit JS SDK
Once you've installed and successfully initialized Web3AuthMPCCoreKit
, you can use it to
authenticate your users. Further, you can use the native provider given by Web3Auth to sign
transactions and interact with the blockchain.
Natively, the instance of Web3AuthMPCCoreKit
(referred to as coreKitInstance
in our examples)
returns the following functions:
loginWithOAuth()
- Logs in the user using OAuth Flow.loginWithJWT()
- Logs in the user with a JWT-based ID Token.handleRedirectResult()
- Handles the redirect result from the OAuth Flow.inputFactorKey()
- Inputs the Factor Key to recover the user's account in case they don't have enough factors.logout()
- Logs out the User.
Check out the Authentication section of the SDK Reference to learn more about these functions.
-
commitChanges()
- Commits the changes made to the user's account while in manual sync mode.To use this function, you'll need to configure the manual sync in the initialization step.
We recommend using the Manual Sync Mode to handle the factors and keys of the user's account. This enables you to have a fined grained control over the API calls made to the metadata server from the SDK.
This is especially useful when you want to handle the factors and keys of the user's account in a more controlled manner, enabling a much faster and safer experience for the User.
During manual sync mode, you need to call the commitChanges()
function to sync the local metadata
to the web3auth metadata server. This helps you to keep the user's account in sync with the metadata
server, after they have successfully configured everything in the local.
account, present in the state of the SDK.
enableMFA()
- Enable MFA for the user. Deletes the Hashed Factor and generates a new Factor Key.createFactor()
- Creates a new Factor for the user's account to increase the factors of your account. It can be of type Device(index:2
) or Recovery(index:3
).deleteFactor()
- Deletes a Factor from the user's account.getCurrentFactorKey()
- Returns the current Factor Key of the user'sgetDeviceFactor()
- Returns the user's device factor if available.
You shouldn't create too many factors, we recommend a maximum of 10 factors.
User & Wallet Account Functions:
setTssWalletIndex()
- Sets the TSS Wallet Index for the user's account.getPubKey()
- Returns the SEC1 Public Address of the user in a Synchronous call.getPubKeyEd25519()
- Returns the Public Address of the user in a Synchronous call.getUserInfo()
- Returns the user's information received from the ID Token.getKeyDetails()
- Returns the user's Key Details.
- Security Questions
setSecurityQuestion()
- Sets the Security Question Factor for the user's account.changeSecurityQuestion()
- Changes the Security Question for the user's account.deleteSecurityQuestion()
- Deletes the Security Question for the user's account.recoverFactor()
- Recovers the Security Question Factor for the user's account using the given password.getQuestion()
- Returns the Security Question for the user's account.
- Conversion from Mnemonic
mnemonicToKey()
- Converts a Mnemonic to a BN.keyToMnemonic()
- Converts a hex string to a Mnemonic.
Authentication Functions
Login with OAuth
loginWithOAuth()
- Logs in the user using OAuth flow.
Login with JWT
loginWithJWT()
- Logs in the user with a JWT-based ID Token.
Handle Redirect Result
handleRedirectResult()
- Handles the redirect result from the OAuth Flow.
Input Factor Key
inputFactorKey(factorKey: BN): Promise<void>;
Inputs the Factor Key into the SDK. This function is used to recover the user's account using the Factor Key. If the factor key is correct, the SDK initializes the user's account and logs them in.
If you want to change the factor key in the current state of the SDK, you can use this function.
Usage
const factorKey = new BN(backupFactorKey, "hex");
await coreKitInstance.inputFactorKey(factorKey);
Logout
logout(): Promise<void>;
Logs out the User from the application and clears the local storage.
logout()
- Logs out the User.
Manual Sync Function
Commit Changes
commitChanges(): Promise<void>;
Syncs the local metadata with the web3auth metadata server. This function is only to be used while in manual sync mode.
Usage
await coreKitInstance?.commitChanges();
Factor Handling Functions
Enable MFA
enableMFA(enableMFAParams: EnableMFAParams): Promise<string>;
Enables MFA for the user. It creates a device factor and stores it in the local storage. It also creates a backup factor and returns it to the user. You can also pass a factor key that can be used for the backup factor. If you don't pass a factor key, a new factor key will be generated.
Most importantly, this function deletes the Hashed Factor Key enabling a non-custodial flow.
Parameters
export interface EnableMFAParams {
/**
* A BN used for encrypting your Device/ Recovery TSS Key Share. You can generate it using `generateFactorKey()` function or use an existing one.
*/
factorKey?: BN;
/**
* Setting the Description of Share - Security Questions, Device Share, Seed Phrase, Password Share, Social Share, Other. Default is Other.
*/
shareDescription?: FactorKeyTypeShareDescription;
/**
* Additional metadata information you want to be stored alongside this factor for easy identification.
*/
additionalMetadata?: Record<string, string>;
}
export enum FactorKeyTypeShareDescription {
HashedShare = "hashedShare",
SecurityQuestions = "tssSecurityQuestions",
DeviceShare = "deviceShare",
SeedPhrase = "seedPhrase",
PasswordShare = "passwordShare",
SocialShare = "socialShare",
Other = "Other",
}
Usage
const factorKey = await coreKitInstance.enableMFA({});
const factorKeyMnemonic = keyToMnemonic(factorKey);
uiConsole(
"MFA enabled, device factor stored in local store, deleted hashed cloud key, your backup factor key: ",
factorKeyMnemonic,
);
Create Factor
A low-level function, helps you to create a backup factor key based on the type of TSS Share you want to create. You can pass your own factor key or let the SDK generate one for you.
Parameters
export interface CreateFactorParams extends EnableMFAParams {
/**
* Setting the Type of Share - Device or Recovery.
**/
shareType: TssShareType;
}
export enum TssShareType {
DEVICE = 2,
RECOVERY = 3,
}
export interface EnableMFAParams {
/**
* A BN used for encrypting your Device/ Recovery TSS Key Share. You can generate it using `generateFactorKey()` function or use an existing one.
*/
factorKey?: BN;
/**
* Setting the Description of Share - Security Questions, Device Share, Seed Phrase, Password Share, Social Share, Other. Default is Other.
*/
shareDescription?: FactorKeyTypeShareDescription;
/**
* Additional metadata information you want to be stored alongside this factor for easy identification.
*/
additionalMetadata?: Record<string, string>;
}
export enum FactorKeyTypeShareDescription {
HashedShare = "hashedShare",
SecurityQuestions = "tssSecurityQuestions",
DeviceShare = "deviceShare",
SeedPhrase = "seedPhrase",
PasswordShare = "passwordShare",
SocialShare = "socialShare",
Other = "Other",
}
Usage
const factorKey = generateFactorKey();
await coreKitInstance.createFactor({
shareType: exportTssShareType,
factorKey: factorKey.private,
});
Delete Factor
deleteFactor(factorPub: TkeyPoint): Promise<void>;
Deletes the Factor, respective to the factorPub provided for the user's account. You can get the
factor Pubs by using the getKeyDetails()
function.
It will throw an error if you try to delete the factor that is currently active within the state of
the SDK. Use the inputFactorKey()
function to change the factor key in the current state of the
SDK to be able to delete that factor.
Usage
const pubBuffer = Buffer.from(factorPubToDelete, "hex");
const pub = Point.fromBufferSEC1(pubBuffer);
await coreKitInstance.deleteFactor(pub.toTkeyPoint());
Get Current Factor Key
getCurrentFactorKey(): IFactorKey;
Returns the current factor key in usage within the state of the SDK.
Usage
const factorKey = coreKitInstance.getCurrentFactorKey();
Get Device Factor
getDeviceFactor(): Promise<string | undefined>
Returns the user's device factor if available.
Usage
const factorKey = await coreKitInstance!.getDeviceFactor();
User & Wallet Account Functions
Set TSS Wallet Index
setTssWalletIndex(accountIndex: number): void;
Sets the TSS Wallet Index for the user's account. This function can be used to deterministically derive different wallet addresses by using account indexes. Using this function you can add multi-address account support to your application.
As an application, you need to persist this account index in the application state.
You can either choose to persist the account index temporarily using the state variable or use a
more permanent storage like localStorage
. Whenever you add, delete or update a share, you need to
set the account index again.
Please note, the function is only supported for secp256k1 KeyType.
Usage
await coreKitInstance.setTssWalletIndex(index);
Get SEC1 Public Key
getPubKey()
This function returns the final secp256k1 public key of the user in a synchronous call.
When you use the setTssWalletIndex()
function to establish your account index, a unique public key
is generated! Remember that each account index you set will result in a different public key.
Usage
const pubKey = coreKitInstance.getPubKey();
Get ed25519 Public Key
getPubKeyEd25519()
This function returns the final ed25519 public key of the user in a synchronous call.
When you use the setTssWalletIndex()
function is only supported for secp256k1 key type.
Usage
const pubKey = coreKitInstance.getPubKeyEd25519();
Get User Info
getUserInfo(): UserInfo;
Gives you the user's information received from the ID Token.
Returns
export type UserInfo = TorusVerifierResponse & LoginWindowResponse;
export interface TorusVerifierResponse {
email: string;
name: string;
profileImage: string;
aggregateVerifier?: string;
verifier: string;
verifierId: string;
typeOfLogin: LOGIN_TYPE;
ref?: string;
registerOnly?: boolean;
extraVerifierParams?: WebAuthnExtraParams;
}
export interface LoginWindowResponse {
accessToken: string;
idToken?: string;
ref?: string;
extraParams?: string;
extraParamsPassed?: string;
state: TorusGenericObject;
}
Usage
const user = coreKitInstance?.getUserInfo();
Get Key Details
getKeyDetails(): MPCKeyDetails;
Gives you the details of the keys and factors held by the user's account.
Returns
export type MPCKeyDetails = {
metadataPubKey: TkeyPoint;
threshold: number;
requiredFactors: number;
totalFactors: number;
shareDescriptions: ShareDescriptionMap;
tssPubKey?: TkeyPoint;
};
export type ShareDescriptionMap = {
[shareIndexStr: string]: string[];
};
Usage
const keyDetails = coreKitInstance?.getKeyDetails();
Additional Helper Functions
Security Question
Set Security Question
setSecurityQuestion(params: setSecurityQuestionParams): Promise<string>
Parameters
export interface setSecurityQuestionParams {
mpcCoreKit: Web3AuthMPCCoreKit;
question: string;
answer: string;
shareType?: TssShareType;
description?: Record<string, string>;
tssIndex?: TssShareType;
}
export enum TssShareType {
DEVICE = 2,
RECOVERY = 3,
}
Creates a security question share for your to easily recover user's account.
Usage
import { TssSecurityQuestion } from "@web3auth/mpc-core-kit";
const securityQuestion: TssSecurityQuestion = new TssSecurityQuestion();
await securityQuestion.setSecurityQuestion({
mpcCoreKit: coreKitInstance,
question,
answer,
shareType: TssShareType.RECOVERY,
});
Change Security Question
changeSecurityQuestion(params: changeSecurityQuestionParams): Promise<void>;
Parameters
export interface changeSecurityQuestionParams {
mpcCoreKit: Web3AuthMPCCoreKit;
newQuestion: string;
newAnswer: string;
answer: string;
}
Changes the Security Question Share of the user's account. This helps you change the password if the user has lost it somehow. However, this function can only be used if the user has already logged in within the application while meeting the minimum share threshold.
Usage
import { TssSecurityQuestion } from "@web3auth/mpc-core-kit";
const securityQuestion: TssSecurityQuestion = new TssSecurityQuestion();
await securityQuestion.changeSecurityQuestion({
mpcCoreKit: coreKitInstance,
newQuestion,
newAnswer,
answer,
});
Delete Security Question Share
deleteSecurityQuestion(mpcCoreKit: Web3AuthMPCCoreKit, deleteFactorKey?: boolean): Promise<void>;
Deletes the Security Question Share of the user's account. This function can only be used if the user has already logged in within the application while meeting the minimum share threshold.
Usage
import { TssSecurityQuestion } from "@web3auth/mpc-core-kit";
const securityQuestion: TssSecurityQuestion = new TssSecurityQuestion();
await securityQuestion.deleteSecurityQuestion(coreKitInstance);
Get Factor Key from Security Question
recoverFactor(mpcCoreKit: Web3AuthMPCCoreKit, answer: string): Promise<string>
Returns the Factor Key stored against the security question share.
Usage
import { TssSecurityQuestion } from "@web3auth/mpc-core-kit";
const securityQuestion: TssSecurityQuestion = new TssSecurityQuestion();
const factorKey = await securityQuestion.recoverFactor(coreKitInstance, answer);
Get Security Question for user's Account
getQuestion(mpcCoreKit: Web3AuthMPCCoreKit): string;
Get the security question for the user's account.
Usage
const question = securityQuestion.getQuestion(coreKitInstance!);
Mnemonic Conversations
Mnemonic to Key
mnemonicToKey(shareMnemonic: string): string
Converts a Mnemonic to a BN.
const factorKeyBN = mnemonicToKey(factorKeyMnemonic);
Key to Mnemonic
keyToMnemonic(shareHex: string): string
Converts a factor key hex string to a Mnemonic.
Usage
const factorKeyMnemonic = keyToMnemonic(factorKeyHex);