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

# Midaz SDK for TypeScript

> Build typed financial integrations with the Midaz SDK for TypeScript — builder pattern, automatic retries, observability, and strict validation.

The Midaz SDK for TypeScript helps you build financial integrations. It gives you a typed, developer-friendly interface over the Midaz financial services platform. You focus on your business logic, not on the transport code.

The SDK works with Organizations, Ledgers, Accounts, Transactions, and more. Use it for a simple workflow or for complex operations.

A layered, modular architecture supports performance, extensibility, and the developer experience.

### Why use the Midaz SDK for TypeScript?

* **Type-safe by design**: Full TypeScript support with precise type definitions.
* **Builder pattern**: Fluent, readable interfaces to construct complex objects.
* **Robust error handling**: Recovery strategies and clear error signals.
* **Observability included**: Tracing, metrics, and logs, ready to use.
* **Layered architecture**: Clean separation between client, entities, API, and models.
* **Automatic retries**: Configurable retry policies for transient failures.
* **Concurrency controls**: Built-in tools to run tasks in parallel with controlled throughput.
* **Fast with caching**: In-memory caching for better performance.
* **Strict validation**: Catch invalid input early with clear error messages.

## Getting started

***

### Prerequisite

* The Midaz SDK for TypeScript **requires** TypeScript **v5.8 or later**.

### Installing the SDK

Install the **Midaz SDK for TypeScript** with one of the following commands:

<CodeGroup>
  ```bash npm theme={null}
  npm install @lerianstudio/midaz-sdk
  ```

  ```bash yarn theme={null}
  yarn add @lerianstudio/midaz-sdk
  ```
</CodeGroup>

After you install it, follow the [*Quick Start Guide*](#quick-start-guide) to learn how to use the SDK.

## Authentication

***

The **Midaz SDK for TypeScript** authenticates through the Lerian **Access Manager** (OAuth). For a local stack with authentication disabled, you can build a client without it.

You never call a `createClient` factory — build a configuration with `createClientConfigWithAccessManager()` (or `createClientConfigBuilder()` for a no-auth local stack) and pass it to `new MidazClient(config)`.

#### Access Manager authentication

To integrate with external identity providers over OAuth:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createClientConfigWithAccessManager, MidazClient } from '@lerianstudio/midaz-sdk';

  const client = new MidazClient(
    createClientConfigWithAccessManager({
      address: 'https://auth.example.com',
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret',
    }).withEnvironment('sandbox')
  );
  ```
</CodeGroup>

The Access Manager handles tokens for you: acquisition, caching, and renewal. You do not manage tokens manually.

#### Local development (no authentication)

For a local Midaz stack with authentication disabled, build a client without the Access Manager:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createClientConfigBuilder, MidazClient } from '@lerianstudio/midaz-sdk';

  const client = new MidazClient(
    createClientConfigBuilder().withEnvironment('development')
  );
  ```
</CodeGroup>

<Tip>
  We offer an [Access Manager plugin](/en/platform/access-manager/access-manager) that you can use. If you'd like to know more about it, [contact us](https://lerian.studio/contact).
</Tip>

## Quick start guide

***

The following sections give practical code examples for the **Midaz SDK for TypeScript**.

### Create a client

This is the first step. The client is your main entry point to the SDK. It handles authentication and gives you access to all entity services.

**Example:**

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createClientConfigBuilder, MidazClient } from '@lerianstudio/midaz-sdk';

  const client = new MidazClient(
    createClientConfigBuilder().withEnvironment('sandbox') // Options: 'development', 'sandbox', 'production'
  );
  ```
</CodeGroup>

### Create an Asset

Create assets with the builder pattern and `createAssetBuilder`.

**Example:**

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createAssetBuilder } from '@lerianstudio/midaz-sdk';

  const assetInput = createAssetBuilder('US Dollar', 'USD')
    .withType('currency')
    .withMetadata({ precision: 2, symbol: '$' })
    .build();

  const asset = await client.entities.assets.createAsset('org_123', 'ledger_456', assetInput);
  ```
</CodeGroup>

In this code, you add the required `name` and `assetCode` fields to the builder `const assetInput = createAssetBuilder('US Dollar', 'USD')`. Then you add any other properties with `with*` methods.

### Create an Account

Create accounts with the builder pattern and `createAccountBuilder`.

**Example:**

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createAccountBuilder } from '@lerianstudio/midaz-sdk';

  const accountInput = createAccountBuilder('Savings Account', 'USD')
    .withType('savings')
    .withAlias('personal-savings')
    .build();

  const account = await client.entities.accounts.createAccount('org_123', 'ledger_456', accountInput);
  ```
</CodeGroup>

In this code, you add the required `name` and `assetCode` fields to the builder `const accountInput = createAccountBuilder('Savings Account', 'USD')`. Then you add any other properties with `with*` methods.

### Create a Transaction

Create transactions with the builder pattern and `createTransactionBuilder`.

**Example:**

<CodeGroup>
  ```typescript TypeScript expandable theme={null}
  import { createTransactionBuilder } from '@lerianstudio/midaz-sdk';

  const transactionInput = createTransactionBuilder()
    .withCode('payment_001')
    .withOperations([
      {
        accountId: 'source_account_id',
        assetCode: 'USD',
        amount: 100 * 100, // $100.00
        type: 'debit',
      },
      {
        accountId: 'destination_account_id',
        assetCode: 'USD',
        amount: 100 * 100, // $100.00
        type: 'credit',
      },
    ])
    .withMetadata({ purpose: 'Monthly payment' })
    .build();
  ```
</CodeGroup>

In this code, you add all properties with `with*` methods.

### Error recovery

Use enhanced error recovery for critical operations.

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { withEnhancedRecovery } from '@lerianstudio/midaz-sdk/util/error';

  const result = await withEnhancedRecovery(
    () => client.entities.transactions.createTransaction('org_123', 'ledger_456', transactionInput),
    {
      maxRetries: 3,
      enableSmartRecovery: true,
    }
  );
  ```
</CodeGroup>

### Clean up resources

<CodeGroup>
  ```typescript TypeScript theme={null}
  client.close();
  ```
</CodeGroup>

### Using Access Manager for authentication

<CodeGroup>
  ```typescript TypeScript expandable theme={null}
  import { createClientConfigWithAccessManager, MidazClient } from '@lerianstudio/midaz-sdk';

  // Initialize the client with Access Manager authentication
  const client = new MidazClient(
    createClientConfigWithAccessManager({
      address: 'https://auth.example.com', // Identity provider address
      clientId: 'your-client-id', // OAuth client ID
      clientSecret: 'your-client-secret', // OAuth client secret
      tokenEndpoint: '/oauth/token', // Optional, defaults to '/oauth/token'
      refreshThresholdSeconds: 300, // Optional, defaults to 300 (5 minutes)
    })
      .withEnvironment('sandbox')
      .withApiVersion('v1')
  );

  // The SDK will automatically handle token acquisition and renewal
  // You can now use the client as normal
  const organizations = await client.entities.organizations.listOrganizations();

  // For environment-specific configurations with Access Manager
  const sandboxClient = new MidazClient(
    createSandboxConfigWithAccessManager({
      address: 'https://auth.example.com',
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret',
    })
  );

  // Clean up resources when done
  client.close();
  ```
</CodeGroup>

## SDK architecture

***

The Midaz SDK uses a multi-layered service architecture for a clean, modular, and scalable developer experience. It has three layers, shown in *Figure 1*. Each layer serves a distinct purpose.

* **Client interface**: This is the main entry point for SDK users. It manages configuration such as API keys and environments. It initializes services lazily and exposes all SDK functionality.
* **Entity services layer**: This layer holds domain-specific services, such as Accounts, Assets, and Transactions. Each service offers consistent methods: create, get, update, delete, and list. Each service also adds specialized operations for its entity.
* **Core services layer**: All entity services use these foundational utilities. They handle HTTP requests, input validation, error processing, observability, configuration, and caching.

<Frame caption="Figure 1. The layered architecture of the Midaz SDK for TypeScript.">
  <img src="https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/sdk-typescript-architecture.svg?fit=max&auto=format&n=SEOef3JqTInYAAau&q=85&s=071bbf4a7b5211949f85b0a406301a77" alt="Layered architecture of the Midaz SDK for TypeScript, with the client interface over the entity services layer over the shared core services layer" width="915" height="780" data-path="images/en/d2/sdk-typescript-architecture.svg" />
</Frame>

The SDK architecture emphasizes:

* **Consistency** through shared patterns across services.
* **Scalability** via dependency injection and service factories.
* **Reliability** through enhanced error handling and typed responses.
* **Testability** with support for mocking, integration, and contract testing.

<Tip>
  Want to dive Deeper? Check the following pages for more information about the Architecture:

  * [Midaz SDK architecture overview](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/architecture/overview.md).
  * [Client interface architecture](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/architecture/client-interface.md).
  * [Service layer architecture](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/architecture/service-layer.md).
</Tip>

## Builder pattern

***

The **Midaz SDK for TypeScript** uses a builder pattern to help you assemble complex objects in a safe, adaptable way. Instead of a fixed set of inputs, it gives you a step-by-step, fluent, chainable interface.

**Builder functions in the SDK:**

* Tell you the parameters in advance.
* Let you set optional fields with `.with*()` methods and chain them.
* Prevent invalid states through a guided structure.
* Hide internal complexity for better readability.

### Example

Here’s a quick example:

<CodeGroup>
  ```typescript TypeScript theme={null}
  const assetInput = createAssetBuilder('USD Currency', 'USD')
    .withType('currency')
    .withMetadata({ precision: 2 })
    .build();
  ```
</CodeGroup>

You can then pass this `assetInput` to the corresponding create method in the SDK.

<Tip>
  Want to dive deeper? Check the [Builder Pattern in Midaz SDK](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/core-concepts/builder-pattern.md) page for more information.
</Tip>

## Working with entities

***

Each entity service covers a distinct part of the financial domain, such as accounts, assets, or transactions.

These services create, retrieve, update, and delete data for each type of entity.

They also offer specialized features for each use case, so you handle financial data with confidence.

| Entity                                                                                                             | Description                                                              |
| :----------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------- |
| [**Organizations**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/organizations.md) | Manage business units and organizational data.                           |
| [**Ledgers**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/ledgers.md)             | Structure and manage financial records.                                  |
| [**Assets**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/assets.md)               | Work with assets such as currencies, commodities, and other value units. |
| [**Accounts**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/accounts.md)           | Create, retrieve, update, and delete accounts within a Ledger.           |
| [**Segments**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/segments.md)           | Organize portfolios for analytics and reporting.                         |
| [**Portfolios**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/portfolios.md)       | Group accounts and assets into meaningful financial collections.         |
| [**Balances**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/balances.md)           | Retrieve and calculate asset balances for accounts.                      |
| [**Asset Rates**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/asset-rates.md)     | Handle exchange rates between different asset types.                     |
| [**Transactions**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/transactions.md)   | Create and manage transactions that move assets between accounts.        |
| [**Operations**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/entities/operations.md)       | Manage atomic debits and credits that make up a transaction.             |

You access each service through the SDK client. They follow a consistent structure, so you build and maintain financial features more easily.

<Tip>
  Want to dive deeper? Check the [Entities pages](https://github.com/LerianStudio/midaz-sdk-typescript/tree/main/docs/entities) for more information.
</Tip>

## Using utilities

***

The SDK provides utility modules for common operations: performance, error handling, configuration, and observability.

These tools work with the rest of the SDK and help you build financial applications with less effort.

| Utility                                                                                                                 | Description                                                             |
| :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------- |
| [**Account Helpers**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/account-helpers.md) | Simplifies common account-related logic and transformations.            |
| [**Cache**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/cache.md)                     | Enables lightweight caching for better runtime performance.             |
| [**Concurrency**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/concurrency.md)         | Helps coordinate and limit concurrent tasks safely and efficiently.     |
| [**Config**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/config.md)                   | Centralized configuration setup and access.                             |
| [**Data**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/data.md)                       | Assists with data formatting and pagination tasks.                      |
| [**Error Handling**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/error-handling.md)   | Offers recovery strategies and error processing mechanisms.             |
| [**HTTP Client**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/http-client.md)         | Provides a low-level HTTP interface for direct API calls.               |
| [**Network**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/network.md)                 | Adds high-level networking features like retries and backoff.           |
| [**Observability**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/observability.md)     | Captures traces, metrics, and logs to support monitoring and debugging. |
| [**Pagination**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/pagination.md)           | Handles paginated responses with predictable, consistent helpers.       |
| [**Validation**](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/validation.md)           | Validates input and output data to help maintain data integrity.        |

<Tip>
  Want to dive deeper? Check the [Utilities pages](https://github.com/LerianStudio/midaz-sdk-typescript/tree/main/docs/utilities) for more information.
</Tip>

## Error handling

***

The **Midaz SDK for TypeScript** helps you handle errors clearly and consistently. When an error occurs during an SDK operation, the SDK throws a structured error. The error includes key fields:

* `code`: A short, consistent identifier for the error type.
* `message`: A human-readable description.
* `statusCode`: The HTTP status code, when available.

Handle an error like this:

<CodeGroup>
  ```typescript TypeScript theme={null}
  try {
    await client.transactions.create(transaction);
  } catch (err) {
    console.error(`Error (${err.code}): ${err.message}`);
    // Optionally: inspect err.statusCode
  }
  ```
</CodeGroup>

### Common error codes

| Code                  | Description                                                  | HTTP Status |
| :-------------------- | :----------------------------------------------------------- | :---------- |
| `invalid_input`       | Your request is missing required data or has invalid values. | `400`       |
| `unauthorized`        | Authentication failed or credentials are missing.            | `401`       |
| `forbidden`           | You're not allowed to perform this action.                   | `403`       |
| `not_found`           | The resource you're trying to access doesn't exist.          | `404`       |
| `conflict`            | The operation conflicts with an existing resource.           | `409`       |
| `internal_error`      | Something went wrong on our side.                            | `500`       |
| `service_unavailable` | Temporary outage—try again later.                            | `503`       |

### Best practices

* **Validate input** before you call SDK methods, to avoid `invalid_input`.
* **Check your auth** when you get `unauthorized` or `forbidden`.
* **Retry** on transient issues like `internal_error` or `service_unavailable`.
* **Use `statusCode` and `message`** to show debug info in development logs.

The SDK keeps errors predictable and actionable.

<Tip>
  **Tip**

  Want to dive deeper? Check the following pages for more information:

  * [Error handling in Midaz SDK](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/core-concepts/error-handling.md).
  * [Error handling architecture](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/architecture/error-handling.md).
  * [Error handling (Utilities)](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/docs/utilities/error-handling.md).
</Tip>

## CI/CD pipeline

***

We use GitHub Actions for automated, production-ready builds:

* Runs tests across multiple Node.js versions.
* Enforces code quality with ESLint and Prettier.
* Keeps dependencies up to date with Dependabot.
* Handles releases automatically with semantic versioning.
* Generates changelogs.

## Want to contribute?

***

To contribute to the Midaz SDK for TypeScript, start with our [contributing guide on GitHub](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/CONTRIBUTING.md). It covers what you need to get started.

## License

***

This project is licensed under the Apache License 2.0. For details, see the [License](https://github.com/LerianStudio/midaz-sdk-typescript/blob/main/LICENSE) page.
