Web3Auth is a wallet infrastructure that is plugged into dApps or wallets. It serves as a pluggable authentication infrastructure for web3 wallets and applications. With Web3Auth's excellent user excellence, both mainstream and crypto natives may be onboarded in a matter of minutes.
As a wallet infrastructure, it provides out-of-the-box support for all social logins, web and mobile native platforms, wallets, and other key management methods. By the end of this guide, you will have integrated Web3Auth into your decentralized web application built on the Klaytn Network. To integrate Web3Auth into other platforms (Android, iOS, React Native, Flutter, & Unity), kindly refer to this guide.
Prerequisite
A working react project (by executing npx create-react-app project-name)
To make use of Web3Auth in your dApp, you must install the required libraries and SDK first. Hence, you'll need to set up ethers.js, and the Web3Auth Web SDK. You can use Web3Auth together with either ethers.js or web3.js libraries to communicate with the Klaytn blockchain. We'll be using ethers.js throughout this guide.
After successfully installing the needed libraries, next is to initialize the Web3Auth instance, set the Web3Auth provider instance in a useState() hook and also the init() function in a useEffect() hook.
import { Web3Auth } from"@web3auth/modal";import { ContractFactory, ethers } from"ethers";import { useState, useEffect } from"react";functionApp() {const [web3auth,setWeb3auth] =useState(null);const [provider,setProvider] =useState(null);useEffect(() => {constinit=async () => {try {constweb3auth=newWeb3Auth({ clientId:"YOUR_WEB3AUTH_CLIENT_ID",// get it from Web3Auth Dashboard web3AuthNetwork:"cyan", chainConfig: { chainNamespace:"eip155",// modify if mainnet => “0x2019” chainId:"0x3e9",// hex of 1001, Klaytn Baobab testnet. rpcTarget:"https://public-en-baobab.klaytn.net",// modify if mainnet displayName:"Klaytn Testnet",// modify if mainnet blockExplorer:"https://baobab.scope.klaytn.com/",// modify if mainnet ticker:"KLAY", tickerName:"KLAY", }, })setWeb3auth(web3auth);awaitweb3auth.initModal();setProvider(web3auth.provider); } catch (error) {console.error(error); } };init();}, []);
Connecting Wallet
Inside your App function in your App.js file, call the connect() method on the web3Auth instance to initiate the connection of your wallet.
In this guide, we will be making use of utils function: truncateAddress(). The truncateAddress() function takes in a valid address and returns a more readable format of the address passed in. The following steps below show how to set up and use the utils function in your project.
Step 1: Create a utils.js file in the src root folder.
Paste the following code in the newly created utils.js file.
Having connected your wallet successfully by calling the connect() method on the Web3Auth instance, you can get the user account and its balance by using the provider and signer object.
const [web3auth,setWeb3auth] =useState(null);const [provider,setProvider] =useState(null);const [address,setAddress] =useState("");const [balance,setBalance] =useState("");constconnectWallet=async() => {if (!web3auth) {console.log("web3auth not initialized yet");return; }constweb3authProvider=awaitweb3auth.connect();setProvider(web3authProvider);// this guide uses ethers version 6.3.0.constethersProvider=newethers.BrowserProvider(web3authProvider);// for ethers version below 6.3.0.// const provider = new ethers.providers.Web3Provider(web3authProvider);constethersProvider=newethers.BrowserProvider(web3authProvider);constsigner=awaitethersProvider.getSigner();// Get user's Ethereum public addressconstaddress=signer.address;// Get user's balance in etherconstbalance=ethers.formatEther(awaitethersProvider.getBalance(address) // balance is in wei );setAddress(address);setBalance(balance);return ( <divclassName="App"> <buttononClick={connectWallet}>Connect Wallet</button> <div>Wallet Address: ${truncateAddress(address)} Balance: ${balance}</div> </div> );}
Disconnecting Wallet
Disconnecting from the wallet is achieved by using the logout() method on the Web3Auth instance. Also, one good practice is to refresh the state to clear any previously stored connection data.
functionApp() {constdisconnect=async () => {if (!web3auth) {console.log("web3auth not initialized yet");return; }awaitweb3auth.logout();refreshState();}// refresh stateconstrefreshState= () => {setAddress();setBalance();// make sure to add every other useState modifier function declared here.}return ( <divclassName="App"> <buttononClick={disconnect}>Disconnect</button> </div> );}
Switching Chains
To switch chains using Web3Auth, you must firstly add the desired chain config to a connected adapter by calling the addChain() method, then proceed to calling the switchChain() method.
A unique feature of Web3Auth is social logins. Once a user login using their social platforms, Web3Auth instance returns some information about the logged in user. Getting the logged in user information is as simple as calling the getUserInfo() method on the Web3Auth instance.
// add to the existing useState hook.const [userData,setUserData] =useState({});constgetUserInfo=async () => {if (!web3auth) {console.log("web3auth not initialized yet");return; }constuser=awaitweb3auth.getUserInfo();setUserData(user);};return ( <divclassName="App"> <buttononClick={getUserInfo}>Get User Info</button> <div> { userData ?`User Email: ${userData.email}, User Name: ${userData.name}`:""} </div> </div> );
Signing Messages
Having initialised the provider and signer object, users can sign an arbitrary string.
// add to the existing useState hook.const [signedMessage,setSignedMessage] =useState("");constsignMessage=async(e) => {e.preventDefault();if (!provider) {console.log("provider not initialized yet");return; }// this guide uses ethers version 6.3.0.constethersProvider=newethers.BrowserProvider(provider);// for ethers version below 6.3.0.// const provider = new ethers.providers.Web3Provider(provider);constsigner=awaitethersProvider.getSigner();constoriginalMessage=e.target.message.value;constresult=awaitsigner.signMessage(originalMessage);setSignedMessage(result) }return ( <divclassName="App"> <formonSubmit={signMessage}> <inputtype="text"name="message"placeholder="Set message"required/> <inputtype="submit"value="Sign Message"/> </form> <div>SignedMessage: ${signedMessage}</div> </div> );
Sending Native Transaction
You can perform native transactions, like sending KLAY from one user to another.
// add to the existing useState hook.const [txHash,setTxHash] =useState();constsendKlay=async () => {if (!provider) {console.log("provider not initialized yet");return; }constdestination="paste recipient address";// this guide uses ethers version 6.3.0.constethersProvider=newethers.BrowserProvider(provider);// for ethers version below 6.3.0.// const provider = new ethers.providers.Web3Provider(provider);constsigner=awaitethersProvider.getSigner();// Submit transaction to the blockchain and wait for it to be minedconsttx=awaitsigner.sendTransaction({ to: destination, value:ethers.parseEther("0.1"), maxPriorityFeePerGas:"5000000000",// Max priority fee per gas maxFeePerGas:"6000000000000",// Max fee per gas })constreceipt=awaittx.wait();setTxHash(receipt.hash)}return ( <divclassName="App"> <buttononClick={sendKlay}>Send Klay</button> <div>Send-Klay Tx Hash : {txHash ? <ahref={`https://baobab.scope.klaytn.com/tx/${txHash}`} target="_blank">Klaytnscope</a> :' ' } </div> </div>);
Working with a Smart Contract
Deploying a Contract
You can deploy a smart contract given its Application Binary Interface(ABI) and its contract byte code.
// add to the existing useState hook.const [contractAddress,setContractAddress] =useState(null);constdeployContract=async () => {if (!provider) {console.log("provider not initialized yet");return; }// this guide uses ethers version 6.3.0.constethersProvider=newethers.BrowserProvider(provider);// for ethers version below 6.3.0.// const provider = new ethers.providers.Web3Provider(provider);constsigner=awaitethersProvider.getSigner();// paste your contractABIconstcontractABI= [ {"inputs": [ {"internalType":"uint256","name":"_initNum","type":"uint256" } ],"stateMutability":"nonpayable","type":"constructor" }, {"inputs": [],"name":"retrieve","outputs": [ {"internalType":"uint256","name":"","type":"uint256" } ],"stateMutability":"view","type":"function" }, {"inputs": [ {"internalType":"uint256","name":"num","type":"uint256" } ],"name":"store","outputs": [],"stateMutability":"nonpayable","type":"function" } ]// Paste your contract byte code const contractBytecode = '608060405234801561001057600080fd5b506040516102063803806102068339818101604052810190610032919061007a565b80600081905550506100a7565b600080fd5b6000819050919050565b61005781610044565b811461006257600080fd5b50565b6000815190506100748161004e565b92915050565b6000602082840312156100905761008f61003f565b5b600061009e84828501610065565b91505092915050565b610150806100b66000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100a1565b60405180910390f35b610073600480360381019061006e91906100ed565b61007e565b005b60008054905090565b8060008190555050565b6000819050919050565b61009b81610088565b82525050565b60006020820190506100b66000830184610092565b92915050565b600080fd5b6100ca81610088565b81146100d557600080fd5b50565b6000813590506100e7816100c1565b92915050565b600060208284031215610103576101026100bc565b5b6000610111848285016100d8565b9150509291505056fea26469706673582212200370e757ac1c15a024febfa9bf6999504ac6616672ad66bd654e87765f74813e64736f6c63430008120033'
constcontractFactory=newContractFactory(contractABI, contractBytecode, signer);constcontract=awaitcontractFactory.deploy(400);// get contract addresssetContractAddress(contract.target)}return ( <divclassName="App"> <buttononClick={deployContract}>Deploy Contract</button> <div>Contract Address: {contractAddress ? contractAddress :''} </div> </div> );
With the Web3Auth provider and signer object, you can make contract interactions such as writing to and reading from a smart contract deployed on the blockchain.
Writing to a Contract
// add to existing useState hookconst [contractTx,setContractTx] =useState();constwriteToContract=async (e) => {e.preventDefault();if (!provider) {console.log("provider not initialized yet");return; }// this guide uses ethers version 6.3.0.constethersProvider=newethers.BrowserProvider(provider);// for ethers version below 6.3.0.// const provider = new ethers.providers.Web3Provider(provider);constsigner=awaitethersProvider.getSigner();// Paste your contractABIconstcontractABI= [ {"inputs": [ {"internalType":"uint256","name":"_initNum","type":"uint256" } ],"stateMutability":"nonpayable","type":"constructor" }, {"inputs": [],"name":"retrieve","outputs": [ {"internalType":"uint256","name":"","type":"uint256" } ],"stateMutability":"view","type":"function" }, {"inputs": [ {"internalType":"uint256","name":"num","type":"uint256" } ],"name":"store","outputs": [],"stateMutability":"nonpayable","type":"function" } ]// Paste your contract addressconstcontractAddress="0x3b01E4025B428fFad9481a500BAc36396719092C";constcontract=newethers.Contract(contractAddress, contractABI, signer);constvalue=e.target.store_value.value;// Send a transaction to smart contract to update the valueconsttx=awaitcontract.store(value);// Wait for the transaction to finishconstreceipt=awaittx.wait();constresult=receipt.hash;setContractTx(result) }return ( <divclassName="App"> <formonSubmit={writeToContract}> <inputname="store_value"placeholder="Set contract value"required/> <inputtype="submit"value="Store"/> </form> <div>Write-to-contract Tx Hash: ${contractTx}</div> </div>);
Reading from a Contract
// add to existing useState hookconst [contractMessage,setContractMessage] =useState();constreadFromContract=async () => {if (!provider) {console.log("provider not initialized yet");return; }// this guide uses ethers version 6.3.0.constethersProvider=newethers.BrowserProvider(provider);// for ethers version below 6.3.0.// const provider = new ethers.providers.Web3Provider(provider);// paste your contract ABIconstcontractABI= [ {"inputs": [ {"internalType":"uint256","name":"_initNum","type":"uint256" } ],"stateMutability":"nonpayable","type":"constructor" }, {"inputs": [],"name":"retrieve","outputs": [ {"internalType":"uint256","name":"","type":"uint256" } ],"stateMutability":"view","type":"function" }, {"inputs": [ {"internalType":"uint256","name":"num","type":"uint256" } ],"name":"store","outputs": [],"stateMutability":"nonpayable","type":"function" } ]// paste your contract addressconstcontractAddress="0x3b01E4025B428fFad9481a500BAc36396719092C"; constcontract=newethers.Contract(contractAddress, contractABI, ethersProvider)// Reading a message from the smart contractconstcontractMessage=awaitcontract.retrieve();setContractMessage(contractMessage.toString()) }return ( <buttononClick={readFromContract}>Read From Contract</button> <div>Read-from-contract Message: ${contractMessage}</div> )
TroubleShooting
Polyfill node core module error
BREAKING CHANGES: webpack<5 used to include polyfills for node.js core modules by default.
This error occurs when you use webpack version 5. In this version, NodeJS polyfills is no longer supported by default. To solve this issue, refer to this guide.
Next Step
For more in-depth guides on Web3Auth, please refer to the Web3Auth Docs and Web3Auth Github repository. Also, you can find the full implementation of the code for this guide on GitHub.