Find out how to Combine the WalletConnect Modal and QR Code


On this article, we’ll use NextJS and Moralis’ Web3 Auth API to combine the WalletConnect modal and QR code. Because of following together with the steps on this article, you’ll be able to have the next authentication sequence operating in your dapp:

For these already conversant in NextJS and Moralis’ API, be at liberty to entry the documentation web page to get began instantly. With that stated, if you happen to’d like a free tutorial guiding you thru the method and studying the way to combine the WalletConnect QR code modal, learn on!

Overview

From a consumer perspective, it’s extraordinarily handy when a web site or app supplies the flexibility to log in utilizing a easy scan of a QR code. As such comfort attracts many customers, it’s not shocking to see a rise in websites and apps integrating QR code performance. Moreover, such a authentication is not only fashionable for conventional apps but in addition for decentralized functions (dapps). So as to add such a Web3 authentication to your dapps, it’s best to concentrate on WalletConnect. Fortuitously, that’s precisely what this text focuses on. Extra particularly, this text explores the way to combine the WalletConnect modal and QR code!

Transferring ahead, you’ll have an opportunity to observe our lead and create a easy dapp utilizing NextJS and Moralis. In spite of everything, it’s the Moralis Web3 Auth API that allows you to combine the WalletConnect modal into any dapp with out breaking a sweat. Whereas we are going to concentrate on utilizing the NextJS framework herein, it’s price mentioning that Moralis is absolutely cross-platform interoperable. As such, you’ll be able to create dapps with the WalletConnect QR code modal utilizing a variety of legacy dev platforms and programming languages. Accordingly, Moralis helps bridge the event hole between Web2 and Web3. Other than the last word Web3 Auth API, Moralis presents the perfect EVM and Solana APIs. These embrace the NFT API, Token API, and Streams API. What’s extra, you should use these glorious instruments on all main blockchain networks.

Nonetheless, earlier than we present you the way to construct a easy NextJS dapp that features the WalletConnect modal, we have to get you all in control. As such, we’ll first discover WalletConnect’s open-source protocol and take a look at what it’s used for. That stated, ensure to prepare for the action-taking a part of in the present day’s article by creating your free Moralis account now.     

Connecting Web3 Design Art

Exploring WalletConnect’s Open-Supply Protocol

You’ll be able to nonetheless hear individuals say that WalletConnect is a crypto pockets. Nonetheless, that’s not fully correct. WalletConnect is an open-source protocol that establishes safe connections between crypto wallets and decentralized functions (dapps). This open-source protocol makes use of symmetric encryption by way of a shared key between two friends, which makes it one of many most secure strategies of Web3 authentication. 

You may as well consider WalletConnect as a decentralized Web3 messaging layer and a normal for connecting blockchain wallets to dapps. As well as, it’s price mentioning that WalletConnect’s group strives to repeatedly increase this protocol’s interoperability. Therefore, we will anticipate top quality and reliability from WalletConnect shifting ahead. As a dapp developer, you don’t need to overlook the vital infrastructure for Web3 wallets and dapps that WalletConnect helps. It achieves that by guaranteeing that the next core ideas are accurately carried out:

Chain Agnostic – WalletConnect believes within the multi-chain way forward for the crypto area. As such, the WalletConnect group focuses on supporting all of the main chains. These embrace Ethereum, Solana, and lots of others. To make sure a chain-agnostic method, WalletConnect is dedicated to repeatedly including help for rising respected chains.  Multi-Chain – WalletConnect’s customers can join any of the supported wallets to a number of chains on the similar time.Platform Agnostic – Along with supporting totally different chains, WalletConnect additionally helps totally different platforms. Therefore, the WalletConnect modal serves internet, desktop, cellular, and gaming dapps.

1 - Pick WalletConnect. 2 - Scan QR code with compatible wallet. 3 - Click connect via your wallet.

What’s WalletConnect Used For?

The above clarification ought to make clear that the WalletConnect modal establishes protected connections between Web3 wallets and dapps. As such, let’s discover what this course of appears to be like like. For starters, it’s price mentioning that WalletConnect offers customers two methods to determine the connection. On the one hand, customers can do this by scanning a QR code with their cellular Web3 wallets – that is the extra user-friendly methodology and is obtainable by default. Alternatively, customers may use a deep hyperlink, which is especially helpful for customers that wouldn’t have cellular wallets to scan the code. 

Nonetheless, each strategies let one peer (a dapp) ship out a code or hyperlink. Then, it’s as much as the opposite peer (a crypto pockets) to scan or approve the connection. Through this methodology, dapps that embrace the WalletConnect modal and QR code allow customers to simply set up protected and dependable Web3 connections. 

Moreover, WalletConnect’s spectacular vary of supported wallets makes this protocol extraordinarily sensible. In spite of everything, it’s virtually inconceivable to seek out unsupported wallets. Furthermore, the official WalletConnect web site presently states that their resolution works with greater than 170 crypto wallets. In case you need to discover what Web3 wallets WalletConnect helps, go to WalletConnect’s official web site, scroll right down to the “In search of a pockets?” part, and click on on the “VIEW ALL WALLETS” button: 

User clicking on view all wallets on WalletConnect's homepage.

The above button will take you to the “Discover” web page. There, you’ll be capable of see all of the supported wallets:

Showcasing all supported wallets.

It’s price mentioning that there are sixteen pages (fifteen full pages) with fifteen wallets per web page (see the screenshot above). So, if we do basic math, it’s evident that WalletConnect already helps over 225 Web3 wallets. 

WalletConnect Modal – Find out how to Combine the WalletConnect QR Code Modal

With the fundamentals below your belt, it’s time to construct a easy dapp with the WalletConnect QR code modal. Should you keep in mind, we’ll be utilizing NextJS and Moralis to finish in the present day’s feat. Therefore, the facility of Moralis’ Auth API makes integrating the WalletConnect modal as easy because it will get. Transferring on, we’ll take you thru all of the steps you want to full to finish up with a easy dapp in your native server. 

A wizard pointing at text that says how to integrate the walletconnect modal and qr code.

Additionally, we’ll offer you all of the traces of code. As such, you’ll be capable of merely copy and paste the content material to your situations of the required scripts. Right here’s the record of the information you’ll get to create if you happen to determine to finish in the present day’s problem:

“.env.native“ – On this file, you’ll retailer all of the native variables, together with your Moralis Web3 API key.“_app.jsx“ – You’ll use this file to wrap your app with “WagmiConfig” and “SessionProvider”.“request-message.js“ – This file will function an endpoint for making requests to generate a novel message.“signin.jsx“ – You’ll use this file to create the “signin” web page. As such, this file will include the connector that may allow customers to authenticate themselves with the WalletConnect QR code modal.“[…nextauth].js“ – That is the file that you just’ll use to configure NextAuth.“consumer.jsx“ – You’ll use this file to create the “consumer” web page that the efficiently authenticated customers will land on. For the sake of this tutorial, it’s going to include some primary consumer data. 

Nonetheless, earlier than you get your palms soiled, we additionally need to make sure that you understand precisely what you’ll be constructing. As such, let’s do a fast demo of our instance dapp.

Our Instance NextJS Dapp Demo

The next screenshot reveals the gist of the “signing” web page on the shopper facet:

Blank page with a authenticate via walletconnect qr code button.

As you’ll be able to see, there may be the “Web3 Authentication” title and the “Authenticate by way of WalletConnect” button. Therefore, it’s very intuitive for customers to click on on the button that may set off the WalletConnect modal:

The qr code modal prompt box.

Utilizing their cellular wallets, customers get to scan the above QR code and make sure their authentication on the cellular units:

User clicking on connect and confirm.

The above picture reveals the affirmation on Belief Pockets; nevertheless, the method is comparable for different crypto wallets.

Lastly, as soon as customers join their pockets to our dapp, they land on the “consumer” web page. The latter shows some primary knowledge associated to the linked profile:

Looking at the user page.

Getting Began – Conditions and the Preliminary Setup for Your NextJS Dapp

Earlier than finishing the preliminary setups, ensure to get the next prepared:

Create your Moralis account.Set up and arrange Visible Studio Code (VSC).Create a NextJS utility. Use the “Create Subsequent App” web page within the NextJS docs or full our “Utilizing NextJS” tutorial if you happen to need assistance with that step. 

With the above stipulations below your belt, you’re prepared to put in the required dependencies. So, you should use one of many following instructions (relying in your bundle supervisor) to put in Moralis, NextAuth, and Axios:

npm set up moralis next-auth axiosyarn add moralis next-auth axiospnpm add moralis next-auth axios

Furthermore, you additionally want to put in the wagmi Web3 library utilizing one of many following instructions:

npm set up wagmi ethersyarn add wagmi etherspnpm add wagmi ethers

Subsequent, create a “.env.native” file in your app’s root and populate it with the required atmosphere variables:

“APP_DOMAIN” – An RFC 4501 DNS authority that’s requesting the signing.“MORALIS_API_KEY” – Your gateway to utilizing Moralis.You’ll be able to acquire the API key inside your Moralis admin space:

Web3 API page on the moralis admin panel.

“NEXTAUTH_URL” – Your app deal with. Within the growth stage, you need to use “http://localhost:3000” or related.“NEXTAUTH_SECRET” – A variable that may encrypt the JWT tokens of customers. Chances are you’ll use any worth right here or generate one at “https://generate-secret.now.sh/32“. 

Nonetheless, check out this instance that may show you how to higher perceive the above atmosphere variables:

Outlining environment variables.

Observe: Needless to say you want to restart your dapp everytime you modify your “.env.native” file.

Override the NextJS “App” Part

NextJS makes use of the “App” part to initialize pages, which you’ll be able to override to take management of the web page initialization. To do that, wrap your pages with “WagmiConfig” and “SessionProvider“. Therefore, create the “_app.jsx” file contained in the “pages” folder. Then, use the next traces of code to populate that file:

import { createClient, configureChains, defaultChains, WagmiConfig } from ‘wagmi’;
import { publicProvider } from ‘wagmi/suppliers/public’;
import { SessionProvider } from ‘next-auth/react’;

const { supplier, webSocketProvider } = configureChains(defaultChains, [publicProvider()]);

const shopper = createClient({
supplier,
webSocketProvider,
autoConnect: true,
});

operate MyApp({ Part, pageProps }) {
return (
<WagmiConfig shopper={shopper}>
<SessionProvider session={pageProps.session} refetchInterval={0}>
<Part {…pageProps} />
</SessionProvider>
</WagmiConfig>
);
}

export default MyApp;

Create the “requestMessage” Endpoint

Begin this step by creating a brand new API file and calling it “request-message.js”. Be certain to create that file contained in the “auth” folder. The latter ought to be inside “pages/api”. Moreover, this endpoint will make requests to “Moralis.Auth” to generate a novel message. In a while, you’ll must signal that message on the shopper facet. Beneath are the traces of code that you want to copy-paste into “request-message.js”:

import Moralis from ‘moralis’;

const config = {
area: course of.env.APP_DOMAIN,
assertion: ‘Please signal this message to substantiate your identification.’,
uri: course of.env.NEXTAUTH_URL,
timeout: 60,
};

export default async operate handler(req, res) {
const { deal with, chain, community } = req.physique;

await Moralis.begin({ apiKey: course of.env.MORALIS_API_KEY });

attempt {
const message = await Moralis.Auth.requestMessage({
deal with,
chain,
community,
…config,
});

res.standing(200).json(message);
} catch (error) {
res.standing(400).json({ error });
console.error(error);
}
}

Create a Signal-In Web page with the WalletConnect Modal

With the preliminary setup accomplished and the “_app.jsx” and “request-message.js” information in place, it’s time to combine WalletConnect. Begin by creating the “signin.jsx” file contained in the “pages” folder. This file will function a brand new web page when you populate it based on our directions. For starters, enter the next:

operate SignIn() {
return (
<div>
<h3>Web3 Authentication</h3>
</div>
);
}

export default SignIn;

Transferring on, you want to create the “Authenticate by way of WalletConnect” button, as introduced within the demo above. Furthermore, for now, additionally “console.log” customers’ particulars. You’ll obtain each of those objectives by updating your “signin.jsx” file to look as follows:

import { useConnect } from ‘wagmi’;
import { InjectedConnector } from ‘wagmi/connectors/injected’;
import axios from ‘axios’;

operate SignIn() {
const { connectAsync } = useConnect();

const handleAuth = async () => {
const { account, chain } = await connectAsync({ connector: new InjectedConnector() });

const userData = { deal with: account, chain: chain.id, community: ‘evm’ };

console.log(userData)
};

return (
<div>
<h3>Web3 Authentication</h3>
<button onClick={() => handleAuth()}>Authenticate by way of WalletConnect</button>
</div>
);
}

export default SignIn;

Lengthen the “handleAuth” Performance

With the above traces of code in place, you have already got your Web3 authentication web page’s look lined. Thus, it’s time to additionally add the precise Web3 performance. So, begin by extending the “handleAuth” performance. You’ll use the latter to name the beforehand created “requestMessage” endpoint. As such, replace the “signin.jsx” script to match the traces of code under:

import { useAccount, useConnect, useSignMessage, useDisconnect } from ‘wagmi’;
import { InjectedConnector } from ‘wagmi/connectors/injected’;
import axios from ‘axios’;

operate SignIn() {
const { connectAsync } = useConnect();
const { disconnectAsync } = useDisconnect();
const { isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();

const handleAuth = async () => {
// Disconnects the Web3 supplier if it is already energetic
if (isConnected) {
await disconnectAsync();
}
// Enabling WalletConnect
const { account, chain } = await connectAsync({
connector: new WalletConnectConnector({
choices: {
qrcode: true,
},
}),
});

const userData = { deal with: account, chain: chain.id, community: ‘evm’ };
// Making a put up request to our ‘request-message’ endpoint
const { knowledge } = await axios.put up(‘/api/auth/request-message’, userData, {
headers: {
‘Content material-Kind’: ‘utility/json’,
},
});
const message = knowledge.message;
const signature = await signMessageAsync({ message });

console.log(signature)
};

return (
<div>
<h3>Web3 Authentication</h3>
<button onClick={() => handleAuth()}>Authenticate by way of WalletConnect</button>
</div>
);
}

export default SignIn;

Configure NextAuth

As a way to correctly configure NextAuth, create a “[…nextauth].js” file. Additionally, ensure the file is contained in the “auth” folder (path: “pages/api/auth/”). Then, add the next code to this file:

import CredentialsProvider from ‘next-auth/suppliers/credentials’;
import NextAuth from ‘next-auth’;
import Moralis from ‘moralis’;

export default NextAuth({
suppliers: [
CredentialsProvider({
name: ‘MoralisAuth’,
credentials: {
message: {
label: ‘Message’,
type: ‘text’,
placeholder: ‘0x0’,
},
signature: {
label: ‘Signature’,
type: ‘text’,
placeholder: ‘0x0’,
},
},
async authorize(credentials) {
try {
// “message” and “signature” are needed for authorization
// We described them in “credentials” above
const { message, signature } = credentials;

await Moralis.start({ apiKey: process.env.MORALIS_API_KEY });

const { address, profileId } = (
await Moralis.Auth.verify({ message, signature, network: ‘evm’ })
).raw;

const user = { address, profileId, signature };
// Returning the user object and creating a session
return user;
} catch (e) {
console.error(e);
return null;
}
},
}),
],
// Including consumer information to the consumer session object
callbacks: {
async jwt({ token, consumer }) {
consumer && (token.consumer = consumer);
return token;
},
async session({ session, token }) {
session.consumer = token.consumer;
return session;
},
},
});

Safe Authentication with WalletConnect

As for the ultimate tweak to the “signin.jsx” file, you want to equip it with NextAuth authentication. As well as, you’ll additionally import “WalletConnectConnector” from wagmi and “useRouter” from Subsequent. Moreover, the traces of code under may even correctly increase the “SignIn” operate:

import { signIn } from ‘next-auth/react’;
import { useAccount, useConnect, useSignMessage, useDisconnect } from ‘wagmi’;
import { useRouter } from ‘subsequent/router’;
import axios from ‘axios’;
import { WalletConnectConnector } from ‘wagmi/connectors/walletConnect’;

operate SignIn() {
const { connectAsync } = useConnect();
const { disconnectAsync } = useDisconnect();
const { isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();
const { push } = useRouter();

const handleAuth = async () => {
if (isConnected) {
await disconnectAsync();
}
// Added WalletConnectConnector
const { account, chain } = await connectAsync({
connector: new WalletConnectConnector({
choices: {
qrcode: true,
},
}),
});

const userData = { deal with: account, chain: chain.id, community: ‘evm’ };

const { knowledge } = await axios.put up(‘/api/auth/request-message’, userData, {
headers: {
‘Content material-Kind’: ‘utility/json’,
},
});

const message = knowledge.message;

const signature = await signMessageAsync({ message });

// Redirect consumer after success authentication to ‘/consumer’ web page
const { url } = await signIn(‘credentials’, { message, signature, redirect: false, callbackUrl: ‘/consumer’ });
/**
* as an alternative of utilizing signIn(…, redirect: “/consumer”)
* we get the url from callback and push it to the router to keep away from web page refreshing
*/
push(url);
};

return (
<div>
<h3>Web3 Authentication</h3>
<button onClick={() => handleAuth()}>Authenticate by way of WalletConnect</button>
</div>
);
}

export default SignIn;

Add the Person Web page

Within the above step, you’ve accomplished your “signin” web page. Nonetheless, if you happen to keep in mind the above demo, our instance dapp additionally has the “consumer” web page. Thus, revisit the “pages” folder and create a brand new file – “consumer.jsx”. Use the next traces of code to make sure that this web page shows some primary consumer information and presents the “Signal out” button:

import { getSession, signOut } from ‘next-auth/react’;

// Will get a prop from getServerSideProps
operate Person({ consumer }) {
return (
<div>
<h4>Person session:</h4>
<pre>{JSON.stringify(consumer, null, 2)}</pre>
<button onClick={() => signOut({ redirect: ‘/signin’ })}>Signal out</button>
</div>
);
}

export async operate getServerSideProps(context) {
const session = await getSession(context);

// Redirect if not authenticated
if (!session) {
return {
redirect: {
vacation spot: ‘/signin’,
everlasting: false,
},
};
}

return {
props: { consumer: session.consumer },
};
}

export default Person;

The “consumer” web page was the ultimate piece of in the present day’s puzzle. As such, you’ve now efficiently created a easy NextJS dapp with the WalletConnect QR code modal. Because you had been in a position to merely copy our code, all the pieces ought to be so as. Nonetheless, we nonetheless encourage you to check your dapp. 

Take a look at the WalletConnect QR Code Modal

Presuming that you just used the “3000” port (as instructed) to your “NEXTAUTH_URL” variable, use your browser to go to “http://localhost:3000/signin“. By doing so, you’ll land on the “signin” web page of your dapp, the place you’ll be able to check the authentication course of. Mainly, you want to full all of the steps introduced within the demo above. So, begin by clicking on “Authenticate by way of WalletConnect”:

Authenticate via WalletConnect modal button.

Nonetheless, it’s best to land on the “consumer” web page (“http://localhost:3000/consumer”) if the WalletConnect QR code modal is functioning correctly. Nonetheless, if you happen to can’t authenticate your self, the above code will redirect you again to the “signing” web page. If that occurs, ensure to re-examine the above steps.

Find out how to Combine the WalletConnect Modal and QR Code – Abstract

You now know that WalletConnect is an open-source protocol designed to determine protected connections between Web3 wallets and dapps. On this article, you additionally realized that it helps over 225 wallets throughout a number of chains. Moreover, you had an opportunity to observe our lead and create your individual NextJS dapp with the WalletConnect modal. To make the method as frictionless as doable, we offered you with all of the scripts you wanted to complete this problem. In consequence, you created the next six information, which include all of the required traces of code:

“.env.native““_app.jsx““request-message.js““signin.jsx““[…nextauth].js““consumer.jsx“

Transferring ahead, we encourage you to work on in the present day’s instance dapp by including extra Web3 functionalities. That means, you’ll get higher acquainted with the facility of Moralis’ Web3 API and, in flip, construct up the arrogance to deal with different initiatives. As a part of the training course of, we advocate you discover different how-to guides and tutorials within the Moralis documentation. Additionally, ensure to make use of the Moralis YouTube channel and the Moralis weblog to increase your blockchain growth horizons. For example, in a few of our newest articles, we concentrate on a Web3 JS tutorial for blockchain builders, constructing a Unity Web3 multiplayer sport, explaining Dogechain, the Aptos and Sui chains, the last word blockchain tech stack, and extra.   

Alternatively, you is perhaps desirous to go full-time crypto as quickly as doable. If that’s the case, it’s best to enroll in Moralis Academy and change into blockchain licensed. It will considerably enhance your probabilities of touchdown your dream crypto job. There are various programs obtainable; nevertheless, we advocate beginning with blockchain and Bitcoin fundamentals.



Source link

Stay in the Loop

Get the daily email from CryptoNews that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement - spot_img

You might also like...