> 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

Every method, option, type, and error in the BaaS SDK, in one place.

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

## `createBaasClient(url, options?)`

Creates the client. Call it **once**, in browser code at the root of your app. It returns **synchronously**; session restoration starts in the background.

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

| Argument                    | Type     | Default  | Description                                                                |
| --------------------------- | -------- | -------- | -------------------------------------------------------------------------- |
| `url`                       | `string` | —        | Your project's API URL (an origin, e.g. `https://my-project-api.baas.sh`). |
| `options.requestTimeout`    | `number` | `15000`  | One Project API HTTP exchange, in milliseconds.                            |
| `options.rpcTimeout`        | `number` | `10000`  | One chain RPC request.                                                     |
| `options.bundlerTimeout`    | `number` | `60000`  | One bundler request.                                                       |
| `options.activationTimeout` | `number` | `300000` | Smart-wallet activation request.                                           |
| `options.inclusionTimeout`  | `number` | `120000` | UserOperation inclusion wait.                                              |

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

```ts
type BaasClient = {
  auth:     BaasAuthClient;
  contract: (name: string) => ContractStep;
  wallet:   BaasWallet;
  smartWallet: BaasSmartWalletClient; // passkey sessions: activation per chain
  chains:   BaasChainsClient;
  user:     BaasUserClient;
};
```

**Throws synchronously:**

* `BaasError` (`INVALID_CONFIG`) — `url` is missing, malformed or not an origin, or a timeout is not a positive integer in the range 1–2,147,483,647.

Methods that need a chain (a contract call, a transaction, a balance read, `baas.chains.list()` / `switch()`) require a session and can fail while loading your project's networks:

* `BaasAuthError` (`NOT_SIGNED_IN`) — no session.
* `BaasNetworkError` (`NETWORK_ERROR`) / `BaasApiError` (`API_ERROR`) — the networks could not be loaded.

## `baas.auth`

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

| Method                                | Returns                            | Description                                                                                                                                                                                                              |
| ------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `signUpWithSmartWallet(options)`      | `Promise<SmartWalletSignUpResult>` | Create a passkey smart wallet account and return its `{ address }`. Opens no session and leaves the current one untouched: call `signInWithSmartWallet()` next. `options.email: string`, `options.signal?: AbortSignal`. |
| `signInWithSmartWallet(options)`      | `Promise<BaasSession>`             | Sign in with the passkey associated with `options.email`. `options.signal?: AbortSignal`.                                                                                                                                |
| `signInWithWallet(provider, options)` | `Promise<BaasSession>`             | Sign in with an EIP-1193 wallet. `options.email: string`.                                                                                                                                                                |
| `signOut()`                           | `Promise<void>`                    | Sign the user out of this browser. Throws `SIGNOUT_FAILED` if it fails: retry.                                                                                                                                           |
| `getSession()`                        | `Promise<BaasSession \| null>`     | The current session, once restoration has settled; rejects when it could not be restored or renewed (see [Sessions](/baas-sdk/authentication/sessions.md#read-the-current-session)).                                     |
| `onAuthStateChange(cb)`               | `() => void`                       | Subscribe to auth events (`INITIAL_SESSION`, `SIGNED_IN`, `SIGNED_OUT`, `TOKEN_REFRESHED`); `cb` receives `(event, session)`. Returns an unsubscribe function.                                                           |
| `refresh()`                           | `Promise<string>`                  | Force a token refresh and return the new access token. Rarely needed.                                                                                                                                                    |
| `getPasskeyCapabilities()`            | `PasskeyCapabilities`              | Whether this page can run passkeys (`webAuthn`, `secureContext`), with no prompt.                                                                                                                                        |
| `dispose()`                           | `void`                             | Releases the client's listeners and timers. Only needed in tests or when you create clients dynamically.                                                                                                                 |

## `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()`. Calls target the active chain selected with `baas.chains.switch()`. An argument wrapped with `SmartUnits()` is scaled with the decimals BaaS knows for it. See [Smart units](/baas-sdk/blockchain/smart-units.md).

| Verb                     | Returns                    | Description                                                                                                                          |
| ------------------------ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `read<T>(opts?)`         | `Promise<T>`               | Call a view or pure function. Resolves to the outputs array.                                                                         |
| `sendTransaction(opts?)` | `Promise<BaasTransaction>` | Submit a state-changing call. Returns `{ hash, wait }`.                                                                              |
| `simulate<T>(opts?)`     | `Promise<T>`               | Dry-run a call without sending; resolves to the same outputs array. 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.                                                                               |

`read()` and `simulate()` return an array in ABI output order; type `T` as a tuple. Amounts with a configured unit return `UnitFormattedValue`. See [Read data](/baas-sdk/blockchain/smart-contracts.md#read-data).

The address step also reads the contract's event history. `.address(addr).events(opts?)` resolves to a `ContractEventsPage`, newest first, narrowed by `event` and `where`, and paged with `page` and `limit`. See [Read the event history](/baas-sdk/blockchain/events.md).

## `baas.wallet`

Native `value` accepts raw wei or `SmartUnits()`, for both wallet and contract operations. See [Send native currency](/baas-sdk/blockchain/smart-units.md#send-native-currency).

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.                                                                                                                            |
| `waitForUserOperation(operation, options?)` | `Promise<BaasTransaction>`    | Resume confirmation of an existing passkey operation without submitting again. See [uncertain confirmation](/baas-sdk/resources/error-handling.md#when-confirmation-is-uncertain). |
| `getBalance(address)`                       | `Promise<UnitFormattedValue>` | Read a native balance: `raw` is the exact wei string, `formatted` is computed with 18 decimals.                                                                                    |

## `baas.chains`

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

| Method                   | Returns                         | Description                                                                                                                    |
| ------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `list()`                 | `Promise<readonly BaasChain[]>` | The chains this session may use. Signed out, throws `NOT_SIGNED_IN`.                                                           |
| `active()`               | `number \| null`                | The active chain id, or `null` if none chosen yet.                                                                             |
| `switch(chainId, opts?)` | `Promise<void>`                 | Switch the active chain (`{ signer }` required with a wallet). Throws `UNKNOWN_CHAIN`, `SIGNER_REQUIRED`, or `CHAIN_SWITCH_*`. |
| `onChainChange(cb)`      | `() => void`                    | Subscribe to chain changes. Fires immediately, then on every change.                                                           |
| `watchWallet(provider)`  | `Promise<void>`                 | Follow the wallet's network again after a reload. Pass the provider used at sign-in; no-op for passkey.                        |

## `baas.smartWallet`

Passkey sessions only. A smart wallet must be activated on a chain before it can send there. Activation costs the user nothing.

| Method       | Returns                                | Description                                                                                                                                                           |
| ------------ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `activate()` | `Promise<SmartWalletActivationResult>` | Activate the signed-in smart wallet on the active chain. See [Activate a smart wallet on a chain](/baas-sdk/blockchain/wallet.md#activate-a-smart-wallet-on-a-chain). |

## `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)`       | `Promise<void>`                                  | Replace the user's email.                                                                                                                                                                                                          |
| `addFcmToken(token)`    | `Promise<void>`                                  | Attach a push notification token (idempotent).                                                                                                                                                                                     |
| `removeFcmToken(token)` | `Promise<void>`                                  | Detach a push notification token (idempotent).                                                                                                                                                                                     |
| `events(opts)`          | `Promise<ContractEventsPage<UserContractEvent>>` | Read the user's events on one contract, each with its `directions`. Takes the contract history's `event` and `where`; a rule may name `direction`. See [Read the user's history](/baas-sdk/manage-user.md#read-the-users-history). |

## Filter helpers

Pass helper-built filters as `where` to contract or user `events()` calls. See the [helper reference](/baas-sdk/resources/exported-types.md#helpers), [contract examples](/baas-sdk/blockchain/events.md#filter-events) and [user examples](/baas-sdk/manage-user.md#filter-the-users-history).

## Types

```ts
type BaasSession = {
  readonly address:     string;      // checksummed EVM address (0x…)
  readonly accessToken: string;      // raw JWT
  readonly expiresAt:   number;      // expiry estimate in Unix seconds
} & (
  | { readonly walletMode: 'external-wallet' }
  | { readonly walletMode: 'smart-wallet'; readonly smartWallet: SmartWalletJournalV1 }
);

type BaasTransaction = {
  hash: `0x${string}`; // transaction hash
  userOperationHash?: `0x${string}`; // present only for passkey sends
  wait(opts?: { confirmations?: number; timeout?: number }): Promise<TransactionReceipt>; // confirms on the send chain, independently of the active chain
};

// baas.wallet
type SendTransactionOptions = { to: string; value: string | bigint | UnitInput; data?: `0x${string}`; signer?: EIP1193Provider };
type SignMessageOptions     = { signer?: EIP1193Provider };

// baas.contract(name).address(addr).function(name).params(...args).VERB()
type SendOptions        = { value?: string | bigint | UnitInput; signer?: EIP1193Provider };
type RequestOptions     = { signal?: AbortSignal; timeoutMs?: number };
type SimulateOptions    = RequestOptions & { value?: string | bigint | UnitInput; from?: string };
type EstimateGasOptions = SimulateOptions;
type ContractEventsOptions = RequestOptions & { event?: string; where?: Where; page?: number; limit?: number };
type UserEventsOptions = ContractEventsOptions & { address: string };

type BaasChain = {
  label:                string;   // human-readable, e.g. 'Base'
  chainId:              number;   // EIP-155 chain id
  rpcUrl:               string;   // JSON-RPC endpoint; may require authentication
  isMainnet:            boolean;  // true for production chains
  nativeCurrencySymbol: string;   // native currency symbol, e.g. 'ETH' / 'POL'
  isBaaSChain:           boolean;  // true for the project's own BaaS chain
  smartWallet?: SmartWalletChainConfig; // bundler configuration for passkey sessions
};

type BaasUser = {
  address:   string;         // checksummed EVM address (the user id)
  email:     string;         // profile email
  fcmTokens: string[];       // registered push-notification tokens
  createdAt: string;         // ISO 8601 timestamp
};

type UnitFormattedValue = {
  readonly raw:       string;                                   // exact on-chain integer
  readonly formatted: string;                                   // in the token's unit or native currency, like '1.5' or '3.0'
  readonly metadata: { readonly encoding: 'units'; readonly decimals: string };  // decimals applied, as a string
};

type UnitValue = string | UnitFormattedValue;          // a numeric output, bound to a unit or not
type UnitInput = ReturnType<typeof SmartUnits>;        // opaque: always build it with SmartUnits()

type ContractEvent = {
  id: string; transactionHash: string; chainId: string; contractAddress: string;
  event: string; blockNumber: string; timestamp: string | null;
  out: string[]; in: string[]; related: string[];       // the groups the mappings declare
  values: Record<string, unknown>;                      // the declared business values
  log: ContractEventLog;                                // the log itself: signature, args, argTypes, topics, data…
};
type UserContractEvent = ContractEvent & { directions: WalletDirection[] }; // 'out' | 'in' | 'related'
type ContractEventsPage<T = ContractEvent> = { data: T[]; count: number; page: number; limit: number };
type Where = { combinator: 'and' | 'or'; rules: readonly (WhereRule | Where)[] }; // args.<name>, occurredAt, key, wallet or direction
type WhereRule =
  | { field: string; operator: '=' | '!=' | '>' | '>=' | '<' | '<=' | 'contains' | 'starts_with' | 'ends_with'; value: WhereValue }
  | { field: string; operator: 'in'; value: readonly WhereValue[] };
type WhereValue = string | boolean | UnitInput; // UnitInput: what SmartUnits() returns
// API limits: 3 levels including the root, 8 rules and 50 values across the tree, 256 characters per string, 4,096 characters serialized; no empty groups or in lists.
```

## Errors

All SDK-defined errors extend `BaasError` and carry a `code`; a wrapped error keeps the original on `.cause`. `BaasAuthError` adds `status`, `BaasApiError` adds `status`, `body`, `level`, `validOptions` and `revert`, `BaasTransactionError` adds `transactionHash` and `userOperationHash`, and `BaasUserOperationError` carries `operation` and `stage`. The [Error handling](/baas-sdk/resources/error-handling.md) guide lists every code.

## 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.
