Shib EOA SDK
Introduction
Shib EOA SDK offers a secure solution for users to sign into websites using Social logins like Google, Discord and Email and WalletConnect. In the case of Social login, it reconstruct a wallet with a Private/Public key pair in the background for downstream use cases like DIDs, Payments etc.
Check out the Web3Auth documentation to understand how wallet reconstruction happens.
Installation
Prerequisites
This SDK is designed to be used with Next.js (version 13 or higher). It can also be used with React-based frameworks capable of including API services, with some adaptations. Ensure your project meets these requirements before proceeding.
Before installing the SDK:
-
Create an empty
.npmignorefile -
And then create a
.npmrcfile in the main folder of your project to include the token required for downloading the SDK. Include the following lines:@shibaone:registry=https://npm.pkg.github.com
package-lock=false
//npm.pkg.github.com/:_authToken=YOUR_TOKEN_HERE
Installing the SDK
Install the SDK from the command line:
yarn add @shibaone/shib-auth-sdk
or via package.json:
"@shibaone/shib-auth-sdk": "1.0.78"
Building
First Install Dependencies:
yarn
Then generate build:
yarn build
Please ensure you use yarn as your package manager. Using other package managers like npm or pnpm may lead to inconsistencies due to differences in how they resolve and manage dependencies.
Environment Configuration
The variable NEXT_PUBLIC_AUTH0_BASE_PATH is used to configure the base URL of the Auth0 service that the application will interact with for authentication purposes. Specifically, this variable defines the endpoint or domain where the Auth0 API is hosted, enabling the application to handle operations such as user login, token exchange, and fetching user information.
This variable is the only environment variable that you can configure inside your application. It is also optional. If it is not set, the library will pass it server-side using a cookie. However, if you prefer not to use cookies, you need to specify this environment variable in the .env file of your project.
The reason for this variable to be passed via a cookie is that it is already included in the configuration provided by the environment-specific mode option but in the client-side.
Each environment contains an Auth0.domain setting that you can use as reference for the enviroment variable.
NEXT_PUBLIC_AUTH0_BASE_PATH="AUTH0_BASE_PATH"
Usage
Here’s how you can get started with the SDK:
Basic Configuration
The SDK includes mandatory files to be included in your project in order to have everything working in the application:
Service Worker
The Service Worker is responsible for the management of the redirect by Auth0 and is used for social login via email.
The SDK provides the serviceworker folder, for simplicity, which can be downloaded from the SDK's repo. Copy and paste it into the public folder of your project.
globals.css
In your globals.css file, add the following imports:
@import '@shibaone/shibhubui/styles.css';
@import "@rainbow-me/rainbowkit/styles.css";
These imports include the styles for ShibHub UI components and RainbowKit.
taiwlind.config
Modify your tailwind.config.ts file to update the content paths and include the necessary presets:
import type { Config } from "tailwindcss";
import shibHubUiPreset from '@shibaone/shibhubui/tailwind.preset.js';
const config: Config = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
'./node_modules/@shibaone/shibhubui/dist/**/*.js', // to add
'./node_modules/@shibaone/shib-auth-sdk/dist/**/*.js', // to add
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
presets: [
shibHubUiPreset, // to add
],
};
export default config;
If your project does not include Tailwind, please install it and use the configuration above. Learn how to add Tailwind to your project on their documentation.
Authorize page
The Authorize page is used for sending the email to the user and show the code for the login.
To generate this page, create authorize/page.tsx under the app folder:
'use client';
import React from 'react';
import { AuthorizePage } from '@shibaone/shib-auth-sdk';
export default function Authorize() {
const siteTitle = "Test App"
return (
<AuthorizePage
siteTitle={siteTitle}
/>
);
}
API routes
userinfo
Create userinfo/route.tsx under the app folder.
This file is used for getting the user info retrieved from Auth0.
You can configure the environment variable NEXT_PUBLIC_AUTH0_BASE_PATH to set the Auth0 URL. If not specified, it will be automatically retrieved from cookies.
import { NextRequest, NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { GetUserInfo } from '@shibaone/shib-auth-sdk';
export async function GET(req: NextRequest) {
const headers_instance = await headers();
const access_token = headers_instance.get('Authorization');
const cookies = req.headers.get('cookie');
const auth0Url = process.env.NEXT_PUBLIC_AUTH0_BASE_PATH ?? cookies
?.split('; ')
.find(cookie => cookie.startsWith('auth0Url='))
?.split('=')[1];
try {
if (!access_token) throw new Error('Access token not setted');
if (!auth0Url) throw new Error('Auth0 Url cookie not setted');
const response = await GetUserInfo(access_token, auth0Url);
return NextResponse.json(response, { status: 200 });
} catch (error) {
console.error(error);
return NextResponse.json(error, { status: 500 });
}
}
Integrate the SDK Provider
Wrap your application with the SDK's provider component to enable its features. Pass in your desired configuration to this provider. You can find more information about the options here.
"use client"
import React from 'react';
import { Environments, ShibAuthSdk, IAuthOptions, shibariumChain } from '@shibaone/shib-auth-sdk';
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/serviceworker/sw.js')
.then(registration => console.log('scope is: ', registration.scope));
}
}, []);
const networkOptions: IAuthOptions = {
GoogleProvider: undefined,
DiscordProvider: undefined,
Chains: [shibariumChain],
// If you use DEV enviroment and you don't have the project running in your local environment then use the TEST authenticator API URL
AuthenticatorApiUrl: "https://auth.shibinternal.com/api"
};
return (
<html lang="en">
<body>
<ShibAuthSdk mode={Environments.DEV} options={networkOptions}>
{ children }
</ShibAuthSdk>
</body>
</html>
);
}
Implementing a Login Button
Use the useShibAuth hook from the SDK for login functionality:
import React from 'react';
import { useShibAuth } from '@shibaone/shib-auth-sdk';
function LoginButton() {
const { openLoginModal } = useShibAuth();
return (
<button onClick={() => openLoginModal()}>Login</button>
);
}
export default LoginButton;
API Documentation
useShibAuth hook:
State Variables
user: User Represents the current authenticated user. This can be of type WAGMI or WEB3AUTH..
currentChain: IChain Represents the currently connected blockchain network.
isConnected: boolean
web3auth Object
The web3auth object is only available if the user is of type WEB3AUTH. It contains various functions and properties specific to managing Web3Auth users.
web3auth Methods
configureConfirmations
Configure the confirmation methods that the wallet will use before every blockchain action that needs a confirmation by the user.
It will works only if the Web3AuthWalletConfirmationsEnabled option is enabled.
Parameters:
| parameter | required/optional | type | description |
|---|---|---|---|
| actions | required | Record<ConfirmationModalStates, (params?: any) => void> | An object where each key corresponds to a ConfirmationModalStates, with each value being a callback function that accepts optional parameters. |
Returns: void No return value.
setCurrentWallet
Sets the main or derived wallet for the Web3Auth user. Parameters:
| parameter | required/optional | type | description |
|---|---|---|---|
| id | required | number | The path index, 0 for the main and >1 for derived wallets. |
Returns: Promise<void> No return value.
createDerivedWallet
Creates a new derived wallet for the Web3Auth user. Parameters:
| parameter | required/optional | type | description |
|---|---|---|---|
| name | optional | sring | The name of the derived wallet. |
Returns: Promise<void> |
hasAuthenticator
Checks if the Web3Auth user has an authenticator set up.
Parameters: None
Returns: Promise<boolean> A promise that resolves to true if the user has an authenticator, false otherwise.
hasSeedPhrase
Checks if the Web3Auth user has a seed phrase set up.
Parameters: None
Returns: Promise<boolean> A promise that resolves to true if the user has a seed phrase, false otherwise.
hasPassword
Checks if the Web3Auth user has a password set up.
Parameters: None
Returns: Promise<boolean> A promise that resolves to true if the user has a password, false otherwise.
web3auth Objects
modal Object
The modal object is responsible for showing and hiding the different modals related to the user's authentication and wallet management.
modal Methods
modal.openPrivateKeyModal
Opens the private key display modal for Web3Auth users.
Parameters: None
Returns: void
Throws:
Error if the user is not logged in.
Error if the user type is WAGMI.
modal.closePrivateKeyModal
Closes the private key display modal if it's currently open.
Parameters: None
Returns: void
modal.setup Object
The setup object within modal contains functions for opening and closing modals related to initial user setup, including setting up passwords, authenticators, and seed phrases.
modal.setup Methods
modal.setup.openPasswordModal
Opens the password setup modal for Web3Auth users.
Parameters: None
Returns: void
Throws:
Error if the user is not logged in.
Error if the user type is WAGMI.
Error if the user already has a password.