WalletConnect Integration – The way to Combine WalletConnect


This tutorial seems to be at including safe authentication through Moralis and how one can combine WalletConnect into your Web3 challenge. By following alongside on this tutorial, you may have an authentication answer up and working in report time, as seen within the following illustrative picture showcasing WalletConnect integration:

In case you’re an skilled developer, go forward and entry the whole file construction and code on our documentation web page to get began instantly. Nevertheless, if you’d like a step-by-step information on how one can combine WalletConnect, we suggest studying this text from begin to end!

Overview

Web3 authentication is the gateway to dapps (decentralized functions), and with Moralis’ Web3 Auth API, you may add Web3 login to any dapp effortlessly. The API helps all main options, together with WalletConnect integration. For the reason that latter tends to be one of the best various for cellular customers, as a developer, you have to discover ways to combine WalletConnect. In spite of everything, this open-source protocol helps greater than 170 crypto wallets, making it some of the user-friendly Web3 authentication strategies. Moreover, since Moralis is all about cross-chain interoperability, its Auth API lets you implement WalletConnect to dapps throughout all main blockchains. Additionally, Moralis empowers you to combine it as a standalone Web3 login answer or mix it with different Web3 onboarding strategies.    

The core part of immediately’s article will probably be all about exhibiting you how one can add WalletConnect integration utilizing Moralis. That is the place you’ll have an opportunity to create a easy NextJS app and combine WalletConnect as an authentication answer. Nevertheless, earlier than we invite you to roll up your sleeves, we have to cowl some fundamentals. As such, we’ll first make sure you all know what WalletConnect is and what wallets are suitable with this neat answer. Nevertheless, in case you are already accustomed to these fundamentals, be at liberty to create your free Moralis account and leap to the “Add WalletConnect Integration” part.   

User holding a phone and scanning WalletConnect's QR code.

WalletConnect – What’s it?

WalletConnect is an open-source protocol that can be utilized to determine a connection between a variety of crypto wallets and dapps. This protocol ensures that the connection between wallets, functions, or units is secure. In spite of everything, while you use WalletConnect to determine these connections, its protocol makes use of symmetric encryption through a shared key between two friends.

Primarily, WalletConnect is a decentralized Web3 messaging layer and a regular to attach blockchain wallets to dapps. Furthermore, the WalletConnect crew’s mission is to constantly develop the interoperability of the Web3 area. Therefore, it’s relatively secure to presume that WalletConnect will proceed to supply one of the best tooling and infrastructure for Web3 wallets and dapps. Furthermore, WalletConnect v2 is chain agnostic and suitable with any blockchain of your selection. Consequently, it’s simple to ship an excellent person expertise when choosing this answer.

These are the three core WalletConnect options:

Chain Agnostic – Like most Web3 initiatives, WalletConnect is conscious that the longer term will most certainly be multi-chain oriented. Accordingly, it already helps numerous chains, together with Ethereum, Solana, and plenty of others. Furthermore, they’re dedicated to persevering with so as to add help for extra chains. Multi-Chain – Due to WalletConnect’s multi-chain help, you may join any of the supported wallets to a number of chains concurrently.Platform Agnostic – WalletConnect helps totally different platforms. As such, you need to use WalletConnect’s protocol on the internet or desktop, cellular, and gaming apps.

Graph illustrating WalletConnect integration.

Establishing Connections with WalletConnect – How Does It Work?

Relating to utilizing WalletConnect integration, customers have two methods to determine the connection between wallets and dapps. They will do it by scanning a QR code, which is the popular methodology and supplied by default. Nevertheless, customers may use a deep hyperlink. In each instances, one peer (or dapp) sends out the code or hyperlink, whereas the opposite should scan or approve it. As such, while you combine WalletConnect into dapps, you allow customers to simply set up secure and dependable Web3 connections.  

What Wallets are Suitable with WalletConnect?

In keeping with the official WalletConnect web site, their answer works with greater than 170 Web3 wallets. Since this quantity is extraordinarily excessive, it wouldn’t make a lot sense to checklist the entire supported wallets herein. Nevertheless, you may view all supported wallets by visiting WalletConnect’s official web site. As soon as there, scroll all the way down to the “Searching for a pockets?” part, and hit the “VIEW ALL WALLETS” button: 

Page showing multiple wallets, including MetaMask, Rainbow, Argent, etc.

On the subsequent web page, you’ll truly be capable of view all supported crypto wallets:

Page showing all available wallets.

Furthermore, because the above screenshot signifies, all supported Web3 wallets are listed throughout sixteen pages. Since there are fifteen wallets per web page and there are fifteen complete pages, it looks as if WalletConnect already helps greater than 225 crypto wallets. 

Add WalletConnect Integration

That is the part the place you’ll discover ways to add WalletConnect integration into your dapps. As talked about above, we’ll concentrate on making a NextJS software and equip it with this answer utilizing the facility of Moralis’ Web3 Auth API. So, in the event you determine to comply with our lead, you’ll have your dapp with WalletConnect integration added very quickly. Actually, right here’s a fast preview of what you’ll be constructing:

Final result of this tutorial's NextJS app with WalletConnect integration.

After clicking on the “Authenticate through WalletConnect” button, a QR code will pop up, enabling you (or your customers) to attach your Web3 pockets by scanning the code:

QR code modal displayed.

Lastly, after efficiently finishing the Web3 authentication course of, our dapp can even show some fundamental particulars concerning the related pockets:

Showing the USER SESSION page.

Stipulations and the Preliminary Setup

If you wish to construct the above-demonstrated dapp following our lead, be sure to full these conditions:

Have your Moralis account prepared.Set up and arrange Visible Studio Code (VSC).Create your NextJS dapp. In case you need assistance with that, use the “Create Subsequent App” web page within the NextJS docs or full our “Utilizing NextJS” tutorial. 

In case you took care of the above conditions, proceed by putting in the required dependencies. Primarily, you must set up Moralis, NextAuth, and Axios. To do that, use one of many following instructions (relying on which package deal supervisor you might be utilizing:

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

Subsequent, you want a Web3 library. After all, there are a number of choices at your disposal; nevertheless, we encourage you to comply with our lead and use wagmi. Thus, set up the “wagmi” dependency utilizing one of many following instructions: 

npm set up wagmi ethersyarn add wagmi etherspnpm add wagmi ethers

Including Environmental Variables

With the above dependencies in place, it’s time so as to add the required atmosphere variables in a “.env.native” file. Additionally, be sure to have that file in your app’s root. Listed below are the variables you must add:

“APP_DOMAIN” – That is an “RFC 4501” DNS authority that’s requesting the signing.“MORALIS_API_KEY” – You possibly can receive the important thing on the “Web3 APIs” web page of your Moralis admin space:

Moralis Admin Page showing the Web3 API key.

“NEXTAUTH_URL” – That is your dapp tackle, and within the growth stage, you’ll use “http://localhost:3000” or one other port.“NEXTAUTH_SECRET” – You employ this variable to encrypt the JWT tokens of customers. Furthermore, you may put any worth right here or generate one at “https://generate-secret.now.sh/32”. 

Moreover, that can assist you higher perceive the above atmosphere variables, make certain to take a look at this instance:

The above-listed bullet point variables are listed as an image.

Observe: Everytime you modify your “.env.native” file, you must restart your dapp.

Wrapping Your App

As you might know, NextJS makes use of the “App” part to initialize pages. Nevertheless, you may override that part and management the web page initialization. To realize that, you have to wrap your pages with “WagmiConfig” and “SessionProvider“. So, create your “_app.jsx” file contained in the “pages” folder and populate this file with the next strains of code:

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,
});

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

export default MyApp;

Including the “requestMessage” Endpoint

So as to add the “requestMessage” endpoint, you have to create a brand new API file. Name that file’s “request-message.js” and ensure to have it within the “auth” folder, which ought to be inside “pages/api”. You’ll use this endpoint to make requests to “Moralis.Auth“, which is able to generate a singular message. Then, you’ll signal that message on the shopper aspect. Listed below are the strains of code that you must use within the “request-message.js” file:

import Moralis from ‘moralis’;

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

export default async perform handler(req, res) {
const { tackle, chain, community } = req.physique;

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

strive {
const message = await Moralis.Auth.requestMessage({
tackle,
chain,
community,
…config,
});

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

Making a Signal-In Web page with WalletConnect Integration

By this level, you’ve efficiently accomplished the preliminary setup. As such, it’s time you truly combine WalletConnect. So, create a brand new web page file (contained in the “pages” folder) and name it “signin.jsx”. Furthermore, begin by populating this file with the next strains of code:

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

export default SignIn;

Subsequent, you wish to use the identical file to create a button that can allow Web3 authentication. As well as, you additionally wish to “console.log” customers’ particulars (as per the demo above). As such, you must develop the content material of the “signin.jsx” to match the next:

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

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

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

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

console.log(userData)
};

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

export default SignIn;

Extending the “handleAuth” Performance

The above strains of code already be sure that your Web3 authentication web page seems to be as introduced above. Nevertheless, we nonetheless want so as to add the precise performance. Therefore, let’s first prolong the “handleAuth” performance to make use of it to name the above-created “requestMessage” endpoint. By doing so, your “signin.jsx” file ought to look as follows:

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

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

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

const userData = { tackle: account, chain: chain.id, community: ‘evm’ };
// Making a submit request to our ‘request-message’ endpoint
const { information } = await axios.submit(‘/api/auth/request-message’, userData, {
headers: {
‘Content material-Sort’: ‘software/json’,
},
});
const message = information.message;
const signature = await signMessageAsync({ message });

console.log(signature)
};

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

export default SignIn;

Configuring NextAuth

Contained in the “auth” folder (path: “pages/api/auth/”), create a “[…nextauth].js” file and populate it with the next strains of code:

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 person information to the person session object
callbacks: {
async jwt({ token, person }) {
person && (token.person = person);
return token;
},
async session({ session, token }) {
session.person = token.person;
return session;
},
},
});

The above configures NextAuth so to add it to the “signin.jsx” script. Furthermore, as you’ve most likely observed, the above configuration additionally makes use of the “MORALIS_API_KEY” variable created within the “.env.native” file above.

Securing Authentication

For this remaining tweak to the “signin.jsx” file, you’ll be including NextAuth authentication. You additionally must import “WalletConnectConnector” from wagmi, import “useRouter” from Subsequent, and develop the “SignIn” perform. In the end, that is what your “signin.jsx” script ought to seem like in its remaining type:

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’;

perform 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 = { tackle: account, chain: chain.id, community: ‘evm’ };

const { information } = await axios.submit(‘/api/auth/request-message’, userData, {
headers: {
‘Content material-Sort’: ‘software/json’,
},
});

const message = information.message;

const signature = await signMessageAsync({ message });

// Redirect person after success authentication to ‘/person’ web page
const { url } = await signIn(‘credentials’, { message, signature, redirect: false, callbackUrl: ‘/person’ });
/**
* as a substitute of utilizing signIn(…, redirect: “/person”)
* 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 through WalletConnect</button>
</div>
);
}

export default SignIn;

Including Person Web page to Dapp with WalletConnect Integration

The ultimate step to finish this straightforward NextJS dapp with WalletConnect integration revolves across the “person” web page. As such, go to the “pages” folder and create the “person.jsx” file. These are the strains of code that you must add to this file:

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

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

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

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

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

export default Person;

With all of the scripts in place, it’s time you take a look at your dapp. 

Testing the WalletConnect Connector

In case you used the “3000” port to your “NEXTAUTH_URL” variable, go to “http://localhost:3000/signin“. That is the place you’ll be capable of take a look at your dapp’s authentication circulate. As soon as on the “signin” web page, click on on “Authenticate through WalletConnect”:

Showing where to click on the Authenticate via WalletConnect button.

When the QR code seems, use your favourite Web3 pockets in your telephone to scan the code. For example, that is what you must see in your telephone in the event you determine to make use of Belief Pockets (the method is analogous for different crypto wallets):

Trust Wallet authentication after clicking on the Trust Wallet option in WalletConnect.

If the authentication is profitable, you must land on the “person” web page (“http://localhost:3000/person“). Nevertheless, if the authentication is just not profitable, you’ll be redirected again to the “signing” web page.

In case you might be going through any points, make certain to undergo the scripts. As such, use the next overview of immediately’s progress. In the end, these are the recordsdata you created and populated by following immediately’s tutorial:

“.env.native” – That is the place you retailer all of the native variables, together with your Moralis Web3 API key.“_app.jsx” – You used this file to wrap your app with “WagmiConfig” and “SessionProvider“.“request-message.js” – This file serves as an endpoint for making requests to generate a singular message.“signin.jsx” – That is the file that covers the “signin” web page and permits customers to authenticate themselves utilizing the WalletConnect integration.“[…nextauth].js” – That is the place you configured NextAuth.“person.jsx” – You created this script to current efficiently authenticated customers with some fundamental person information. 

WalletConnect Integration – The way to Combine WalletConnect – Abstract

We lined fairly a distance in immediately’s article. First, you discovered what WalletConnect is and what wallets are suitable with this open-source protocol. Therefore, you now know that there are considerably near 200 wallets you need to use to authenticate with WalletConnect. With the fundamentals below your belt, you have been able to comply with our lead as we confirmed you how one can combine WalletConnect right into a easy NextJS software. To do that, you accomplished some conditions, put in correct dependencies, and took care of the preliminary setup. Then, you simply needed to copy-paste the strains of code offered herein into the recordsdata we instructed you to create. Final however not least, you had a chance to test-run your dapp. 

In case you loved this tutorial, we encourage you to discover different tutorials and how-to guides within the Moralis documentation. For example, you may create dapps utilizing Moralis with different frameworks and dev platforms. Or, you may discover different Web3 authentication choices. Along with Moralis’ docs, make certain to develop your blockchain growth information and abilities utilizing the Moralis YouTube channel and the Moralis weblog. Actually, you might use these two retailers as your free ongoing blockchain growth training. A number of the newest articles concentrate on Dogechain, Aptos, the Sui blockchain, the final word blockchain tech stack, the main Web3 infrastructure answer, cross-chain bridging, and rather more.

However, you could be considering going full-time crypto sooner relatively than later. In that case, you must turn into blockchain licensed by enrolling in Moralis Academy. If you wish to be a pacesetter in a promising Web3 challenge, the “Blockchain Enterprise Masterclass” course undoubtedly deserves your consideration. 

Moralis Academy



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...