Skip to main content

Integrate Web3Auth with the Sui Blockchain

While using the Web3Auth Web SDK for a non-EVM chain like Sui you get a standard provider from which you can get the private key of the user. Using this private key, you can use the corresponding libraries of the blockchain to make blockchain calls like getting the user's public signing key, fetching balance, and sign & send transaction. We have highlighted a few methods here to get you started quickly on that.

Installation

For Sui, we will use the @mysten/sui.js library to create the Sui address, query the chain and submit transactions.

npm install --save @mysten/sui.js

Initializing Provider

Getting the chainConfig

const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.OTHER,
chainId: "35834a8a",
rpcTarget: "https://fullnode.mainnet.sui.io:443",
displayName: "Sui Mainnet",
blockExplorerUrl: "https://suiexplorer.com/",
ticker: "SUI",
tickerName: "Sui",
logo: "https://cryptologos.cc/logos/sui-sui-logo.png?v=029",
};

Initializing and instantiating the Web3Auth SDK

import { Web3Auth } from "@web3auth/modal";
import { CommonPrivateKeyProvider } from "@web3auth/base-provider";
import { WEB3AUTH_NETWORK } from "@web3auth/base";

const privateKeyProvider = new CommonPrivateKeyProvider({
config: { chainConfig: chainConfig }
});

const web3auth = new Web3Auth({
// Get it from Web3Auth Dashboard
clientId,
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
privateKeyProvider: privateKeyProvider,
});

Get User Info

After logging in, the Web3Auth instance will provide you with information regarding the user that is logged in. This information is obtained directly from the JWT token and is not stored by Web3Auth. Therefore, this information can only be accessed through social logins after the user has logged into your application.

const user = await web3auth.getUserInfo(); // web3auth instance

Get Account and KeyPair

Once a user logs in, the Web3Auth SDK returns a provider. Since Web3Auth doesn't have a native provider for Sui, we need to directly use the private key to create account.

Using the function, web3auth.provider.request({method: "private_key"}) from Web3Auth provider, the application can have access to the user's private key. However, Web3Auth does not provide direct access to Sui specific signing functions, hence, we create a new Ed25519Keypair to give SDK the ability to sign transactions with this key pair.

import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";

// web3authProvider is web3auth.provider from above
const privateKey = await web3authProvider.request({ method: "private_key" });

// Create a Uint8Arrray from private key which is in hex format
const privateKeyUint8Array = new Uint8Array(privateKey.match(/.{1,2}/g)!.map((byte: any) => parseInt(byte, 16)));

// Create an instance of the Sui local key pair manager
const keyPair = Ed25519Keypair.fromSecretKey(privateKeyUint8Array);

const address = keyPair.toSuiAddress();
console.log(`Sui account: ${address}`);

Get Balance

import { CoinBalance, getFullnodeUrl, SuiClient } from '@mysten/sui.js/client';
import { MIST_PER_SUI } from '@mysten/sui.js/utils';

// Use the getFullnodeUrl from SDK to get the RPC detils for the Sui network.
const rpcUrl = getFullnodeUrl('devnet');
const suiClient = new SuiClient({ url: this.rpcUrl });

// Use code from the above to retrive address here.
const balanceResponse = await this.suiClient.getBalance({owner: address});
const suiBalance = balance(balanceResponse);
console.log(`Sui Balance: ${suiBalance}`);


// Convert MIST to Sui
private balance = (balance: CoinBalance) => {
return Number.parseInt(balance.totalBalance) / Number(MIST_PER_SUI);
}

Send Transaction

import { TransactionBlock } from "@mysten/sui.js/transactions";
import { MIST_PER_SUI } from "@mysten/sui.js/utils";

// Use code from the above Initializing SuiClient and Ed25519Keypair here

const tx = new TransactionBlock();

// Convert value to be transferred to smallest value.
const [coin] = tx.splitCoins(tx.gas, [tx.pure(0.2 * Number(MIST_PER_SUI))]);
tx.transferObjects([coin], tx.pure("0x7d42ef777fa6e46a7b19d54dc9353c898e7f1c65a3abab8b73f92fe5efe6d96d"));

const result = await this.suiClient.signAndExecuteTransactionBlock({ signer: keyPair, transactionBlock: tx });
const transactionHash = result.digest;
console.log(`Transaction hash: ${transactionHash}`);