# @poince/auth

The affordable building blocks for auth, wallets, and payments. From sign-in to CRM.

`@poince/auth` is the React SDK for Poince: sign-in (passkeys, email and SMS codes, social sign-in, Sign-In with
Ethereum and Solana, MFA), embedded wallets on EVM chains and Solana, funding and payments, user attributes and events.
The sign-in UI ships in English, Chinese (Simplified and Traditional), Japanese, Spanish, Portuguese and French, and
every string can be overridden.

Full guides and the API reference: **https://docs.poince.com**

## Install

```bash
pnpm add @poince/auth viem
```

`react` and `react-dom` (18 or 19) and `viem` (2.38.6 or later) are peer dependencies. npm 7+ and pnpm install them
for you; with Yarn v1, add them yourself. The package is ESM only.

### pnpm 10 and later: dependency build scripts

pnpm 10 doesn't run dependencies' install scripts until you approve them, and pnpm 11 stops the install until you
approve or ignore each one. This package pulls in a few: `@reown/appkit` (a version check), `bufferutil`,
`utf-8-validate` and `keccak`. The last three have JavaScript fallbacks, so you can ignore them all.

```bash
pnpm approve-builds
```

## Quick start

Get your app id (25 characters) from the [Poince dashboard](https://dashboard.poince.com), then wrap your app in
`PoinceProvider`. A Next.js Server Component layout is fine: the SDK's entry points are marked `"use client"`.

```tsx
// app/layout.tsx
import type { ReactNode } from "react";
import { PoinceProvider } from "@poince/auth";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <PoinceProvider appId="YOUR_APP_ID_25_CHARACTERS">{children}</PoinceProvider>
      </body>
    </html>
  );
}
```

Open sign-in from a Client Component. `login()` opens the sign-in modal and rejects with the code
`exited_auth_flow` when the user closes it, so catch it:

```tsx
"use client";
import { useLogin, usePoince, PoinceErrorCode, isPoinceClientError } from "@poince/auth";

export function SignIn() {
  const { ready, authenticated, user } = usePoince();
  const { login } = useLogin();

  const signIn = () =>
    login().catch((e) => {
      if (isPoinceClientError(e) && e.code === PoinceErrorCode.USER_EXITED_AUTH_FLOW) return; // closed by the user
      throw e;
    });

  if (!ready) return <button disabled>Loading…</button>;
  return authenticated ? <p>Signed in as {user?.id}</p> : <button onClick={signIn}>Sign in</button>;
}
```

If `ready` never turns true, check the browser console for a `[poince]` message: an app id that doesn't exist keeps
the SDK from loading your app's settings.

## Sign-in in your own page

To show sign-in, wallet connection or the account portal inside your page instead of in a modal, place one of these
components anywhere under `PoinceProvider`:

```tsx
"use client";
import { PoinceSignIn } from "@poince/auth";

export function SignInPanel() {
  return <PoinceSignIn onComplete={({ user }) => console.log("signed in", user.id)} />;
}
```

- `<PoinceSignIn />` shows the sign-in methods your app is set up with. If your app requires MFA, it also runs the MFA
  check, or MFA setup for a user who has none, then calls `onComplete({ user })` and renders nothing, so you choose
  what comes next. It renders nothing for a user who is already signed in.
- `<PoinceConnectWallet />` calls `onComplete({ wallet })` once a wallet is connected.
- `<PoinceAccountPortal />` takes the same options as `openAccountPortal()` (`payment_params`, `tab="accounts"` or
  `"custody"`) and renders while the user is signed in. When those values change it shows the new payment and tab;
  while it is sending a payment, it waits until that payment ends.

Use one of each per page. Each takes the width of its container between 320 and 440px, grows with its content and uses
your page's font, so reserve some height to avoid a layout shift while it loads. All three take `onError`.
`login()` and the other hooks still open the modal, and transaction approvals, wallet export and transaction MFA always
use the modal. A sign-in that leaves your page (a mobile social sign-in redirect) finishes in the modal.

## Light and dark mode

The sign-in UI follows your page's light or dark mode. It reads a `dark` or `light` class, a `data-theme`,
`data-color-scheme`, `data-mode` or `data-bs-theme` of `dark` or `light`, or an inline `color-scheme` style on
`<html>` or `<body>`, and switches when your page does. next-themes, Tailwind's `dark` class and Bootstrap's
`data-bs-theme` need no code.

To choose the scheme yourself, use `useTheme()`:

```tsx
"use client";
import { useTheme } from "@poince/auth";

export function ThemeButtons() {
  const { theme, setTheme } = useTheme(); // theme is the scheme on screen: "light" or "dark"
  return (
    <>
      <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>Toggle theme</button>
      <button onClick={() => setTheme("system")}>Match my device</button>
    </>
  );
}
```

A `setTheme()` call wins for the rest of the page view. It is also remembered on the viewer's device, and on their next
visit it applies when your page carries no light or dark marker. With neither, your app's default theme from the
dashboard applies. `setTheme("system")` follows the device's setting.

## Branding and themes

Colours, surface, corner radius, font, logos and the full theme are set per app in the dashboard, which also lets you
preview a draft theme on your own site with a `?poince_theme_preview=` link before you publish it. To override a value
from your own CSS, set the `--poince-*` custom property on `.poince-styles-wrapper` (a `:root` rule doesn't reach the
sign-in UI). Rules for the in-page components can target `.poince-styles-wrapper[data-poince-mode="embedded"]`.

## Configuration

Sign-in methods and their order, wallets, chains, captcha, legal links and branding come from your app's settings in
the dashboard. The `config` prop covers the few things that belong to your page:

- `intl`: the interface language (`locale`), the default phone country (`defaultCountry`), and your own strings
  (`textLocalization`, `messages`);
- `supportedChains`: narrows the chains your app allows to the ones this page uses (viem `Chain` objects);
- `passkeys.registration`: the `hints` passed when a passkey is created;
- `allowOAuthInEmbeddedBrowsers`: allows social sign-in inside in-app browsers.

A `config` with functions or viem chains that carry formatters (Base, OP) can't be passed from a Server Component: put
the provider in a client file that you import from your layout.

## Content-Security-Policy

If your page sends a Content-Security-Policy, allow:

- `connect-src`: `https://api.poince.com` (or your own API domain, if your plan has one) and `https://cdn.poince.com`,
  where your app's settings and theme are served; the RPC endpoints of the chains you use; and, for WalletConnect,
  `wss://relay.walletconnect.org` and `https://explorer-api.walletconnect.com`;
- `img-src`: `https://cdn.poince.com` (wallet and network icons);
- `frame-src`: `https://verify.walletconnect.org`, and the captcha provider your app uses;
- `script-src`: the captcha provider your app uses;
- `style-src`: the SDK adds `<style>` elements. Under a nonce policy, pass the nonce as `<PoinceProvider nonce={…}>`, or
  expose it as `<meta property="csp-nonce" nonce="…">` (Vite's `html.cspNonce` writes this), `<meta name="sc-nonce">`
  or webpack's `__webpack_nonce__`. With server rendering, give your own styled-components registry the same nonce.

## Errors

SDK errors are classes you can check with guards: `isPoinceApiError` (the Poince API answered with an error; `status`
is the HTTP status, `null` on a network failure), `isPoinceClientError` (the SDK refused or ended a call, such as a
closed modal), `isPoinceConnectorError` (a wallet connection failed) and `isPoinceError` for any of them. Wallet RPC
errors (EIP-1193) are separate, with a numeric `code`.

Branch on `error.code` (the `PoinceErrorCode` values). It can be absent for an error the SDK doesn't recognise, so
fall back to the response body:

```tsx
"use client";
import { isPoinceApiError, useLoginWithEmail } from "@poince/auth";

export function useSendCode() {
  const { sendCode } = useLoginWithEmail();
  return async (email: string) => {
    try {
      await sendCode({ email });
    } catch (e) {
      if (isPoinceApiError(e) && e.status === 429) {
        const wait = (e.data as { retry_after_seconds?: number } | undefined)?.retry_after_seconds;
        console.warn(`Too many attempts; try again in ${wait ?? 60}s`);
        return;
      }
      throw e;
    }
  };
}
```

When the provider can't start (for example an `appId` that isn't a 25-character string, a page served over plain
`http://` other than `localhost` or `127.0.0.1`, a second `PoinceProvider` on the page, or sign-in methods none of
which can be used in this browser, such as a passkey-only app where passkeys aren't supported), it renders a short
diagnostic in place of its children. An app with no sign-in method set up still starts: its sign-in screen tells the
user sign-in isn't available. Pass `providerErrorFallback` to render your own, and
`onProviderError` to report it. These cover only Poince's own failures: an error thrown by your own components inside
`PoinceProvider` reaches your own error boundary unchanged, as it would without Poince. When you contact support,
include the error's `code`, its message and the SDK `VERSION` (exported).

## Entry points

| Import | What it gives you |
| --- | --- |
| `@poince/auth` | `PoinceProvider`, the sign-in, wallet, signing and payment hooks, the in-page components, `useTheme` and `useLocale`, events, errors and their guards |
| `@poince/auth/solana` | Solana signing and wallet hooks (Solana wallets connect automatically when your app enables Solana) |
| `@poince/auth/skin-contract` | The theme token and selector names, for theme authors |
| `@poince/auth/internal` | Used by Poince's own dashboard; not for apps and not covered by semver |

TypeScript resolves the root entry under any `moduleResolution`; the subpaths need `"bundler"`, `"node16"` or
`"nodenext"`. Under Jest, transform `@poince/auth` (it is ESM only).

## Changelog and license

See `CHANGELOG.md` in this package for what changed in each version. `@poince/auth` is commercial software, used under
the terms in `LICENSE` with a Poince account and agreement.
