npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@civic/auth-web3

v0.1.7

Published

- [Civic Auth Client Web3 SDK](#civic-auth-client-web3-sdk) - [Embedded Wallets](#embedded-wallets) - [Quick Start](#quick-start) - [Installation](#installation) - [npm](#npm) - [yarn](#yarn) - [pnpm](#pnpm) - [bun](#bun) - [**Integr

Downloads

1,239

Readme

Civic Auth Client Web3 SDK

Civic Auth Web3 offers a simple, flexible, and fast way to integrate authentication with Web3 features into your applications.

You can find the full, official documentation here, with a quick-start version in this README.

Embedded Wallets

The Civic Auth Web3 SDK (@civic/auth-web3) extends the functionality of the base Civic Auth SDK by including the ability to provision a Web3 wallet for users. This allows Civic Auth apps to provide their users with access to the world of Cryptocurrencies and Web3 without any hassle or prior knowledge.

Quick Start

Sign up for Civic Auth at auth.civic.com and make sure to select the "web3 wallet" option.

If you already have an account, just log in and select the web3 wallet option in the configuration to enable web3 wallets.

Installation

Install the Civic Auth Web3 SDK:

npm

npm install @civic/auth-web3

yarn

yarn add @civic/auth-web3

pnpm

pnpm install @civic/auth-web3

bun

bun add @civic/auth-web3

Integration

You need to set up a CivicAuthProvider in your application with the integration for the web3 library being identical to the setup for @civic/auth, except that you import from @civic/auth-web3 instead of @civic/auth i.e:

import { CivicAuthProvider, UserButton } from "@civic/auth-web3/react";

Once the basic setup is done, you can access Web3 features by following the Embedded Wallet Web3 integration instructions below.

Ethereum / EVM

Creating a Wallet

When a new user logs in, they do not yet have a Web3 wallet by default. You can create a wallet for them by calling the createWallet function on the user object. Here’s a basic example:

import { userHasWallet } from "@civic/auth-web3";
import { useUser } from '@civic/auth-web3/react';

export const afterLogin = async () => {
  const userContext = await useUser();

  if (userContext.user && !userHasWallet(userContext)) {
    await userContext.createWallet();
  }
};

The useUser hook and UserContext Object

The useUser hook returns a user context object that provides access to the base library's user object in the 'user' field, and adds some Web3 specific fields. The returned object has different types depending on these cases:

If the user has a wallet,

type ExistingWeb3UserContext = UserContext & {
  walletAddress: "0x..." // the address of the embedded wallet
  wallet: // a Viem WalletClient
}

If the user does not yet have a wallet:

type NewWeb3UserContext = UserContext & {
  createWallet: () => Promise<void>;
  walletCreationInProgress: boolean;
} 

An easy way to distinguish between the two is to use the userHasWallet type guard.

Using the Wallet

The CivicAuth Web3 SDK uses Wagmi and Viem to expose the embedded wallet to your app, simplifying wallet interactions on both the front end and back end.

  • React Apps: Civic Auth is optimized for React, with easy access to Wagmi hooks for a seamless experience.
  • Non-React Apps: For non-React frameworks, use Viem directly to interact with the wallet.

Using the Wallet with Wagmi

To use the embedded wallet with Wagmi, follow these steps:

Ensure you have created the user's wallet first as described above.

1. Add the Embedded Wallet to Wagmi Config

Include embeddedWallet() in your Wagmi configuration as shown below:

import { embeddedWallet } from "@civic/auth-web3";

const wagmiConfig = createConfig({
  chains: supportedChains,
  transports: transports,
  connectors: [
    embeddedWallet(),
  ],
});

Call connect

Initiate the connection to the embedded wallet using Wagmi’s connect method.

const { connectors, connect } = useConnect();

// connect to the "civic" connector
const connector = connectors[0];
connect(connector);

Use Wagmi Hooks

Once connected, you can use Wagmi hooks to interact with the embedded wallet. Common hooks include:

  • useBalance: Retrieve the wallet balance.
  • useAccount: Access account details.
  • useSendTransaction: Send transactions from the wallet.
  • useSignMessage: Sign messages with the wallet.

For more detailed documentation on how to use these hooks, see the Wagmi docs.

A Full Example

See below for a full minimal example of a Wagmi app using Civic Auth for an embedded wallet. This is based on this GitHub repository that contains a sample implementation.

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { WagmiProvider, createConfig, useAccount, useConnect, useBalance, http } from 'wagmi';
import { embeddedWallet, userHasWallet } from '@civic/auth-web3';
import { CivicAuthProvider, UserButton, useUser } from '@civic/auth-web3/react';
import { mainnet, sepolia } from "wagmi/chains";

const wagmiConfig = createConfig({
  chains: [ mainnet, sepolia ],
  transports: {
    [mainnet.id]: http(),
    [sepolia.id]: http(),
  },
  connectors: [
    embeddedWallet(),
  ],
});

// Wagmi requires react-query
const queryClient = new QueryClient();

// Wrap the content with the necessary providers to give access to hooks: react-query, wagmi & civic auth provider
const App = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <WagmiProvider config={wagmiConfig}>
        <CivicAuthProvider clientId="< YOUR CLIENT ID >">
          <AppContent />
        </CivicAuthProvider>
      </WagmiProvider>
    </QueryClientProvider>
  );
};

// Separate component for the app content that needs access to hooks
const AppContent = () => {
  // The civic user hook
  const userContext = useUser();

  // Add the wagmi hooks
  const { connect, connectors } = useConnect();
  const { isConnected } = useAccount();
  const balance = useBalance({
    address: userHasWallet(userContext) ? userContext.walletAddress as `0x${string}`: undefined,
  });

  // A function to connect to an existing civic embedded wallet
  const connectExistingWallet = () => connect({
    connector: connectors[0],
  });

  // A function that creates the wallet if the user doesn't have one already
  const createWallet = () => {
    if (userContext.user && !userHasWallet(userContext)) {
      // Once the wallet is created, we can connect it straight away
      return userContext.createWallet().then(connectExistingWallet)
    }
  }

  return (
    <>
      <UserButton />
      {userContext.user && 
        <div>
          {!userHasWallet(userContext) &&
            <p><button onClick={createWallet}>Create Wallet</button></p>
          }
          {userHasWallet(userContext) && 
            <>
              <p>Wallet address: {userContext.walletAddress}</p>
              <p>Balance: {
                balance?.data
                  ? `${(BigInt(balance.data.value) / BigInt(1e18)).toString()} ${balance.data.symbol}`
                  : 'Loading...'
              }</p>
              {isConnected ? <p>Wallet is connected</p> : (
                <button onClick={connectExistingWallet}>Connect Wallet</button>
              )}
            </>
          }
        </div>
      }
    </>
  );
};

export default App;

Using the Wallet with Viem

If you are not using Wagmi, you may also use Viem directly to access the same wallet capabilities:

const userContext  = useUser();

if (userContext.user && userHasWallet(userContext)) {
  const { wallet } = userContext;
  const hash = await wallet.sendTransaction({ 
    to: '0x...',
    value: 1000n
  })
}

Full documentation for Viem can be found here.

Using Viem without React

While our SDK is Our SDK is currently being adapted to support other frontend frameworks beyond React.

Contact us if you have questions about integrating Civic Auth Web3 with a different framework.