Notus API
Authentication

Web3Auth

Web3Auth is a popular authentication provider that enables social login flows using Google, Apple, email magic links, and other familiar Web2 credentials. It abstracts away the complexity of private key management, making it easier to onboard mainstream users into Web3.

However, while Web3Auth authenticates users, it does not provide direct access to onchain functionality — users still need to fund wallets, manage gas fees, and interact with smart contracts manually.


Why combine Web3Auth with Notus API?

By combining Web3Auth with the Notus API, developers can deliver a seamless and gasless onboarding experience. This integration allows you to:

  • ✅ Authenticate users with social login
  • ✅ Create and register an ERC-4337 smart wallet
  • ✅ Eliminate the need for seed phrases or private keys
  • ✅ Sponsor gas fees using Paymasters or allow payment in ERC-20 tokens
  • ✅ Perform DeFi actions (like swaps) without requiring any prior user setup

This makes it possible to build applications where users can sign in with a Google account and immediately start using onchain features — without downloading wallets, buying tokens, or learning blockchain mechanics.


This guide will help you integrate Notus API with Web3Auth in a Next.js project. By the end of this tutorial, you will set up Web3Auth, retrieve the user's wallet, register a Smart Wallet, generate a swap quote, and execute a UserOperation.

Eager to get started? Check out our GitHub repository for a complete example and see how to integrate Notus API into your project.

1. Start a Next.js Project

First, create a new Next.js project. Run the following command in your terminal:

npx create-next-app@latest

This will scaffold a new Next.js application, setting up a basic React-based environment for building your dApp.


2. Install viem

We’ll use viem, a library for blockchain interactions, to simplify our integration. Install it by running:

npm i viem

3. Install web3Auth

npm i @web3auth/base @web3auth/ethereum-provider @web3auth/modal

4. Simple Web3Auth Setup

Configure Web3Auth by initializing the required modules and settings. Replace clientId with your actual Web3Auth client ID.

import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { Web3Auth, Web3AuthOptions } from "@web3auth/modal";
 
const clientId =
  "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ";
 
const chainConfig = {
  chainNamespace: CHAIN_NAMESPACES.EIP155,
  chainId: "0xaa36a7",
  rpcTarget: "https://rpc.ankr.com/eth_sepolia",
  ticker: "ETH",
  tickerName: "Ethereum",
  logo: "https://cryptologos.cc/logos/ethereum-eth-logo.png",
};
 
const privateKeyProvider = new EthereumPrivateKeyProvider({
  config: { chainConfig },
});
 
const web3AuthOptions: Web3AuthOptions = {
  clientId,
  web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
  privateKeyProvider,
};
 
const web3auth = new Web3Auth(web3AuthOptions);
 
export default function App() {
//...//
}

5. Initialize Web3Auth

Initialize Web3Auth to manage user sessions and connect to the blockchain.

import { useEffect, useState } from "react";
import { createWalletClient } from "viem";
 
export default function App() {
  const [account, setAccount] = useState<any | null>(null);
  const [loggedIn, setLoggedIn] = useState(false);
  const [externallyOwnedAccount, setExternallyOwnedAccount] = useState("");
 
  useEffect(() => {
    const init = async () => {
      try {
        await web3auth.initModal();
        if (!web3auth.provider) {
          return;
        }
        const account = createWalletClient({
          chain: polygon,
          transport: custom(web3auth.provider),
        });
 
        const [address] = await account.getAddresses();
 
        setExternallyOwnedAccount(address);
 
        setAccount(account);
 
        if (web3auth.connected) {
          setLoggedIn(true);
        }
      } catch (error) {
        console.error(error);
      }
    };
 
    init();
  }, []);
 
  //....//
}

6. Login with Web3Auth

Allow users to log in with Web3Auth and retrieve their externally owned account (EOA).

import { polygon } from "viem/chains";
 
 
const web3auth = new Web3Auth(web3AuthOptions);
 
export default function App() {
  const [account, setAccount] = useState<any | null>(null);
  const [loggedIn, setLoggedIn] = useState(false);
  const [externallyOwnedAccount, setExternallyOwnedAccount] = useState("");
 
  const login = async () => {
    const web3authProvider = await web3auth.connect();
    if (!web3authProvider) {
      return;
    }
    const account = createWalletClient({
      chain: polygon,
      transport: custom(web3authProvider),
    });
    const [address] = await account.getAddresses();
 
    setExternallyOwnedAccount(address);
 
    setAccount(account);
    if (web3auth.connected) {
      setLoggedIn(true);
    }
  };
 
  return <button onClick={login}>Login</button>;
}

7. Register or Query a Smart Wallet

Using the externally owned account (EOA) retrieved in the previous step, we can register or fetch the corresponding smart wallet details (Account Abstraction).

"use client";
//...//
export default function App() {
  const [accountAbstraction, setAccountAbstraction] = useState("");
 
  //.....//
 
  const getSmartWalletAddress = async () => {
    const FACTORY_ADDRESS = "0x0000000000400CdFef5E2714E63d8040b700BC24";
    let res = await fetch(`https://<baseUrl>/api/v1/wallets/register`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "<api-key>",
      },
      body: JSON.stringify({
        externallyOwnedAccount: externallyOwnedAccount,
        factory: FACTORY_ADDRESS,
        salt: "0",
      }),
    });
    if (!res?.ok) {
      res = await fetch(
        `https://<baseUrl>/api/v1/wallets/address?externallyOwnedAccount=${externallyOwnedAccount}&factory=${FACTORY_ADDRESS}&salt=${0}`,
        {
          method: "GET",
          headers: {
            "x-api-key": "<api-key>",
          },
        }
      );
    }
 
    const data = await res.json();
    setAccountAbstraction(data.wallet.accountAbstraction);
  };
 
  return (
    <button onClick={() => getSmartWalletAddress()}>Get SmartWallet</button>
  );
}

A Factory is a smart contract responsible for creating smart wallets. It helps ensure that wallet addresses are consistent and predictable, even before the wallet is fully deployed. This simplifies wallet creation and management while maintaining compatibility with blockchain standards.

If you're new to the concept of factories, we recommend visiting the What is Factory? page for a more detailed explanation.

Explanation:

This function interacts with the Notus API to either register or query a smart wallet based on the provided Externally Owned Account (EOA).

  • The salt is a unique value that, when combined with the EOA and factory, generates a deterministic smart wallet address. If no salt is provided, the default value is zero. Each distinct salt creates a new smart wallet for the same EOA and factory, allowing flexibility while ensuring consistent and predictable address generation.

  • The POST request is sent to register a smart wallet if it hasn’t been registered yet. The request uses the EOA, a factory address, and a salt value.

  • If the POST request fails (e.g., because the wallet is already registered), a fallback GET request retrieves the existing smart wallet details.

  • Once the smart wallet address is retrieved, it’s stored in the accountAbstraction state for further use.


8. Generate a Swap Quote

Next, let’s request a swap quote for exchanging tokens:

"use client";
 
import { polygon } from "viem/chains";
 
//...//
export default function App() {
  const [accountAbstraction, setAccountAbstraction] = useState("");
  const [externallyOwnedAccount, setExternallyOwnedAccount] = useState("");
 
  const [quote, setQuote] = useState<any>();
 
 
  //...//
 
  const getSwapQuote = async () => {
    const swapParams = {
      payGasFeeToken: "<token-address>",
      tokenIn: "<token-address>",
      tokenOut: "<token-address>",
      amountIn: "5",
      walletAddress: accountAbstraction,
      toAddress: accountAbstraction,
      signerAddress: externallyOwnedAccount,
      chainIdIn: polygon.id,
      chainIdOut: polygon.id,
      gasFeePaymentMethod: "DEDUCT_FROM_AMOUNT",
    };
    const res = await fetch("https://<baseUrl>/api/v1/crypto/swap", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "<api-key>",
      },
      body: JSON.stringify(swapParams),
    });
 
    if (!res.ok) return;
 
    const data = (await res.json()) as SwapQuote;
 
 
    setQuote(data);
  };
 
  return <button onClick={() => getSwapQuote()}>Swap Quote</button>;
}

If you are swapping from a native token (e.g., ETH, BNB, AVAX), use the following address as tokenIn: 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee. This ensures that the Notus API recognizes the asset as a native token.

Explanation:

The swapParams object contains details of the swap, including token addresses, wallet address, and fees.

The Notus API returns a swap quote, which is stored in the quote state.


9. Sign and Execute the User Operation

Finally, let’s sign the swap quote and execute the User Operation:

A UserOperation is a pseudo-transaction used in Account Abstraction (ERC-4337). It defines actions for a smart contract account to execute and is sent to a dedicated mempool, where bundlers group and forward these operations to the EntryPoint contract for validation and execution. Unlike traditional transactions, it offers greater flexibility, such as paying fees in tokens or executing custom logic.

export default function App() {
  const [account, setAccount] = useState<any | null>(null);
  const [externallyOwnedAccount, setExternallyOwnedAccount] = useState("");
 
  const [quote, setQuote] = useState<any>();
  const [txHash, setTxHash] = useState("");
 
 
  const signingAndExecute = async () => {
    if (!quote?.swap.quoteId) return;
 
    const quoteId = quote.swap.quoteId;
 
    const signature = await account.signMessage({
      account: externallyOwnedAccount,
      message: {
        raw: quoteId,
      },
    });
 
    const res = await fetch("https://<baseUrl>/api/v1/crypto/execute-user-op", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "<api-key>",
      },
      body: JSON.stringify({
        quoteId,
        signature,
      }),
    });
 
    if (!res.ok) return;
 
    const data = await res.json();
 
    setTxHash(data.userOpHash);
  };
 
  console.log(txHash);
 
  return (
    <button onClick={() => signingAndExecute()}>
      Signing user operation and execute
    </button>
  );
}

Explanation:

The quote is signed using the wallet’s private key.

The signed operation is sent to Notus for execution, and the resulting hash (userOpHash) confirms the transaction.

Signatures are validated on-chain, transactions won't be executed unless the EOA match

On this page