npm package: @otim/turnkey
Description: Turnkey authentication and wallet management library
Author: Otim Labs
Latest version: 0.0.5

# @otim/turnkey

Turnkey authentication and wallet management library for React applications.

## Installation

```bash
pnpm add @otim/turnkey
```

## Features

- 🔐 Turnkey authentication with passkeys
- 🔌 Wagmi connector for seamless Web3 integration
- ⚡ Auto-connect functionality
- 🪝 React hooks for authentication flow
- 📦 TypeScript support
- 📁 Folder-based exports for tree-shaking

## Import Paths

This package provides folder-based exports for better tree-shaking and organized imports:

```tsx
// Main export (includes everything)
import * from "@otim/turnkey";

// Folder-based exports (recommended)
import { TurnkeyConnectorError } from "@otim/turnkey/errors";
import { useTurnkeyAuth, useTurnkeyAutoConnect } from "@otim/turnkey/hooks";
import { TurnkeyProviderWrapper, TurnkeyAutoConnectProvider } from "@otim/turnkey/providers";
import { AccountManagerService, ChainManagerService } from "@otim/turnkey/services";
import { TurnkeyAccountData } from "@otim/turnkey/types";
import { getTurnkeyAccountData, isTurnkeyConnector } from "@otim/turnkey/utils";
```

## Usage

### 1. Setup Turnkey Provider

Wrap your application with the `TurnkeyProviderWrapper`:

```tsx
import { TurnkeyProviderWrapper } from "@otim/turnkey/providers";

function App() {
  return (
    <TurnkeyProviderWrapper
      apiBaseUrl={process.env.NEXT_PUBLIC_TURNKEY_API_URL}
      defaultOrganizationId={process.env.NEXT_PUBLIC_TURNKEY_ORGANIZATION_ID}
    >
      {/* Your app */}
    </TurnkeyProviderWrapper>
  );
}
```

### 2. Use Authentication Hook

Use the `useTurnkeyAuth` hook for authentication:

```tsx
import { useTurnkeyAuth } from "@otim/turnkey/hooks";
import { turnkeyLogin, turnkeyVerification } from "@/server/actions";

function LoginForm() {
  const auth = useTurnkeyAuth({
    rpName: "Your App Name",
    onLogin: turnkeyLogin,
    onVerification: turnkeyVerification,
  });

  const handleLogin = async (email: string, code: string) => {
    const result = await auth.authenticateExistingUser(email, code);
    if (result.success) {
      // Handle success
    }
  };

  return (
    // Your login form
  );
}
```

### 3. Auto-Connect (Optional)

Enable auto-connect functionality:

```tsx
import { TurnkeyAutoConnectProvider } from "@otim/turnkey/providers";

function App() {
  return (
    <TurnkeyAutoConnectProvider chains={chains}>
      {/* Your app */}
    </TurnkeyAutoConnectProvider>
  );
}
```

### 4. Account Management

Use utility functions for account data management:

```tsx
import {
  getTurnkeyAccountData,
  setTurnkeyAccountData,
  updateTurnkeyAccountData,
} from "@otim/turnkey/utils";

// Get account data
const accountData = getTurnkeyAccountData(chains);

// Set account data
setTurnkeyAccountData(accountData, chains);

// Update account data
updateTurnkeyAccountData({ email: "new@example.com" }, chains);
```

## API Reference

### Components

#### `TurnkeyProviderWrapper`

Props:

- `apiBaseUrl: string` - Turnkey API base URL
- `defaultOrganizationId: string` - Turnkey organization ID
- `customRpId?: string` - Custom relying party ID (optional)
- `children: ReactNode` - Child components

#### `MigrationTurnkeyProvider`

For legacy passkey migration. Same props as `TurnkeyProviderWrapper` plus:

- `legacyRpId?: string` - Legacy relying party ID

#### `TurnkeyAutoConnectProvider`

Props:

- `chains: readonly Chain[]` - Array of supported chains
- `children: ReactNode` - Child components

### Hooks

#### `useTurnkeyAuth(config: TurnkeyAuthConfig)`

Configuration:

- `rpName: string` - Relying party name
- `onLogin: (params) => Promise<{ data: TurnkeyLoginResponse }>` - Login handler
- `onVerification: (params) => Promise<{ data: { isLogin: boolean } }>` - Verification handler

Returns:

- `isLoading: boolean`
- `error: string | null`
- `sendVerificationEmail: (email: string) => Promise<VerificationResult>`
- `authenticateExistingUser: (email: string, code: string) => Promise<AuthResult>`
- `createNewAccount: (email: string, code: string, credential: PasskeyCredential) => Promise<AuthResult>`
- `createPasskey: (email: string, customRpId?: string) => Promise<PasskeyCredential>`
- `resetState: () => void`

#### `useTurnkeyAutoConnect(config: UseTurnkeyAutoConnectConfig)`

Configuration:

- `chains: readonly Chain[]` - Array of supported chains

### Functions

#### `turnkeyConnector(config: TurnkeyConnectorConfig)`

Creates a Wagmi connector for Turnkey.

Configuration:

- `chains: readonly Chain[]` - Array of supported chains

#### Account Management

- `getTurnkeyAccountData(chains: Chain[]): TurnkeyAccountData | null`
- `setTurnkeyAccountData(data: TurnkeyAccountData | null, chains: Chain[]): void`
- `updateTurnkeyAccountData(updates: Partial<TurnkeyAccountData>, chains: Chain[]): void`
- `getChainManager(chains: Chain[]): ChainManagerService`

## Migration Guide

If you're migrating from the app-specific Turnkey implementation:

1. **Provider changes**: Pass configuration as props instead of importing from `~/env`
2. **Auth hook changes**: Pass server actions and RP name as config parameters
3. **Connector changes**: Pass chains array when creating the connector
4. **Account management**: Pass chains array to account management functions

### Before

```tsx
import { TurnkeyProviderWrapper } from "@/features/turnkey";
import { useTurnkeyAuth } from "@/features/turnkey";

// Provider automatically used env variables
<TurnkeyProviderWrapper>{children}</TurnkeyProviderWrapper>;

// Hook automatically used server actions
const auth = useTurnkeyAuth();
```

### After

```tsx
import { TurnkeyProviderWrapper } from "@otim/turnkey/providers";
import { useTurnkeyAuth } from "@otim/turnkey/hooks";
import { turnkeyLogin, turnkeyVerification } from "@/server/actions";

// Provider needs configuration
<TurnkeyProviderWrapper
  apiBaseUrl={env.PUBLIC_TURNKEY_API_URL}
  defaultOrganizationId={env.PUBLIC_TURNKEY_ORGANIZATION_ID}
>
  {children}
</TurnkeyProviderWrapper>;

// Hook needs configuration
const auth = useTurnkeyAuth({
  rpName: "Your App",
  onLogin: turnkeyLogin,
  onVerification: turnkeyVerification,
});
```

## License

MIT