> For the complete documentation index, see [llms.txt](https://docs.baas.sh/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.baas.sh/baas-sdk/resources/api-reference.md).

# API reference

A complete reference for `@baas/sdk`. For the why and how, see the [Introduction](/baas-sdk/sdk.md).

## `createBaasClient(options)`

Creates the client. Call it **once**, at the root of your app. It's **synchronous**, so `getSession()` works on the first render. The network runtime (`/networks` → Porto) loads **lazily** on the first operation that needs it (a passkey sign-in or `baas.chains.list()`), then is memoized.

```ts
const baas = createBaasClient({
  projectId:      'my-baas-project',
  publishableKey: 'sb_publishable_xxx',
  apiUrl:         'https://my-project-api.baas.sh',
  requestTimeout: 15_000, // optional
});
```

| Option           | Type     | Default | Description                                                                                    |
| ---------------- | -------- | ------- | ---------------------------------------------------------------------------------------------- |
| `projectId`      | `string` | —       | Your project ID. Scopes local session storage (so sessions survive publishable-key rotations). |
| `publishableKey` | `string` | —       | Your publishable key (starts with `sb_publishable_`).                                          |
| `apiUrl`         | `string` | —       | Your project's API URL.                                                                        |
| `requestTimeout` | `number` | `15000` | HTTP request timeout, in milliseconds.                                                         |

**Returns** `BaasClient` (synchronously):

```ts
type BaasClient = {
  auth:     BaasAuthClient;
  contract: (name: string) => ContractStep;
  wallet:   BaasWallet;
  chains:   BaasChainsClient;
  user:     BaasUserClient;
};
```

**Throws synchronously:**

* `BaasError` (`INVALID_CONFIG`) — `projectId`, `publishableKey`, or `apiUrl` is missing or empty.

The `/networks` runtime errors surface at the **first operation that needs the network** (passkey sign-in, `chains.list()`, `chains.switch()`), not at init:

* `BaasNetworkError` (`NETWORK_ERROR`) — `/networks` unreachable (down, timeout, wrong `apiUrl`).
* `BaasApiError` (`API_ERROR`) — `/networks` returned a non-2xx response (e.g. invalid `publishableKey`).
* `BaasError` (`INVALID_CONFIG`) — `/networks` returned an empty or malformed list.

## `baas.auth`

See the [Authentication](/baas-sdk/authentication.md) and [Sessions](/baas-sdk/authentication/sessions.md) guides.

| Method                        | Returns                | Description                                                                                             |
| ----------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------- |
| `signIn(method?, provider?)`  | `Promise<BaasSession>` | Shortcut. Defaults to passkey; `signIn('wallet', provider)` for a wallet.                               |
| `signUp(method?, options?)`   | `Promise<BaasSession>` | Shortcut. Defaults to passkey; `signUp('passkey', { label })` to label it.                              |
| `signInWithPasskey()`         | `Promise<BaasSession>` | Sign in with an existing passkey.                                                                       |
| `signUpWithPasskey(options?)` | `Promise<BaasSession>` | Create a new passkey and sign in. `options.label?: string`.                                             |
| `signInWithWallet(provider)`  | `Promise<BaasSession>` | Sign in with an EIP-1193 wallet.                                                                        |
| `signOut()`                   | `Promise<void>`        | End the session locally and clear the server cookie. Always succeeds.                                   |
| `getSession()`                | `BaasSession \| null`  | The current session, synchronously.                                                                     |
| `onAuthStateChange(cb)`       | `() => void`           | Subscribe to session changes. Fires immediately, then on every change. Returns an unsubscribe function. |
| `refresh()`                   | `Promise<string>`      | Force a token refresh and return the new access token. Rarely needed.                                   |

## `baas.contract`

See the [Smart contracts](/baas-sdk/blockchain/smart-contracts.md) guide.

`baas.contract(name)` opens a fluent chain: `.address(addr).function(name).params(...args).VERB()`.

| Verb                     | Returns                    | Description                                                                                      |
| ------------------------ | -------------------------- | ------------------------------------------------------------------------------------------------ |
| `read<T>()`              | `Promise<T>`               | Call a view or pure function.                                                                    |
| `sendTransaction(opts?)` | `Promise<BaasTransaction>` | Submit a state-changing call. Returns `{ hash, wait }`.                                          |
| `simulate<T>(opts?)`     | `Promise<T>`               | Dry-run a call without sending. Useful as a revert preview and for `msg.sender`-dependent reads. |
| `estimateGas(opts?)`     | `Promise<bigint>`          | Estimate the number of gas units a call would consume.                                           |

## `baas.wallet`

See the [Wallet operations](/baas-sdk/blockchain/wallet.md) guide.

| Method                        | Returns                    | Description                                             |
| ----------------------------- | -------------------------- | ------------------------------------------------------- |
| `sendTransaction(opts)`       | `Promise<BaasTransaction>` | Send a transaction from the user's wallet.              |
| `signMessage(message, opts?)` | ``Promise<`0x${string}`>`` | Sign an off-chain message and return the hex signature. |
| `getBalance(address, opts?)`  | `Promise<bigint>`          | Read the native balance of an address (in wei).         |

## `baas.chains`

See the [Networks](/baas-sdk/blockchain/networks.md) guide.

| Method              | Returns                         | Description                                                                                      |
| ------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------ |
| `list()`            | `Promise<readonly BaasChain[]>` | The chains your project supports (fetched once, then memoized).                                  |
| `active()`          | `number \| null`                | The selected chain id, or `null` if none chosen yet (sign-in defaults to the first chain).       |
| `switch(chainId)`   | `Promise<void>`                 | Switch the active chain. Throws `UNKNOWN_CHAIN` if unknown.                                      |
| `onChainChange(cb)` | `() => void`                    | Subscribe to chain changes. Fires immediately (with `number \| null`), then on every `switch()`. |

## `baas.user`

See the [Manage user](/baas-sdk/manage-user.md) guide.

| Method                    | Returns             | Description                                     |
| ------------------------- | ------------------- | ----------------------------------------------- |
| `getUser()`               | `Promise<BaasUser>` | Read the signed-in user's profile.              |
| `setEmail(email \| null)` | `Promise<void>`     | Set the user's email — pass `null` to clear it. |
| `addFcmToken(token)`      | `Promise<void>`     | Attach a push notification token (idempotent).  |
| `removeFcmToken(token)`   | `Promise<void>`     | Detach a push notification token (idempotent).  |

## Types

```ts
type BaasSession = {
  address:     string;               // checksummed EVM address (0x…)
  accessToken: string;               // raw JWT
  expiresAt:   number;               // Unix timestamp in seconds
  method?:     'passkey' | 'wallet'; // sign-in method (used by baas.wallet to route the default signer)
};

type BaasChain = {
  value:     string;   // stable slug, e.g. 'base'
  label:     string;   // human-readable, e.g. 'Base'
  chainId:   number;   // EIP-155 chain id
  rpcUrl:    string;   // public JSON-RPC endpoint
  isMainnet: boolean;  // true for production chains
};

type BaasUser = {
  address:      string;                          // checksummed EVM address (the user id)
  email:        string | null;                   // profile email, or null if unset
  contractData: Record<string, unknown> | null;  // arbitrary contract-associated data
  fcmTokens:    string[];                        // registered push-notification tokens
  createdAt:    string;                          // ISO 8601 timestamp
};
```

## Errors

All errors extend `BaasError` and carry a `code`. See the [Error handling](/baas-sdk/resources/error-handling.md) guide for usage and the full code table.

```
BaasError                 code, optional cause          (INVALID_CONFIG, UNKNOWN_CHAIN,
│                                                         TRANSACTION_FAILED, SIGNATURE_FAILED,
│                                                         SIGNER_REQUIRED)
├── BaasAuthError         + status?: number             (NONCE_FETCH_FAILED, VERIFY_FAILED,
│                                                         REFRESH_FAILED, SESSION_EXPIRED, NOT_SIGNED_IN)
├── BaasWalletError                                     (WALLET_CONNECT_REJECTED,
│                                                         TRANSACTION_REJECTED, SIGNATURE_REJECTED)
├── BaasNetworkError                                    (NETWORK_ERROR)
└── BaasApiError          + status: number, body,       (API_ERROR)
                          + level?, validOptions?
```

## Next

* [Exported types](/baas-sdk/resources/exported-types.md) — all the TypeScript types you can import.
* [Error handling](/baas-sdk/resources/error-handling.md) — error classes, codes, and patterns.
* [Integration guides](/baas-sdk/integrations.md) — TypeScript setup and supported environments.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.baas.sh/baas-sdk/resources/api-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
