Skip to main content

Using tKey JS SDK

Once you've installed all packages, instantiated tKey and initialized the service provider instance in your constructor, you can use it to authenticate your users and generate their tKey shares. Further, you can use a variety of functions exposed by the tKey SDK and its modules to manage different aspects of your users' authentication needs.

We'll be talking in-depth about the following operations:

ThresholdKey

Natively, the instance of tKey, (ie. ThresholdKey) returns many functions, however, we have documented a few relevant ones here. You can check the table below for a list of all relevant functions, or the class reference to checkout the full list of functions.

FunctionDescriptionArgumentsReturn
initializeGenerates a Threshold Key corresponding to your login provider.paramsKeyDetails
reconstructKeyReconstructs the user private key. Can only work if the minimum threshold of keys has reached_reconstructKeyMiddleware?: booleanReconstructedKeyResult
deleteShareDelete a share details from metadata. The corresponding share won't be valid anymore.shareIndex: BNStringDeleteShareResult
getKeyDetailsGet the details of the keys present for the particular user.voidKeyDetails
generateNewShareGenerate a new share for the reconstructed private key.voidGenerateNewShareResult
inputShareStoreSafeInput a share store into the tKeyshareStore: ShareStore, autoUpdateMetadata?: booleanvoid
outputShareStoreOutput a share store from the tKeyshareIndex: BNString, polyID?: stringShareStore
addShareDescriptionAdd a description to a shareshareIndex: string, description: string, updateMetadata?: booleanvoid
deleteShareDescriptionDelete a description from a shareshareIndex: string, description: string, updateMetadata?: booleanvoid
updateShareDescriptionUpdate a description from a shareshareIndex: string, oldDescription: string, newDescription: string, updateMetadata?: booleanvoid
outputShareOutput a shareshareIndex: BNString, type?: stringunknown
inputShareInput a shareshare: unknown, type?: stringvoid
toJSONConvert the tKey to JSONvoidStringifiedType

Log In

The login with the tKey SDK is a 3-step process.

  1. Login using your desired login provider and get their OAuth Id Token
  2. Use the OAuth ID Token to connect to the Web3Auth Service Provider to generate the OAuth Key
  3. Once the OAuth Key is generated, initialize the tKey Instance

However, before starting this process, you need to set up Custom Authentication on your Web3Auth Dashboard. For this, you need to Create a Verifier within the Web3Auth Developer Dashboard with your desired configuration.

tip

If you want to know more about setting up a verifier and how to use it, please refer to the Auth Provider Setup Documentation.

Login using OAuth

You can choose any OAuth Provider of your choice and login using their standard process. You can check out our examples where we have used the most common OAuth providers like Google, Auth0, Firebase etc. Additionally, you can checkout our documentation around OAuth Provider setup here.

Implicit Auth Flow

If you prefer using an implicit login method with your OAuth Provider, you can do so by using the TorusServiceProvider. You can check out the additional reading section for more information. This provider doesn't work in a React Native environment.

Generating OAuth Key

This setup helps you generate a private key which will be needed by the tKey Instance to generate the OAuth Share. This is done by calling the connect() function within the tKey instance's serviceProvider.

tKeyInstance.serviceProvider.connect(params: LoginParams): Promise<BN>;

LoginParams

ParameterDescription
verifierDetails of the verifier (verifier type, ie. torus, metamask, openlogin etc.). 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.

Usage

const OAuthShareKey = await(tKeyInstance.serviceProvider as SfaServiceProvider).connect({
verifier,
verifierId,
idToken,
});

Initializing tKey

tKey.initialize(params?)

Once you have triggered the login process, you're ready to initialize the tKey. This will generate a Threshold Key corresponding to your login provider.

Parameters

params

The initialize function accepts the following optional parameters:

ParameterTypeDescriptionMandatory
withShare?ShareStoreInitialize tkey with an existing share store. This allows you to directly initialize tKey without using the service provider login.No
importKey?BNImport a key into tkey for initialisation.No
neverInitializeNewKey?booleanNever initialize using a new key if the shares are already formedNo
transitionMetadata?MetadataIf we've been provided with transition metadata we use that as the current metadata instead as we want to maintain state before and after serialization.No
previouslyFetchedCloudMetadata?MetadataPass the previous cloud metadataNo
previousLocalMetadataTransitions?LocalMetadataTransitionsPass the previous transition metadataNo

Example

import { decode as atob } from "base-64";

const loginRes = await signInWithEmailPassword(); // Logging in via email and password
const idToken = await loginRes!.user.getIdToken(true); // Getting ID Token from the Login Provider
const parsedToken = parseToken(idToken); // Parsing the ID Token

// function to Parse Id Token
const parseToken = (token: any) => {
try {
const base64Url = token.split(".")[1];
const base64 = base64Url.replace("-", "+").replace("_", "/");
return JSON.parse(atob(base64 || ""));
} catch (err) {
console.log(err);
return null;
}
};

console.log("User Information:", parsedToken);

// Connecting to the service provider
const verifier = "web3auth-firebase-examples";
const verifierId = parsedToken.sub;
const OAuthShareKey = await (tKeyInstance.serviceProvider as SfaServiceProvider).connect({
verifier,
verifierId,
idToken,
});

console.log("OAuth Share:", OAuthShareKey);

await tKeyInstance.initialize();

Get tKey Details

tKey.getKeyDetails()

The function getKeyDetails() returns the details of the keys present generated for the specific user. This includes the public key X & Y of the user, alongside the shares details and the threshold.

Sample Key Details Return

[
{
pubKey: {
x: "eb83edf410ac3cb479ccaa281f96d94e6188a746442be0f727cc72b596a1d17",
y: "12625b4139805d0ae570a923a83b8a022aa06941aca3ace0bb538ffabeaf4242",
},
requiredShares: -4,
threshold: 2,
totalShares: 6,
shareDescriptions: {
e8c4eb2197e06dd34f1b33ee58b496e7f6c7f9ebe929d5b63bde4db407e8c1f0: [
'{"module":"webStorage","userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36","dateAdded":1692014296326}',
],
e1587941cbd1fe967387794f9fa026c9229fd2945386846a66aff41f6ecfefb3: [
'{"module":"securityQuestions","questions":"whats your password?","dateAdded":1692014335216}',
],
},
},
];

From here, you can know whether the user key can be reconstructed or not.

  • If the requiredShares is greater than 0, then the key cannot be reconstructed, because this means that the user has not yet generated enough shares to meet the threshold.
  • Once the requiredShares is 0 or less than that, then the key can be reconstructed, and the user can use the shares to generate the private key and make further operations on the tKey and manipulate their keys.
Example
const { requiredShares } = tKey.getKeyDetails();
if (requiredShares <= 0) {
console.log("All shares are present, you can reconstruct your private key and do operations on the tKey");
} else {
console.log("You need to generate more shares to reconstruct your private key");
}

Reconstruct Private Key

tKey.reconstructKey()

The function reconstructKey() reconstructs the private key of the user from the shares generated. This function returns the private key of the user once the threshold has been met.

reconstructKey(_reconstructKeyMiddleware?: boolean): Promise<ReconstructedKeyResult>;

export type ReconstructedKeyResult = {
privKey: BN;
seedPhrase?: BN[];
allKeys?: BN[];
};
Example
const { requiredShares } = tKey.getKeyDetails();
if (requiredShares <= 0) {
const reconstructedKeyResult = await tKey.reconstructKey();
const privateKey = reconstructedKeyResult?.privKey.toString("hex"));
console.log("Private Key: ", privateKey);
}

Generate a New Share

tKey.generateNewShare()

The function generateNewShare() generates a new share on the same threshold set by the user. This function returns the new share generated.

generateNewShare(): Promise<GenerateNewShareResult>;

export type GenerateNewShareResult = {
newShareStores: ShareStoreMap;
newShareIndex: BN;
};
Example
const shareStore = await tKey.generateNewShare();
await(tKey.modules.webStorage as WebStorageModule).storeDeviceShare(shareStore.newShareStores[1]);
console.log("New Share Stored on the Browser Local Storage: ", shareStore.newShareIndex.toString());

Delete a Share

tKey.deleteShare(shareIndex: BNString)

The function deleteShare() deletes a share from the user's shares. This function returns the updated shareStore after the share has been deleted.

deleteShare(shareIndex: BNString): Promise<DeleteShareResult>;

export type DeleteShareResult = {
newShareStores: ShareStoreMap;
};
Example
const shareStore = await tKey.deleteShare(previousShareIndex);
console.log("Share has been deleted", shareStore);

Using Modules

For making advanced operations on tKey and to manipulate the keys, you can use the modules provided by tKey. As mentioned in the initialisation section, you need to configure the modules beforehand to make it work with tKey. Once that is done, the instance of the respective module is available within your tKey instance and can be used for further operations.

tip

Checkout the Modules section where we have listed all the available modules alongside the functions that can be used within them.

Making Blockchain Calls

Once you have generated the private key, you can use it to make blockchain calls. The key generated by tKey is of type secp256k1, which is compatible with EVM-based blockchains like Ethereum, Polygon, and many others that use the same curve. However, you can also convert this key into other curves and utilize it. For example, we have a dedicated package for converting this module to the ed25519 curve for usage in Solana and other blockchains that use this curve.

In addition to that, we have dedicated provider packages for EVM, Solana and XRPL libraries. You can check out their respective documentation in the Providers Section.

tip

You can checkout our Connect Blockchain documentation which has a detailed guide on how to connect to major blockchains out there.