# @startbahn/startrail-sdk-js

> Startrail Api for JS SDK

Latest version **2.3.1** (published 2026-10-06) · UNLICENSED license · 0 weekly downloads

## Install

```sh
npm install @startbahn/startrail-sdk-js
pnpm add @startbahn/startrail-sdk-js
yarn add @startbahn/startrail-sdk-js
bun add @startbahn/startrail-sdk-js
```

## Health

**Score 65/100 (B)** — status: active.

Positive: has types; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads; no esm support.

## Facts

| | |
|---|---|
| Version | 2.3.1 |
| Published | 2026-10-06 |
| First published | 2020-08-21 |
| Weekly downloads | 0 |
| License | UNLICENSED |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | ^22.18.0 \|\| >=24.11.0 |
| Dependencies | 8 |
| Unpacked size | 2 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Startbahn, Inc. |
| Maintainers | startbahninc, nobari |
| Keywords | javascript |

## Links

- npm: https://www.npmjs.com/package/@startbahn/startrail-sdk-js
- Repository: https://github.com/startbahn/startrail-sdk-js
- Homepage: https://github.com/startbahn/startrail-sdk-js#readme
- Issues: https://github.com/startbahn/startrail-sdk-js/issues
- npm.io page: https://npm.io/package/@startbahn/startrail-sdk-js

## Dependencies (8)

- [flat](https://npm.io/package/flat.md) ^6.0.1
- [axios](https://npm.io/package/axios.md) ^1.20.0
- [ethers](https://npm.io/package/ethers.md) ~6.17.0
- [globalthis](https://npm.io/package/globalthis.md) ^1.0.4
- [@ethereumjs/util](https://npm.io/package/@ethereumjs/util.md) ~10.1.3
- [@vercel/analytics](https://npm.io/package/@vercel/analytics.md) ^2.0.1
- [@toruslabs/torus-embed](https://npm.io/package/@toruslabs/torus-embed.md) 7.0.0
- [@metamask/detect-provider](https://npm.io/package/@metamask/detect-provider.md) ^2.0.0

## Recent versions

- 2.3.1 (latest) — 2026-10-06
- 2.0.0-beta.5 (next) — 2025-11-11
- 2.3.0 — 2026-09-15
- 2.2.0 — 2026-06-15
- 2.1.0 — 2026-06-15
- 2.0.4 — 2026-02-18
- 2.0.2 — 2026-02-13
- 2.0.1 — 2026-02-13
- 2.0.0 — 2026-02-11
- 2.0.0-beta.4 — 2025-11-11
- 2.0.0-beta.3 — 2025-11-11
- 2.0.0-beta.2 — 2025-11-11
- 2.0.0-beta.1 — 2025-10-30
- 2.0.0-beta.0 — 2025-10-30
- 1.36.0 — 2025-08-15
- … 152 more at https://npm.io/package/@startbahn/startrail-sdk-js/versions

## README

# @startbahn/startrail-sdk-js

[![npm version](https://img.shields.io/npm/v/@startbahn/startrail-sdk-js.svg)](https://www.npmjs.com/package/@startbahn/startrail-sdk-js)
[![types](https://img.shields.io/badge/types-included-blue.svg)](./types/startrail-sdk-js.d.ts)
[![live playground](https://img.shields.io/badge/playground-sdk.startrail.io-4a156c.svg)](https://sdk.startrail.io/)

The browser SDK for the **Startrail** platform. It signs a user in with a wallet — **Startrail**
(social / email login, powered by Torus) or **MetaMask** — and signs Startrail meta-transactions on
their behalf: minting Startrail Records (SRRs), managing collections, transferring ownership with
provenance, and reading royalties. One class, full TypeScript types, no framework required.

<p align="center">
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/default-light-dark.webp" alt="The SDK's login modal in light and dark mode" width="760">
</p>

```ts
import { Startrail } from '@startbahn/startrail-sdk-js'

const sdk = new Startrail({ env: 'staging', apiPath: 'https://api-stg.startrail.startbahn.jp/api/v1' })
const eoas = await sdk.login()          // opens the wallet sign-in; EOA[] | false
if (eoas) await sdk.createSRR({ /* … */ })
```

> **Try it without installing anything:** **[sdk.startrail.io](https://sdk.startrail.io/)** hosts
> the playground described below — sign in with a test account, brand the login modal, and run
> every SDK method against the live QA / staging environments from your browser.

> **Using an AI coding tool?** A machine-readable API reference lives in [`llms.txt`](./llms.txt)
> and a short agent how-to in [`AGENTS.md`](./AGENTS.md).

## Contents

- [How it works](#how-it-works)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Configuration](#configuration)
- [Environments](#environments)
- [Authentication](#authentication)
- [Login modal](#login-modal)
- [Custom UI](#custom-ui)
- [API reference](#api-reference)
- [Errors](#errors)
- [Demo playground](#demo-playground)
- [Development](#development)
- [Resources](#resources)

---

## How it works

1. **Construct** — `new Startrail(config)` picks the environment, the wallet backend and the UI
   options. Construction is cheap and does nothing on the network.
2. **Log in** — `await sdk.login()` opens the wallet flow. With the Startrail wallet the user picks a
   social provider or enters an email in the SDK's own [login modal](#login-modal); with MetaMask the
   extension asks to connect. It resolves with the user's EOA addresses.
3. **Act** — call an action such as `createSRR()`. The SDK asks the wallet to sign a
   meta-transaction and submits it to the Startrail API through the **Licensed User Wallet (LUW)**
   contract you pass as `startrailLUWContractAddress`. Write actions log the user in first if needed.

Every action resolves to **its result**, or to **`false`** when nothing happened because the user
cancelled a wallet popup (or one was already open). Real failures **throw** a typed
[error](#errors). Never treat `false` as data.

## Requirements

- **Browser only.** The SDK opens wallet popups and renders into the DOM; it does not run in Node.
  Supported browsers: Chrome 67+, Edge 79+, Firefox 68+, Safari 14+, Opera 54+.
- A **Startrail API** endpoint and a **LUW contract address** for your organisation, provided by
  Startbahn.
- For the Startrail wallet, third-party cookies must be allowed for the wallet iframe (the SDK throws
  `TORUS_THIRD_PARTY_COOKIES_UNSUPPORTED` otherwise). For MetaMask, the extension must be installed.

## Installation

```sh
pnpm add @startbahn/startrail-sdk-js
# or
npm install @startbahn/startrail-sdk-js
# or
yarn add @startbahn/startrail-sdk-js
```

```ts
import { Startrail, METADATA_VALIDATION_FAILED } from '@startbahn/startrail-sdk-js'
```

The package ships a single UMD bundle (`dist/startrail-sdk.js`) plus bundled type declarations
(`types/startrail-sdk-js.d.ts`), so it works with any bundler and in plain script tags. With a
script tag the class is available as the global `Startrail`:

```html
<script src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js"></script>
<script>
  const sdk = new Startrail({ env: 'staging' })
</script>
```

## Quick start

```ts
import { Startrail } from '@startbahn/startrail-sdk-js'

const sdk = new Startrail({
  env: 'staging',                                              // network + wallet accounts
  apiPath: 'https://api-stg.startrail.startbahn.jp/api/v1',    // Startrail API for that env
  lang: 'en',
  customUi: { serviceName: 'My Gallery', logoUrl: 'https://my.gallery/logo.png' },
})

// 1. Sign the user in (opens the wallet flow)
const eoas = await sdk.login()
if (!eoas) return                                 // user closed the modal — not an error

// 2. Who is this?
const user = await sdk.getUserInfo()              // { email, name, profileImage, … } | false

// 3. Do something — mint a Startrail Record
const res = await sdk.createSRR({
  isPrimaryIssuer: true,
  artistAddress: '0xArtist…',
  lockExternalTransfer: false,
  metadata: { /* SRR metadata, validated against the schema */ },
  startrailLUWContractAddress: '0xLUW…',
})
if (res) console.log(res.tx.tokenId, res.txReceiptId)
```

Success responses carry a `txReceiptId` (or `batchId`). The on-chain state change is asynchronous —
poll the Startrail API with that id when you need confirmation.

## Configuration

`new Startrail(config?)` — every field is optional.

| Field | Type | Default | Description |
|---|---|---|---|
| `env` | `'production' \| 'staging' \| 'lrc' \| 'local'` | `'production'` | Blockchain network and wallet accounts. See [Environments](#environments). |
| `apiPath` | `string` | production API | Startrail API base URL. **Not derived from `env`** — pass the staging / QA URL when you use those environments. |
| `wallet` | `'startrail' \| 'metamask'` | `'startrail'` | Wallet backend. `startrail` is the social / email wallet; `metamask` uses the browser extension. |
| `lang` | `'en' \| 'ja'` | `'en'` | Language of the login modal and wallet UI. |
| `loginProvider` | `LoginProvider[]` | all providers | Providers offered at login. One provider logs in directly; two or more open the [login modal](#login-modal). |
| `loginHint` | `string` | — | The user's email when you already know it. With `['email_passwordless']` as the only provider the modal is skipped and login goes straight through. |
| `authAction` | `{ login: boolean; signup: boolean }` | both `true` | Restricts the email/password popup to a single tab and adjusts wording ("Login" vs "Sign up"). |
| `customUi` | `CustomUi` | — | Logo, service name, wording and the login-modal theme. See [Custom UI](#custom-ui). |
| `confirmationStrategy` | `'modal' \| 'popup' \| 'default'` | `'modal'` | Where wallet sign confirmations render. `modal` (inside the wallet iframe) is immune to popup blockers; `popup` opens a separate window; `default` is an alias for the SDK default, `modal`. |
| `rpcEndpoint` | `string` | per `env` | Custom JSON-RPC endpoint. |
| `chainId` | `number` | per `env` | Custom chain id. Requires `rpcEndpoint`. |
| `auth0TorusConfigKey` | `string` | per `env` | Auth0 ↔ Torus config key for the email/password connection. Only override when Startbahn gives you one. |
| `callbackUrl` | `string` | — | URL the signup verification email links back to. |
| `debug` | `boolean` | `false` | Verbose SDK logging in the console (init / login / logout / signing steps). |
| `withModal` | `boolean` | — | Deprecated, no effect: the SDK's modal opens whenever `loginProvider` offers a choice. |
| `mfaLevel`, `torusBuildEnv` | — | — | Deprecated, no effect. Use `env`. |

`LoginProvider` is one of `'google'`, `'apple'`, `'facebook'`, `'twitter'` (X), `'line'`,
`'email_passwordless'`, `'email_password'`.

## Environments

`env` selects the chain and the wallet network. It does **not** select the API — set `apiPath`.

| `env` | Chain | Chain id | Wallet network | `apiPath` to use |
|---|---|---|---|---|
| `production` | Polygon Mainnet | 137 | mainnet | `https://api.startrail.io/api/v1` (default) |
| `staging` | Polygon Amoy testnet | 80002 | mainnet | `https://api-stg.startrail.startbahn.jp/api/v1` |
| `lrc` | Polygon Amoy testnet | 80002 | testnet | `https://api-qa.startrail.startbahn.jp/api/v1` |
| `local` | `localhost:8545` | 5777 | testnet | your local API |

Public RPC endpoints are tried in order and the first live one is used; pass `rpcEndpoint` to pin
your own.

## Authentication

### The Startrail wallet

```ts
// Let the user choose: opens the login modal with the configured providers
await sdk.login()

// A single provider skips the modal and opens that provider directly
const sdk = new Startrail({ loginProvider: ['google'] })

// Email passwordless with a known address: no modal, no typing
const sdk = new Startrail({ loginProvider: ['email_passwordless'], loginHint: 'user@example.com' })

// Per-call overrides
await sdk.login({ loginProvider: ['apple'], lang: 'ja' })

// Switch user: end whatever session exists, then sign in with these options
await sdk.login({ loginProvider: ['google'], forceLogin: true })
```

`login()` resolves with the EOA addresses, or `false` if the user closed the modal or the wallet
window. A session persists inside the wallet iframe: calling `login()` on a later page load (or a
new SDK instance) restores it without a prompt. That also means `login({ loginProvider: ['google'] })`
while someone is already signed in returns *their* accounts and never shows Google — pass
`forceLogin: true` to end the current session first (the same as `logout()` then `login()`, in one
call, with the override honoured). Because the iframe needs a moment to rehydrate, the
SDK waits for it before ever showing the picker — the modal opens in a *"Checking for an existing
session…"* state and closes itself when the session lands. To know how long to wait, the SDK keeps
a timestamp (no addresses) under `localStorage['startrail-sdk:torus-session']` on your origin after
each successful login and removes it on `logout()`.

### MetaMask

```ts
const sdk = new Startrail({ wallet: 'metamask', env: 'staging' })
const eoas = await sdk.login()   // asks MetaMask to connect and to switch to (or add) the chain for `env`
```

MetaMask users can switch accounts in the extension at any time. The SDK remembers the EOA that
logged in and throws `WALLET_EOA_NOT_MATCH` if a later call is made from a different one — compare
`login()`'s result with what your app expects.

`logout()` disconnects the site from MetaMask (it revokes the accounts permission granted on
connect), so the next `login()` — or `login({ forceLogin: true })` — opens MetaMask's account picker
again instead of silently reconnecting the previous account. Where MetaMask cannot revoke (MetaMask
Mobile, older extensions) the SDK re-requests the permission on that next `login()` instead, which
prompts as well.

### Session helpers

| Method | Returns | Notes |
|---|---|---|
| `logout()` | `void \| false` | Ends the wallet session. A following `login()` on the same instance prompts fresh, so users can switch accounts. |
| `getUserInfo()` | `UserInfo \| false` | `{ email, name, profileImage, typeOfLogin, … }`. Logs in first if needed. |
| `switchLanguage(lang)` | `void \| false` | Switches the wallet UI to `'en'` or `'ja'`. |
| `signMessage(message, disableCustomPrefix?)` | `MessageSignature \| false` | Signs a UTF-8 message. Pass `true` to use `personal_sign` (recommended); the default `eth_sign` with a custom prefix is kept for backward compatibility. |

## Login modal

When `loginProvider` offers a choice (or `email_passwordless` is used without a `loginHint`), `login()`
opens the SDK's own provider picker. It renders in a Shadow DOM, so your page's CSS never affects it
and its CSS never leaks out. Out of the box it is **brand-neutral** — a near-black accent on a white
card in light mode, inverted on a dark card in dark mode — and every visible part of it is yours to
configure.

### Brand it

One `customUi` block brands the modal *and* the wallet UI it hands off to. Both examples below are
the same component — PORT with pill-shaped, filled buttons; Acme with its logo inline beside a
left-aligned title:

<p align="center">
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/brand-port-light-dark.webp" alt="The modal themed for PORT: purple accent, pill-shaped filled buttons, light and dark mode" width="760">
  <br>
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/brand-acme-light-dark.webp" alt="The modal themed for Acme Gallery: orange accent, circular logo inline beside a left-aligned title, custom font and wording, light and dark mode" width="760">
</p>

```ts
const sdk = new Startrail({
  customUi: {
    serviceName: 'Acme Gallery',                         // "to continue to Acme Gallery"; wallet app name
    logoUrl: 'https://acme.example/logo.png',            // shown on light backgrounds
    logoWhiteUrl: 'https://acme.example/logo-white.png', // shown in dark mode
    theme: {
      mode: 'auto',              // 'light' (default) | 'dark' | 'auto' (follows prefers-color-scheme)
      accent: '#ff5a1f',         // primary button, links, focus rings — text colour is chosen for contrast
      accentDark: '#ffb48f',     // optional dark-mode accent
      fontFamily: "'Avenir Next', 'Segoe UI', system-ui, sans-serif",
      borderRadius: 10,          // dialog corners in px (0–40)
      controlRadius: '50%',      // buttons and inputs: px (0–24), or '50%' for pills
      logoPlacement: 'inline',   // 'top' (default) | 'inline' (beside the title) | 'none'
      logoSize: 40,              // logo box in px (24–120)
      logoShape: 'circle',       // 'rounded' (default) | 'circle' | 'square' | 'plain' (no frame — wordmarks)
      buttonStyle: 'filled',     // provider buttons: 'outline' (default) | 'filled' | 'accent'
      align: 'left',             // title, logo and footer: 'center' (default) | 'left'
    },
    words: {
      en: { modal: { title: 'Welcome to Acme', subtitle: 'Sign in to manage your collection', privacyPolicy: 'Privacy notice' } },
      ja: { modal: { title: 'Acme へようこそ', subtitle: 'ログインしてコレクションを管理' } },
    },
  },
})
```

| `customUi.theme` | Default | What it does |
|---|---|---|
| `mode` | `'light'` | `'dark'`, or `'auto'` to follow the visitor's `prefers-color-scheme`. |
| `accent` | near-black | Primary button, links and focus rings. Text on it is picked by WCAG luminance (`#ffcc00` gets dark text, `#4a156c` gets white); hover and pressed tints are derived, so one colour is enough. |
| `accentDark` | derived | Accent in dark mode. Defaults to `accent`; a near-black accent inverts to a light neutral instead of vanishing on the dark card. |
| `fontFamily` | Inter / Noto Sans JP | Typeface for the whole modal, with system fallbacks. |
| `borderRadius` | `20` | Dialog corner radius in px (0–40); buttons and inputs follow it, capped at 12. |
| `controlRadius` | follows `borderRadius` | Radius of buttons and inputs in px (0–24), or `'50%'` for fully rounded, pill-shaped controls. |
| `logoPlacement` | `'top'` | `'top'` centres the logo above the title, `'inline'` puts it beside the title on one row, `'none'` hides it. |
| `logoSize` | `48` | Size of the logo box in px (24–120); the artwork and corner radius scale with it. |
| `logoShape` | `'rounded'` | Frame around the logo: `'rounded'`, `'circle'`, `'square'`, or `'plain'` for the artwork alone at `logoSize` height — for wordmarks and wide logos. |
| `buttonStyle` | `'outline'` | Provider buttons: `'outline'` (border), `'filled'` (tinted surface, no border) or `'accent'` (solid brand colour with contrasting text and icons). |
| `align` | `'center'` | Alignment of the title, subtitle, logo and footer links; `'left'` reads well with `logoPlacement: 'inline'`. |

| Wording (`customUi.words[lang].modal`) | Default |
|---|---|
| `title` | "Login" or "Sign up", from `authAction` ("ログイン" / "登録" in Japanese) |
| `subtitle` | "to continue to *serviceName*" |
| `termsConditions`, `privacyPolicy` | Labels of the two footer links |
| `termsConditionsLinkUrl`, `privacyPolicyLinkUrl` | Their targets (default: Startrail's terms and privacy policy) |

Provider buttons ("Continue with Google" / "Googleで続ける") and status messages are localised
automatically from `lang`. `theme.mode` and `theme.accent` are also forwarded to the wallet iframe
(`whiteLabel.mode` / `whiteLabel.theme.primary`), so confirmation popups match — only when configured.

### The sign-in flow

<p align="center">
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/flow-waiting-cancelled-error.webp" alt="Waiting for the wallet window, sign-in cancelled with a retry notice, and sign-in failed with the error message" width="900">
</p>

0. **Existing session?** — on a fresh page load the modal first shows *"Checking for an existing
   session…"*; if the wallet restores one, the modal closes and `login()` resolves without a click.
1. **Pick a provider** — the modal shows a *waiting* view ("Continue in the Google window") while the
   wallet finishes the login in its own window, and mentions blocked pop-ups if nothing appears.
2. **Success** — the modal closes itself and `login()` resolves with the EOAs.
3. **Cancelled** — if the user closes the wallet window, the picker comes back with an inline notice
   and they can choose again. `login()` stays pending; your app is not involved.
4. **Failed** — a real wallet error is shown inline (and logged with `console.error`); the user can
   retry.
5. **Closed** — the × button or <kbd>Esc</kbd> dismisses the modal and `login()` resolves to `false`.
   Clicking the backdrop nudges the dialog instead of closing it, so an accidental click doesn't
   cancel a sign-in.

### Email passwordless

<p align="center">
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/email-validation-and-hint.webp" alt="Inline email validation, and the email-only modal pre-filled from loginHint" width="760">
</p>

With `email_passwordless` in `loginProvider` the picker ends with an email field — no password, the
wallet verifies the address by email. Validation is inline; `loginHint` pre-fills the address, and
when `email_passwordless` is the *only* provider the modal is skipped entirely.

### Mobile, languages and accessibility

<p align="center">
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/mobile-light-dark.webp" alt="The modal as a bottom sheet on a phone, light and dark" width="560">
  <img src="https://cdn.jsdelivr.net/npm/@startbahn/startrail-sdk-js/docs/images/login-modal/japanese.webp" alt="The modal in Japanese" width="280">
</p>

- Below 480px the dialog becomes a bottom sheet with safe-area padding; on short viewports it
  scrolls instead of clipping.
- `lang: 'ja'` switches every string, the font stack (Noto Sans JP / Hiragino) and typography rules.
- `role="dialog"` / `aria-modal`, labelled by the title; focus moves into the dialog on open, is
  trapped while it is open, and returns to the opener on close; notices are announced via live
  regions; page scroll is locked; `prefers-reduced-motion` disables the transitions.
- No network requests of its own — provider icons are inline SVG, so it works under a strict CSP.

### Per-site CSS overrides

For tweaks beyond `customUi.theme`, CSS custom properties on the modal's container win over the
configured theme:

```css
#torus-social-login-modal-container {
  --startrail-modal-accent: #4a156c;
  --startrail-modal-on-accent: #fff;
  --startrail-modal-accent-ring: rgba(74, 21, 108, 0.22);
  --startrail-modal-font: 'Inter', sans-serif;
  --startrail-modal-radius: 20px;
  --startrail-modal-z-index: 9999;   /* keep below the wallet iframe (99999) */
}
```

Try all of the above live in the **Brand the login modal** section of the playground at
[sdk.startrail.io](https://sdk.startrail.io/): pick a preset or tune every option, copy the generated
`new Startrail(config)`, and press **Preview** to open the real modal.

## Custom UI

`customUi` covers everything the user sees with your brand on it — the login modal above, the
wallet's email/password popup, its sign-confirmation popup and the embedded wallet widget.

```ts
const sdk = new Startrail({
  customUi: {
    serviceName: 'Your service',
    logoUrl: 'https://…/logo.png',            // dark artwork for light backgrounds
    logoWhiteUrl: 'https://…/logo-white.png', // light artwork for dark backgrounds
    contactUrl: 'contact@your-service.example',
    verificationEmailTitle: 'Verify your Your-service account',
    theme: { /* see Login modal */ },
    words: {
      en: {
        modal: {
          continueLogin: 'Continue with existing {verifier}',   // wallet UI; {verifier} = provider name
          title: '…', subtitle: '…',
          termsConditions: '…', termsConditionsLinkUrl: '…', privacyPolicy: '…', privacyPolicyLinkUrl: '…',
        },
        signPopup: { title: '…', requestFrom: '…', dataToSign: '…', confirm: 'Confirm', cancel: 'Cancel' },
        emailAuthPopup: { titleLogin: 'Log in', titleSignup: 'Sign up' },
        embed: { continue: '…', actionRequired: '…', pendingAction: '…' },
      },
      ja: { /* same keys */ },
    },
  },
})
```

Every group is optional and falls back to the SDK's EN/JA defaults. Note the types: when you supply `modal`, `continueLogin` is required; `embed` and `emailAuthPopup` require all of their keys.

## API reference

All methods are `async` and live on the `Startrail` instance. Write actions log the user in first if
needed, and resolve to their result **or `false`** when the user cancelled a wallet popup (or one was
already open). `startrailLUWContractAddress` — the Licensed User Wallet contract the
meta-transaction is proxied through — is required by every write action. Addresses are
checksummed hex; royalties are in basis points (`1000` = 10%).

### Session

| Method | Returns |
|---|---|
| `login(overwrite?)` | `EOA[] \| false` — `overwrite` may set `authAction`, `lang`, `loginProvider`, `loginHint`; `forceLogin: true` ends any existing session first so those are honoured. |
| `logout()` | `void \| false` |
| `getUserInfo()` | `UserInfo \| false` |
| `signMessage(message, disableCustomPrefix?)` | `MessageSignature \| false` — `{ signature, prefix }` |
| `switchLanguage(lang)` | `void \| false` |

### Collections

```ts
// Deploy a new collection (ERC-721) contract
await sdk.createCollection({ name: 'My Collection', symbol: 'MYC', startrailLUWContractAddress: '0xLUW…' })
// → { txReceiptId, tx: { contractAddress, salt } } | false

// Transfer collection ownership
await sdk.transferCollectionOwnership({ contractAddress: '0xCollection…', newOwner: '0xNewOwner…', startrailLUWContractAddress: '0xLUW…' })
// → { txReceiptId, tx: { contractAddress } } | false
```

### Startrail Records (SRRs)

```ts
// Mint. `contractAddress` targets a custom collection; omit it for the default contract.
await sdk.createSRR({
  isPrimaryIssuer: true,
  artistAddress: '0xArtist…',
  lockExternalTransfer: false,        // true = transfers only within Startrail
  metadata: { /* validated against the SRR metadata schema */ },
  startrailLUWContractAddress: '0xLUW…',
  contractAddress: '0xCollection…',   // optional
})
// → { txReceiptId, tx: { tokenId, metadataCID, contractAddress? } } | false

// Update metadata
await sdk.updateMetadata({ tokenId: '123', metadata: { /* … */ }, startrailLUWContractAddress: '0xLUW…' })
// → { txReceiptId } | false

// Transfer to an Ethereum address, recording provenance
await sdk.transferSRRToEthereumAddress({
  to: '0xRecipient…',
  tokenId: '123',
  metadata: { transferType: 'Primary sale', remarks: { en: '…', ja: '…' } },   // HistoryMetadata
  isIntermediary: false,
  startrailLUWContractAddress: '0xLUW…',
})
// → { txReceiptId } | false

// Two-step transfer: approve by commitment (the new owner reveals to finalise)
await sdk.approveSRRByCommitment({
  tokenId: '123',
  preimage: 'secret shared with the recipient',   // or pass `revealHash`
  metadata: { transferType: 'Primary sale' },
  startrailLUWContractAddress: '0xLUW…',
})
// → { txReceiptId } | false

// Attach custom histories
await sdk.addCustomHistoriesToSRRs({ tokenIds: ['123', '124'], customHistoryIds: ['10'], startrailLUWContractAddress: '0xLUW…' })
// → { txReceiptId } | false
```

### Read-only helpers

```ts
// Convert metadata to the latest schema — no popup, no transaction
await sdk.convertMetadata({ metadataBatch: [{ metadata: legacyMetadata, tokenId: '123' }] })
// → [{ metadata, isConverted, message }]

// ERC-2981 royalty for an issued SRR, or for metadata that is about to be issued
await sdk.checkERC2981Royalty({ tokenId: '123' })
await sdk.checkERC2981Royalty({ metadata, issuerAddress: '0xIssuer…' })
// → { royaltyReceiver, royaltyBasisPoints } | false
```

### Batch

```ts
await sdk.bulk({
  isCompressEnabled: false,
  startrailLUWContractAddress: '0xLUW…',
  txs: [
    { functionType: 'createSRR', data: { isPrimaryIssuer: true, artistAddress: '0x…', lockExternalTransfer: false, metadata } },
    { functionType: 'approveSRRByCommitment', data: { tokenId: '123', preimage: '…', metadata: historyMetadata } },
    { functionType: 'transferFromWithProvenance', data: { to: '0x…', tokenId: '124', metadata: historyMetadata } },
  ],
})
// → { batchId } | false
```

`transferFromWithProvenance(args)` still exists as a method but is **deprecated** — use
`transferSRRToEthereumAddress(args)`.

## Errors

Real failures throw a subclass of the common `StartrailSdkErrorBase`. Every class is exported, and
each instance carries an `errorCode` (`StartrailSdkErrorCodeEnum`) and the original `message`.

```ts
import { Startrail, METADATA_VALIDATION_FAILED, StartrailApiError } from '@startbahn/startrail-sdk-js'

try {
  const res = await sdk.createSRR(args)
  if (res === false) return              // user cancelled — nothing happened
} catch (e) {
  if (e instanceof METADATA_VALIDATION_FAILED) showFieldErrors(e.message)
  else if (e instanceof StartrailApiError) showApiError(e)
  else throw e
}
```

| Class | When |
|---|---|
| `StartrailApiError` | A Startrail API request failed (HTTP error / rejected payload). |
| `STARTRAIL_API_QUOTA_LIMIT_EXCEEDED` | API rate or quota exceeded. |
| `STARTRAIL_API_NFC_TAG_MISSING` | The LUW has no NFC tag registered for the operation. |
| `METADATA_VALIDATION_FAILED` | Metadata failed schema validation; the message names the field. |
| `Auth0VerifyEmail` | The user must verify their email before logging in. |
| `WALLET_NOT_FOUND` / `WALLET_NOT_INITIALIZED` | No wallet detected / an action was called before `login()`. |
| `WALLET_NOT_SUPPORTED` / `WALLET_NOT_SUPPORT_FUNCTION` | The selected wallet cannot do this. |
| `WALLET_EOA_NOT_MATCH` | The active EOA differs from the one that logged in (MetaMask account switch). |
| `WALLET_USER_REJECT_WALLET_REQUEST` / `TORUS_USER_REJECT_WALLET_REQUEST` | The user rejected a signing request. |
| `WALLET_RPC_CONNECTION_FAILURE` | None of the RPC endpoints could be reached. |
| `TORUS_FAILS_INIT`, `TORUS_THIRD_PARTY_COOKIES_UNSUPPORTED`, `TORUS_INTEGRITY_UNMATCH`, `TORUS_CACHE_CONTROL_HEADERS_UNMATCH`, `TORUS_REJECT_USER_INFO` | Startrail-wallet initialisation / browser issues. |
| `JSON_RPC_ERROR` | A chain JSON-RPC error; a chain-id mismatch has `errorCode: 'CHAINID_MISMATCH'`. |
| `StartrailSdkError`, `Others` | Anything else. |

## Demo playground

**Hosted at [sdk.startrail.io](https://sdk.startrail.io/)** — open it and start clicking; nothing to
install. It is the `demo/` folder of this repo, a working integration that exercises every SDK method
against the live wallet and API. Each method is a card: fill the form, press **Run**, and read the
exact outcome (the result, a `false` for a cancelled popup, or the typed error) right under it,
together with the code you would write. A brand studio previews the login modal with your own
colours, and a scenario runner covers the multi-step session flows.

The hosted page always runs the **latest release on npm**: the version is resolved when the page
loads (through jsDelivr), so a new publish is live there within minutes and without a redeploy. The
top bar shows which version you are on (it links to that release on npm), the **environment** switch
(production / staging / lrc · QA / local — QA is the default) and your sign-in state.

| URL | Runs |
|---|---|
| `https://sdk.startrail.io/` | The latest release on npm. |
| `https://sdk.startrail.io/?sdk=2.2.0` | That release, pinned — to compare versions or reproduce a report. |
| `https://sdk.startrail.io/?sdk=local` | The bundle built by that deployment (on a preview deployment: the branch under review). |

### Run it

```sh
git clone git@github.com:startbahn/startrail-sdk-js.git
cd startrail-sdk-js
nvm use              # Node 24 (see .nvmrc); Node ^22.18 also works
corepack enable      # provisions the pnpm version pinned in package.json
pnpm install
pnpm demo            # dev server on http://localhost:3001 — opens the playground in your browser
```

`pnpm demo` starts webpack-dev-server, builds the SDK in memory, serves it at `/startrail-sdk.js`
for the page and rebuilds on every change under `src/` (reload the page to pick it up). Use
`pnpm serve` for the same server without opening a browser, then visit
**http://localhost:3001/demo/index.html**. Locally the page runs **this checkout's build** (the
top-bar badge says *this build*), so you can try changes to `src/` before they are published; pick
any release in the top-bar version picker (or add `?sdk=<version>` to the URL) to compare against a
release from npm.

With Docker instead of a local Node:

```sh
pnpm install         # the repo is bind-mounted into the container, so node_modules must exist on the host
pnpm demo:docker     # = docker compose up --build → same URL
```

### What's in it

| Section | What you can do |
|---|---|
| **Top bar** | A version picker — this build, the latest release, or any version published on npm, deprecated ones included — so you can run the same call on two releases and compare (the tag next to it says *latest on npm*, *pinned*, *this build* or *deprecated on npm*), the environment switch — production is red and warns before switching — and a session pill that is always visible: green with your short EOA when signed in, and a click away from the full address, a copy button, the block-explorer link, `getUserInfo()` details and sign-out. The session is remembered across reloads and instance rebuilds while the wallet still holds it. |
| **Overview** | Lifecycle at a glance, a getting-started checklist, and a one-click *Quick run* (sign in + `getUserInfo()`). |
| **1 · Setup** | Every constructor option with per-environment Auth0 / API values auto-filled, and a live, copyable `new Startrail(config)` snippet. |
| **2 · Brand the modal** | Presets (Startrail, PORT, Acme Gallery), every `customUi.theme` option — colours with pickers, font, dialog and control radii (incl. `'50%'` pills), logo placement / size / shape, button style, alignment — EN/JA wording, a per-site CSS override toggle, and **Preview** to open the real modal. |
| **3 · Sign in** | A sign-in panel: pick the wallet (Startrail wallet or MetaMask) and tap the login methods to offer — one method signs in directly, several or none show the picker — with an optional `loginHint`, a **sign out first** switch (`forceLogin`), a sentence that says exactly what `login()` will do, and **Sign in** / **Sign out**. Below it, `login()` with per-call overrides, `logout()`, `getUserInfo()`, `signMessage()`, `switchLanguage()`. |
| **4 · Shared parameters** | LUW, collection, artist, token id, recipient and preimage — edited once, used by every write action, persisted across reloads. |
| **5 · Records** | `createSRR()`, `updateMetadata()`, `transferSRRToEthereumAddress()`, `approveSRRByCommitment()`, `addCustomHistoriesToSRRs()` and the deprecated `transferFromWithProvenance()`, each with sample metadata you can edit. |
| **6 · Collections** | `createCollection()`, `transferCollectionOwnership()`. |
| **7 · Read & batch** | `convertMetadata()`, `checkERC2981Royalty()`, and `bulk()` with presets for the txs array. |
| **8 · Scenarios** | Regression tests with a pass/fail verdict, kept per SDK version so two releases can be compared: the switch-user test (login → discard → new instance → logout → login) with a storage inspector, and the MetaMask re-login test (login → logout → login, then `forceLogin` while signed in) that checks MetaMask asks for the account again. |

Every call lands in the **Activity** panel with its duration and outcome (filter to problems, copy,
or export as JSON). Inputs are validated inline (addresses, JSON), the page remembers your settings,
and it works in light and dark mode, on phones, and with a keyboard.

Logins open real wallet windows, so you need a test account for the chosen environment (QA by
default). Nothing writes to the chain until you run a card marked **write**.

## Development

| Command | What it does |
|---|---|
| `pnpm demo` | Dev server + opens the playground in the browser. `pnpm serve` is the same server without opening a tab; `pnpm demo:docker` runs it in a container. |
| `pnpm build:site` | Release bundle + the playground assembled into `site/` — what Vercel deploys to [sdk.startrail.io](https://sdk.startrail.io/). |
| `pnpm watch` | Rebuild `dist/startrail-sdk.js` on change (development mode). |
| `pnpm build:development` / `pnpm build:release` | One-off development / minified production bundle. |
| `pnpm test` | Development build, then the Jest suite. The `it-*` integration suites are `describe.skip`ped by default because they need a live wallet. |
| `pnpm jest` | Unit tests only, no rebuild. `pnpm jest-coverage` adds coverage. |
| `pnpm lint` | ESLint (neostandard, TypeScript-aware) with `--fix`. |
| `pnpm generate-dts` | Regenerate `types/startrail-sdk-js.d.ts` from `src/`. Also runs on every commit via husky. |

Layout: `src/startrail.ts` (public class) → `src/service.ts` (orchestration) → `src/wallets/`
(`torus.ts`, `metamask.ts`, the login modal in `modalContent.ts` + `modalTheme.ts`) and
`src/transaction.ts` / `src/requestAdapter.ts` (API calls). Request/response types live in
`src/types.ts`; error classes in `src/errorClass.ts`. Tests are in `test/`; the DOM tests for the
modal run under jsdom. The playground is `demo/index.html` + `demo/playground.css` + `demo/app.js`
(UI engine) + `demo/catalog.js` (one data entry per SDK method — add a method there and it gets a
card).

CI (CircleCI) runs the development build and `pnpm test` on every push.

### Releasing

A release is published to npm by GitHub Actions when its tag is pushed
([`.github/workflows/release.yml`](./.github/workflows/release.yml)):

1. Bump `version` in `package.json` through a pull request and merge it.
2. Tag that commit on `master` and push the tag (creating a GitHub Release with a new tag does the
   same):

```sh
git switch master && git pull --ff-only
git tag v2.3.1 && git push origin v2.3.1
```

The workflow checks that the tag is `v` + the `package.json` version, runs the tests, builds the
release bundle and publishes it. A plain version gets the `latest` dist-tag — its commit must be on
`master` and newer than the current `latest` — and a pre-release such as `v2.4.0-beta.1` gets
`next`. It authenticates with npm Trusted Publishing, so there is no npm token to store or rotate;
the one-time setup on npmjs.com is in
[`docs/deployment.md`](./docs/deployment.md#releasing-to-npm). *Run workflow* on any branch rehearses
every step and ends with `npm publish --dry-run`.

`pnpm publish:prod` (`latest`) and `pnpm publish:beta` (`next`) remain as the manual fallback, run by
the `startbahninc` npm user from a clean checkout. The README screenshots are served from the
published package via jsDelivr, so they update with each release.

The playground at [sdk.startrail.io](https://sdk.startrail.io/) is the Vercel project
`startbahn/sdk` (`vercel.json`): every push to `master` builds `pnpm build:site` and goes live; other
branches get preview URLs. The hosted page loads the SDK from npm (the latest release, resolved
when the page loads), not from the deployment, so a release changes what visitors run within
minutes; a redeploy only changes the page itself. `?sdk=local` on a preview URL runs that
branch's own bundle. See [`docs/deployment.md`](./docs/deployment.md#demo-site-sdkstartrailio).

## Resources

- [`llms.txt`](./llms.txt) — machine-readable API reference for AI coding tools
- [`AGENTS.md`](./AGENTS.md) — how coding agents should use the SDK
- [`docs/local_setup.md`](./docs/local_setup.md), [`docs/web_integration.md`](./docs/web_integration.md), [`docs/deployment.md`](./docs/deployment.md)
- Wallet terms of service: [EN](https://help.port.startrail.io/hc/en-us/articles/6210607383191) · [JA](https://help.port.startrail.io/hc/ja/articles/6210607383191)

© Startbahn, Inc. Proprietary — see `package.json` (`UNLICENSED`).

---
_Source: https://npm.io/package/@startbahn/startrail-sdk-js · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
