@threesigmaxyz/zkauth-sdk
TypeScript icon, indicating that this package has built-in type declarations

0.0.2404-5.716 • Public • Published

zkAuth SDK Github Actions License: MIT

🚧 NOTICE: This project is still under active development. Do not use in production until a stable version is released.

banner

The zkAuth SDK is a JavaScript library that allows you to interact with the zkAuth protocol. It provides a set of tools for connecting to the zkAuth protocol, authenticating users, and managing user sessions. The SDK is designed to be easy to use and flexible, allowing you to integrate zkAuth into your existing applications with minimal effort.

Getting Started

Requirements

In order to run the tests and deployment scripts you must install the following:

  • Git - A distributed version control system.
  • Docker - A containerization platform. Additionally, you should have make installed.

Installation

Install from package manager

npm install @threesigmaxyz/zkauth-sdk

Install from source

git clone https://github.com/threesigmaxyz/zkauth-sdk
cd zkauth-sdk
npm install

Usage

Initialization

ZkAuth should be initialised as soon as your app loads up to enable the user to log in. Preferably done within a constructor, initialisation is the step where you can pass on all the configurations for ZkAuth you want. An example configuration for the zkSync Sepolia testnet will look like this:

import { ZkAuth, ZKAUTH_NETWORK } from '@threesigmaxyz/zkauth-sdk';
import { GoogleAdapter } from '@threesigmaxyz/zkauth-sdk/adapters';

const zkAuth = new ZkAuth({
    // Get your API key from the ZkAuth Dashboard
    apiKey: process.env.ZKAUTH_API_KEY,

    // Mainnet, Testnet or Local
    zkAuthNetwork: ZkAuthEnvironment.Testnet,

    // List of adapters to use.
    adapters: [
        new GoogleAdapter(
            process.env.GOOGLE_CLIENT_ID, // Google OAuth Client ID.
            'http://localhost:3000/auth/redirect' // OAuth redirect URL.
        ),
    ],
});

The apiKey is the API key used to connect to the zkAuth backend. You can get your API key from the ZkAuth Dashboard, or use the default API key for testing purposes. Please note that the default API key is heavily rate-limited and should not be used in production.

The zkAuthNetwork is the network to use. This will configure the RPC url to connect to as well as the API endpoints to use. For this guide, we will use the Testnet environment, which connects to the zkSync Sepolia testnet. More information about the available environments can be found here.

The adapters field is an array of authentication adapters to use. These adapters are used to authenticate users using different auth providers such as Google, Facebook, Twitter, etc. For this guide, we will use the GoogleAdapter to authenticate users using Google OAuth. You can add more adapters to support other authentication methods.

Adapters

The ZkAuth object uses adapters to interact with the zkAuth protocol. Adapters must implement the ZkAuthAdapter interface which provides the required methods for managing the login flow and user session.

/**
 * Represents an interface for a ZkAuth adapter.
 */
export interface ZkAuthAdapter {
  name: string;
  
  /**
   * Connects the adapter to a wallet and returns a JWT token.
   * @param wallet The wallet to connect to.
   * @returns A promise that resolves to a JWT token.
   */
  connect: (wallet: Wallet) => Promise<JWT>;
  
  /**
   * Disconnects the adapter from the wallet.
   * @returns A promise that resolves when the disconnection is complete.
   */
  disconnect: () => Promise<void>;
}

Default Adapters

The zkauth-sdk provides the following default adapters:

Name Adapter Description
google GoogleAdapter A Google adapter for connecting to a Google account.
recovery RecoveryAdapter A recovery adapter for restoring a session using a recovery code.
mock MockAdapter A mock adapter for testing purposes (should not be used in production).

Note that some adapters may require additional configuration. For example, the GoogleAdapter requires a clientId and redirectUri to be set in the configuration object.

Custom Adapters

You can implement your own custom adapter by extending the ZkAuthAdapter interface. For example, the following code snippet shows how to implement a custom adapter for a hypothetical provider called MyProvider:

import { ZkAuthAdapter, Wallet, JWT } from '@threesigmaxyz/zkauth-sdk';

export class MyProviderAdapter implements ZkAuthAdapter {
  name = 'my-provider';

  async connect(wallet: Wallet): Promise<JWT> {
    // Connect to the wallet and return a JWT token.
  }

  async disconnect(): Promise<void> {
    // Disconnect from the wallet.
  }
}

Connect

The connect method is used to connect to the zkAuth protocol and authenticate the user via a specific adapter. It returns a ZkAuthSession object that can be used to interact with a ZkAuth account.

// Connect to the zkAuth protocol.
const session = await zkAuth.connect("google"); // or "recovery" or "mock"

The session object contains the following properties:

  • wallet: A ZkAuthWallet object that can be used to send transactions to the zkAuth protocol.
  • provider: A ZkAuthProvider object that can be used to interact with the zkAuth protocol.
  • userInfo: A ZkAuthUserInfo object that contains the user's account information.
  • token: A JWT token that can be used to authenticate the user.

A failed connection attempt will throw an error.

Get Session

After connecting to the zkAuth protocol, you can get the current session by calling the session method. The session method will return a cached ZkAuthSession object as long as the session is still valid and the user is still logged in. A logout attempt will invalidate the session even if the token has not expired.

const session = await zkAuth.session();

If the session has expired or the user has logged out, the session method will return null.

Send Transaction

The sendTransaction method is used to send a transaction to the zkAuth protocol. It accepts a transaction object as an argument and returns a promise that resolves to a transaction receipt.

const tx = {
    to: 'recipient_address',
    value: ethers.utils.parseEther('0.01') // Amount to send, for example, 0.01 ETH
};

const txResponse = await session.provider.sendTransaction(tx);
const receipt = await txResponse.wait();
console.log('Transaction Receipt:', receipt);

Logout

The logout method is used to log the user out of the zkAuth protocol.

await zkAuth.logout();

The logout method accepts a revoke parameter, which is used to revoke the user's on-chain session. By default, the revoke parameter is set to true. Setting the revoke parameter to false will only log the user out of the browser session.

await zkAuth.logout(false);

Note that revoking the user's on-chain session incurs a gas fee.

Testing

The SDK uses jest for testing. Jest configuration can be found in the jest.config.js file. We provide two separate testing suites: unit tests and integration tests.

Unit Tests

Unit tests are located in the tests/unit project. They test the business logic and core use-cases. To execute all unit tests, run the following command:

npm run test:unit

Integration Tests

Integration tests, that rely on a Docker deployment of the zkAuth protocol, are located in the tests/integration folder. They test for the correct interaction between the SDK and the on-chain components of the zkAuth protocol. To execute all integration tests, run the following command:

npm run test:integration

About Us

Three Sigma is a venture builder firm focused on blockchain engineering, research, and investment. Our mission is to advance the adoption of blockchain technology and contribute towards the healthy development of the Web3 space. If you are interested in joining our team, please contact us here.

Package Sidebar

Install

npm i @threesigmaxyz/zkauth-sdk

Weekly Downloads

9

Version

0.0.2404-5.716

License

MIT

Unpacked Size

3.73 MB

Total Files

231

Last publish

Collaborators

  • 3s-jafonso
  • 0x0xyz
  • threesigmaxyz_info