> ## Documentation Index
> Fetch the complete documentation index at: https://docs.polygon.technology/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript sessions and access

> Restore wallet sessions, create or import wallets, issue backend tokens, and manage direct or remote access.

An active session binds the local credential to one selected wallet. Authentication can return several wallets, but `omsWallet.wallet` exposes one `activeWallet` at a time.

## Read and restore session state

Create `OMSWallet` with the same publishable key and storage configuration on each application load. It restores the saved session right away and refreshes its expiry in the background.

```typescript theme={null}
import { OMSWallet } from '@polygonlabs/oms-wallet'

const omsWallet = new OMSWallet({
  publishableKey: 'YOUR_PUBLISHABLE_KEY',
})

const activeWallet = omsWallet.wallet.activeWallet
const session = omsWallet.wallet.session

if (activeWallet && session) {
  console.log('Restored wallet:', activeWallet.type, activeWallet.address)
  console.log('Session expires:', session.expiresAt)
  console.log('Authentication:', session.auth)
}
```

`wallet.activeWallet` and `wallet.session` are read-only snapshots:

* `activeWallet` is the active `WalletAccount`, with `id`, `type`, `address`, optional `reference`, and `keyOrigin`. It is `undefined` when signed out.
* Narrow on `activeWallet.type` before using the address. Ethereum wallets have a viem `Address`; Solana and Tron addresses are strings.
* `session` contains the current `expiresAt` and the `auth` metadata. It is defined exactly when `activeWallet` is.
* Email auth metadata is `{ type: 'email', email }`.
* OIDC metadata is `{ type: 'oidc', flow, issuer, provider, providerLabel, email }`. Optional provider fields can be `undefined`.

## Understand storage defaults

Browser defaults use separate storage for completed sessions and pending redirects:

* Completed session metadata uses `localStorage`.
* The default non-extractable WebCrypto P-256 signer stores its credential in IndexedDB.
* Temporary OIDC verifier and state data use `sessionStorage`.

Outside a browser, completed session metadata defaults to in-memory storage, so it does not survive a process restart. Redirect storage has no non-browser default. Pass `redirectAuthStorage` before calling any redirect auth method, and make sure it remains available to the callback process.

For a non-browser runtime, provide application-owned implementations of the public `StorageManager` and `CredentialSigner` interfaces through the `storage`, `redirectAuthStorage`, and `credentialSigner` constructor options. See the [package API reference](https://docs.polygon.technology/wallets/sdk/typescript/api-reference.md) for their exact contracts.

For the redirect convenience wrapper outside a browser, pass `currentUrl` and `assignUrl`. On completion, pass `callbackUrl`; either keep `cleanUrl: false` or provide `replaceUrl` when URL cleanup is required. An in-memory redirect store is suitable only when both stages run in the same process. See [authentication](https://docs.polygon.technology/wallets/sdk/typescript/authentication.md#control-browser-routing-directly) for the lower-level browser flow.

## Create the wallet once per project

In a browser, creating `OMSWallet` again for the same project and environment returns the same wallet, so React StrictMode, hot reloads, or one instance per screen all share one session. A rotated publishable key for the same project keeps the session.

Outside a browser, each instance keeps its own in-memory session, such as one per user on a server, unless you pass the same `storage`. Instances that share a `storage` must also share their `credentialSigner` and `redirectAuthStorage`; otherwise the constructor throws `OMSWalletValidationError`.

## Keep your UI in sync

A session stays active while it is used. It ends after about 10 days without use, or at the lifetime requested at sign-in (180 days by default). `session.expiresAt` is the current expiry, and the SDK keeps it up to date; `credential.expiresAt` in an auth result is the expiry at sign-in.

When the session ends, protected operations throw `OMSWalletSessionError` with code `OMS_SESSION_EXPIRED`. If the wallet API cannot be reached, the SDK keeps the session and the operation fails with a request error.

`onSessionChange` calls your listener after every change of `activeWallet` or `session`. Subscribe first, then read the current state, so no change is missed:

```typescript theme={null}
const unsubscribe = omsWallet.wallet.onSessionChange((event) => {
  render(event.activeWallet, event.session)

  if (event.reason === 'expired') {
    showSignIn(event.expiredSession.session.auth)
  }
})
render(omsWallet.wallet.activeWallet, omsWallet.wallet.session)

// Call during application or component cleanup.
unsubscribe()
```

| `reason` | Meaning |
| - | - |
| `signedIn` | A sign-in made a wallet active |
| `walletChanged` | Another wallet of the same sign-in became active |
| `expiryUpdated` | `session.expiresAt` moved; safe to ignore unless you show it |
| `signedOut` | The session ended without expiring, for example `signOut()` or a new sign-in starting while signed in |
| `expired` | The session expired; `expiredSession` has its wallet and authentication for signing in again |

After a reload, a new listener first receives the last `expired` change until the user signs in again or signs out.

Tabs of your app share the session: a sign-in, wallet switch, or sign-out in one tab is applied in the others, which receive the same change.

In React, `useSyncExternalStore` keeps a component in sync; `activeWallet` and `session` return the same object until they change:

```typescript theme={null}
function useOMSWalletSession(wallet: WalletClient) {
  const subscribe = useCallback((onChange: () => void) => wallet.onSessionChange(onChange), [wallet])
  const activeWallet = useSyncExternalStore(subscribe, () => wallet.activeWallet)
  const session = useSyncExternalStore(subscribe, () => wallet.session)
  return { activeWallet, session }
}
```

## List and activate wallets

List every wallet available to the authenticated credential:

```typescript theme={null}
const wallets = await omsWallet.wallet.listWallets()

for (const wallet of wallets) {
  console.log(wallet.id, wallet.type, wallet.address, wallet.keyOrigin)
}
```

`listWallets` works with an active session and while manual auth selection is pending. After normal automatic auth, switch the active wallet with its server-side ID:

```typescript theme={null}
const wallet = wallets[0]

if (wallet) {
  const active = await omsWallet.wallet.useWallet({ walletId: wallet.id })
  console.log('Now active:', active.wallet.address)
}
```

`useWallet` requires an active session and preserves its credential expiry and auth metadata. If auth returned `PendingWalletSelection`, call `selection.selectWallet` instead.

## Create and activate another wallet

```typescript theme={null}
const active = await omsWallet.wallet.createWallet({
  reference: 'treasury',
})

console.log(active.wallet.id, active.wallet.address)
```

`createWallet` creates an Ethereum wallet by default and immediately makes it active. A pending manual selection must use `selection.createAndSelectWallet` instead.

Create a Solana or Tron wallet by setting `walletType` explicitly:

```typescript theme={null}
import { WalletType } from '@polygonlabs/oms-wallet'

const solana = await omsWallet.wallet.createWallet({
  walletType: WalletType.Solana,
  reference: 'solana-primary',
})

const tron = await omsWallet.wallet.createWallet({
  walletType: WalletType.Tron,
  reference: 'tron-primary',
})
```

Each call activates the wallet it creates, so the second call leaves the Tron wallet active.

## Claim a preallocated wallet

A completed sign-in result lists, in `claimableWallets`, the wallets your project preallocated for the user's email that the sign-in did not claim. See [authentication](https://docs.polygon.technology/wallets/sdk/typescript/authentication.md#claim-a-preallocated-wallet) for how wallets become claimable. Claim one with `claimWallet`:

```typescript theme={null}
const result = await omsWallet.wallet.completeEmailAuth({ code: '123456' })

const [claimable] = result.claimableWallets
if (claimable) {
  const active = await omsWallet.wallet.claimWallet({ walletId: claimable.id })
  console.log('Claimed:', active.wallet.type, active.wallet.address)
}
```

`claimWallet` requires an active session and makes the claimed wallet active, like `useWallet`. A pending manual selection must use `selection.claimAndSelectWallet` instead.

## Import and activate a wallet

`importWallet` validates and encrypts private-key material locally, sends only the encrypted material through the attested import transport, and activates the imported wallet:

```typescript theme={null}
import { WalletKeyOrigin, WalletType } from '@polygonlabs/oms-wallet'

const imported = await omsWallet.wallet.importWallet({
  type: WalletType.Ethereum,
  privateKey: '0x...', // Supply the private key from your secure migration flow.
  reference: 'imported-wallet',
})

console.log(imported.wallet.keyOrigin === WalletKeyOrigin.Imported)
```

Ethereum and Tron (`type: 'tron'`) imports take a private key as 32 bytes or a hex string. Solana imports take a 32-byte seed or 64-byte keypair, as bytes or base58. The SDK never stores the plaintext key. `WalletAccount.keyOrigin` tells you whether a wallet was created by OMS or imported.

Attestation failures throw an SDK error with code `OMS_ATTESTATION_VERIFICATION_FAILED`.

> [!WARNING]
>
> Development uses Nitro debug-mode attestation. Use only disposable test keys in Development. Staging and Production verify against SDK-pinned enclave measurements.

## Issue an ID token for your backend

`getIdToken` asks OMS Wallet to issue an ID token that proves the active wallet session to your backend.

```typescript theme={null}
const idToken = await omsWallet.wallet.getIdToken({
  ttlSeconds: 300,
  customClaims: { purpose: 'checkout' },
})
```

This token is OMS Wallet output. It is distinct from the provider-issued ID token passed into `signInWithOidcIdToken` during authentication. Treat client-supplied custom claims as untrusted context unless your backend independently controls or validates them. See [backend wallet verification](https://docs.polygon.technology/wallets/sdk/guides/backend-wallet-verification.md).

## Review and revoke access

`listAccess` follows all service pages and returns direct or remote grants for the active wallet. Use `listAccessPages` when you want page-at-a-time rendering, or `listAccessPage` to read one page and resume later from its `page.cursor`. Narrow on `type` before reading remote-session fields.

```typescript theme={null}
const grants = await omsWallet.wallet.listAccess()

for (const grant of grants) {
  console.log(grant.credentialId, grant.expiresAt, grant.isCaller)
  if (grant.type === 'remote') {
    console.log(grant.sessionId, grant.metadata, grant.grants)
  }
}

for await (const page of omsWallet.wallet.listAccessPages({ pageSize: 25 })) {
  console.log(page.grants)
}

const firstPage = await omsWallet.wallet.listAccessPage({ pageSize: 25 })
const nextPage = firstPage.page?.cursor
  ? await omsWallet.wallet.listAccessPage({
      pageSize: 25,
      cursor: firstPage.page.cursor,
    })
  : undefined
```

Revoke only a credential that is not the caller for the current session:

```typescript theme={null}
const revocableGrant = grants.find((grant) => !grant.isCaller)

if (revocableGrant) {
  await omsWallet.wallet.revokeAccess({
    credentialId: revocableGrant.credentialId,
    sessionId:
      revocableGrant.type === 'remote'
        ? revocableGrant.sessionId
        : undefined,
  })
}
```

> [!WARNING]
>
> Do not offer `revokeAccess` for a grant whose `isCaller` field is `true`. It represents the credential making the current request. Revocation is permanent for the target grant.

## Authorize remote access

Remote access grants are bounded EVM smart sessions. Inspect the remote credential and show its returned metadata to the wallet owner before requesting approval:

This example uses Polygon Amoy. Grant limits are raw EVM base-unit amounts. A native-transfer limit is cumulative, so `1_000_000_000_000_000` wei authorizes up to `0.001 POL` across the session.

```typescript theme={null}
import { Networks } from '@polygonlabs/oms-wallet'

const credentialId = 'REMOTE_CREDENTIAL_ID'
const metadata = await omsWallet.wallet.inspectRemoteCredential({ credentialId })

// Render the returned metadata in your consent UI and continue only after approval.
console.log(metadata.appName, metadata.appUrl)

const session = await omsWallet.wallet.authorizeRemoteAccess({
  credentialId,
  network: Networks.amoy,
  expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
  grants: [
    {
      kind: 'nativeTransfer',
      to: '0x1111111111111111111111111111111111111111',
      // Cumulative 0.001 POL limit in wei.
      limit: 1_000_000_000_000_000n,
    },
  ],
})

const details = await omsWallet.wallet.getRemoteAccessSession({
  sessionId: session.sessionId,
})
const usage = await omsWallet.wallet.getRemoteAccessSessionUsage({
  sessionId: session.sessionId,
  network: Networks.amoy,
})
```

Pass the remote grant's `credentialId` and `sessionId` to `revokeAccess` to revoke that specific session. WaaS caps the requested session expiry at the remote credential's expiry.

A wallet can have up to 100 active remote sessions by default. At the limit, `authorizeRemoteAccess` fails with `OMSWalletRequestError` (`upstreamError.code` `'7208'`); revoke a session the wallet no longer needs, then try again.

## Operate a remote session from a backend

TypeScript also exports `RemoteAccessClient` for a remote application's backend. The backend owns and registers a persistent credential, reconciles the sessions approved for it, and prepares and executes transactions within each session's grants. This backend credential and the application workflow are separate from the wallet owner's active SDK session.

> [card] [Manage smart sessions from a backend](https://docs.polygon.technology/wallets/sdk/guides/backend-smart-sessions.md)
>
> Set up the persistent signer, owner approval handoff, application storage, backend session reconciliation, remote execution, revocation, and credential rotation.

See the [TypeScript API reference](https://docs.polygon.technology/wallets/sdk/typescript/api-reference.md) for the exact `RemoteAccessClient` contracts.

## Sign out locally

```typescript theme={null}
await omsWallet.wallet.signOut()
```

`signOut` clears the local session record, pending auth state, active wallet, and local credential signer where supported. It does not call the OMS service and does not revoke server-side access grants. Use `revokeAccess` separately for other grants before signing out when your account-management flow requires revocation.
