> ## 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  serves as an essential tool for building financial integrations with ease and confidence. It provides a developer-friendly, fully typed interface that wraps around Midaz’s financial services platform, allowing you to concentrate on your business logic instead and not on the code.

Designed for clarity and scalability, the SDK enables you to work with Organizations, Ledgers, Accounts, Transactions, and more, whether you are creating a simple workflow or managing complex operations.

At its core, the SDK is built on a layered, modular architecture that prioritizes performance, extensibility, and an excellent developer experience.

### Why use the Midaz SDK for TypeScript?

* **Type-safe by design**: Built with full TypeScript support and precise type definitions.
* **Builder pattern**: Fluent, readable interfaces to help you construct complex objects with ease.
* **Robust error handling**: Smart recovery strategies and clear error signals, so you stay in control.
* **Observability included**: Tracing, metrics, and logs, ready out of the box.
* **Layered architecture**: Clean separation between client, entities, API, and models. Organized, predictable, scalable.
* **Automatic retries**: Handle transient hiccups with configurable retry policies.
* **Concurrency controls**: Built-in tools to run tasks in parallel, without losing control of throughput.
* **Fast with caching**: In-memory caching to boost performance where it counts.
* **Strict validation**: Catch invalid input early with clear, actionable error messages.

## Getting started

***

### Prerequisite

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

### Installing the SDK

To start using the **Midaz SDK for TypeScript**, you **must** install the dependencies using the following command:

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

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

Once installed, follow the examples in the [*Quick Start Guide*](#quick-start-guide) section to learn how to use the **Midaz SDK for TypeScript**.

## Authentication

***

The **Midaz SDK for TypeScript** gives you flexibility when it comes to authentication. You can choose the method that fits your setup:

#### API key

You can use a simple authentication method by adding an API Key.

<CodeGroup>
  ```typescript TypeScript theme={null}
  const client = createClient({
    apiKey: 'your-api-key',
    environment: 'sandbox',
  });
  ```
</CodeGroup>

#### Access Manager authentication

For integration with external identity providers using OAuth:

<CodeGroup>
  ```typescript TypeScript theme={null}
  const client = createClient({
    accessManager: {
      enabled: true,
      address: 'https://auth.example.com',
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret',
    },
    environment: 'sandbox',
  });
  ```
</CodeGroup>

The Access Manager handles token handling for you, such as acquisition, caching, and renewal, so you don’t have to worry about managing tokens manually.

<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

***

In the following sections, you will find practical code examples to help you understand how to use the **Midaz SDK for TypeScript**.

### Create a client

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

**Example:**

<CodeGroup>
  ```bash bash theme={null}
  import { createClient } from 'midaz-sdk';

  const client = createClient({
    apiKey: 'your-api-key',
    environment: 'sandbox', // Options: 'development', 'sandbox', 'production'
  });
  ```
</CodeGroup>

### Create an Asset

The best way to create assets is with the **Builder Pattern** using `createAssetBuilder`.

**Example:**

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createAssetBuilder } from '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 will add the required `name` and `assetCode` fields to the builder `const assetInput = createAssetBuilder('US Dollar', 'USD')`, then add any additional properties with `with*` methods.

### Create an Account

The easiest way to create accounts is with the **Builder Pattern** using `createAccountBuilder`.

**Example:**

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createAccountBuilder } from '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 will add the required `name` and `assetCode` fields to the builder `const accountInput = createAccountBuilder('Savings Account', 'USD')`, then add any additional properties with `with*` methods.

### Create a Transaction

The easiest way to create accounts is with the **Builder Pattern** using `createTransactionBuilder`.

**Example:**

<CodeGroup>
  ```typescript TypeScript expandable theme={null}
  import { createTransactionBuilder } from '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 will add all properties with `with*` methods.

### Error recovery

Use enhanced error recovery for critical operations

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { withEnhancedRecovery } from '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 '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 to provide a clean, modular, and scalable developer experience. It is organized into three key layers, as shown in *Figure 1*, each serving a distinct purpose.

* **Client interface**: This is the primary entry point for SDK users. It manages configurations such as API keys and environments, initializes services lazily, and exposes all available functionality in a unified and discoverable manner.
* **Entity services layer**: This layer contains domain-specific services (e.g., Accounts, Assets, and Transactions) and offers consistent methods for operations such as create, get, update, delete, and list. Additionally, specialized operations are included based on each entity's specific needs.
* **Core services layer**: These foundational utilities are used by all entity services. 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/HGN18tk9FWtM6lAM/images/en/docs/sdk-typescript-architecture.jpg?fit=max&auto=format&n=HGN18tk9FWtM6lAM&q=85&s=6eee48831875c99f252b738e1cc529cb" alt="" width="1275" height="1225" data-path="images/en/docs/sdk-typescript-architecture.jpg" />
</Frame>

The architecture of the SDK 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** employs a builder design pattern to help you assemble advanced objects in a straightforward, safe, and adaptable way. Instead of pre-defining a set of inputs, it provides a step-by-step, fluent, chainable interface that walks you through the entire process.

**Builder functions in the SDK:**

* Assist you by informing you of the parameters in advance.
* Let you modify optional fields using `.with*()` methods and chain them.
* Aid in avoiding invalid states through a guiding structure.
* Hide internal complexity, which leads to 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 concentrates on distinct aspects of the financial domain, such as accounts, assets, or transactions.

These services provide a reliable method for creating, retrieving, updating, and deleting data while allowing meaningful interactions with each type of entity.

Additionally, they offer specialized features designed for their particular use case, enabling you to handle financial data with greater confidence and efficiency.

| 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 can access each of these services through the SDK client. They follow a consistent structure, making it easier to build and maintain financial features.

<Tip>
  Wan 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 a set of utility modules to streamline common operations, whether you're optimizing performance, handling errors, managing configurations, or enhancing observability.

These tools are designed to work seamlessly with the rest of the SDK and help you build robust 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, a structured error is thrown. This error includes key fields to help you understand and resolve the issue:

* `code`: A short, consistent identifier for the error type.
* `message`: A human-readable description.
* `details`: (Optional) Additional context or metadata.
* `status`: The HTTP status code, when available.

Here’s how you might handle an error:

<CodeGroup>
  ```typescript TypeScript theme={null}
  try {
    await client.transactions.create(transaction);
  } catch (err) {
    console.error(`Error (${err.code}): ${err.message}`);
    // Optionally: inspect err.details or err.status
  }
  ```
</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 calling SDK methods to avoid `invalid_input`.
* **Double-check auth** when facing `unauthorized` or `forbidden`.
* **Retry** on transient issues like `internal_error` or `service_unavailable`.
* **`Usedetails`** to surface helpful debug info in development logs.

The SDK is built to keep errors predictable and actionable, so you can focus on building, not debugging.

<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 to keep things smooth, automated, and production-ready:

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

## Want to contribute?

***

If you're thinking about contributing 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 everything you need to know to get started.

## License

***

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