# Welcome Source: https://docs.lerian.studio/en/index Guides, platform capabilities, API references, and integration tutorials for the Lerian core banking platform: Midaz, the products around it, Brazil Rails, and Interfaces. # Build core banking on primitives you control. Guides, platform capabilities, and API references for the entire Lerian ecosystem, from the double-entry ledger up. [Explore the products →](/en/products/about-products) [See the integration diagrams](/en/diagrams/introduction) [Get started →](/en/start-here/getting-started) · [Start with the fundamentals →](/en/start-here/fundamentals/core-banking/what-is-core-banking) · [API reference →](/en/reference/introduction) ## Go from zero to your first transaction. 01 ### [Model your ledger](/en/start-here/getting-started) Set up your Organization, Ledger, and Accounts. 02 ### [Post a transaction](/en/products/midaz/transactions-overview) Move value with strict double-entry guarantees. 03 ### [Deploy anywhere](https://github.com/LerianStudio/helm) BYOC on AWS, GCP, on-prem, or Lerian Cloud. ## Products Lerian is a complete, modular core banking platform. Start with the components that fit your operation and compose them into the platform you need. ### [![](https://mintcdn.com/lerian-49cb71fc/5dD4BTy_lmC0R8p5/images/icons/midaz.svg?fit=max\&auto=format\&n=5dD4BTy_lmC0R8p5\&q=85\&s=016d1c1908b9ae42d80bb50a49d90bad) Midaz CORE](/en/products/midaz/what-is-midaz) The double-entry ledger at the platform's core: organizations, ledgers, accounts, and transactions you fully control. Get started with Midaz → ### [![](https://mintcdn.com/lerian-49cb71fc/5dD4BTy_lmC0R8p5/images/icons/tracer.svg?fit=max\&auto=format\&n=5dD4BTy_lmC0R8p5\&q=85\&s=84a6c37f8f2cf59ada19656e3559f3f6) Tracer](/en/products/tracer/what-is-tracer) Apply real-time spending controls and analyze transaction risk as money moves. Trace a transaction → ### [![](https://mintcdn.com/lerian-49cb71fc/5dD4BTy_lmC0R8p5/images/icons/matcher.svg?fit=max\&auto=format\&n=5dD4BTy_lmC0R8p5\&q=85\&s=55ca7734fc78f84f2aacfc823802af86) Matcher](/en/products/matcher/what-is-matcher) Reconcile transactions across banks, processors, and ERPs, and work through the exceptions that don't match. Reconcile a batch → ### [![](https://mintcdn.com/lerian-49cb71fc/5dD4BTy_lmC0R8p5/images/icons/flowker.svg?fit=max\&auto=format\&n=5dD4BTy_lmC0R8p5\&q=85\&s=82555c849a03e5f2d4d4d5c6b8372a7a) Flowker](/en/products/flowker/what-is-flowker) Orchestrate financial workflows and connect third-party services through its API. Design a workflow → ### [ Lender](/en/products/lender/what-is-lender) Run the full credit journey, from product definition and origination through servicing, accounting, and audit. Explore Lender → ### [![](https://mintcdn.com/lerian-49cb71fc/5dD4BTy_lmC0R8p5/images/icons/reporter.svg?fit=max\&auto=format\&n=5dD4BTy_lmC0R8p5\&q=85\&s=3a2ac26a15de0a860fc4566278f28c2a) Reporter](/en/products/reporter/what-is-reporter) Turn ledger and platform data into audit-ready reports from configurable templates. Build a report → ## Brazil Rails and Interfaces Where the platform meets Brazil's payment system. A Brazil rail is Lerian's own messaging with BACEN, Núclea, or Dataprev. An interface is the product surface over a rail, from Lerian or from a connectivity partner. Either way, you keep your ledger, your data, and your business logic. ### Brazil Rails What are Brazil Rails? The Brazil Rails tab documents Brazil's national payment and regulatory systems. → [Open](/en/rails/what-are-brazil-rails) Native messaging The two ways the Lerian platform reaches Brazil's payment system. → [Open](/en/rails/native-messaging) SPI (Pix) A native Pix connector to BACEN's SPI. → [Open](/en/rails/spi/what-is-lerian-spi) SPB (TED) Lerian SPB is your direct, non-intermediated BACEN STR connector. → [Open](/en/rails/spb/what-is-lerian-spb) Other rails SLC, SILOC, STA, SISBAJUD, CCS, SCR, BC Correios, SRC, and Consignado CLT. → [Open](/en/rails/what-are-brazil-rails) Lerian Cabine The operators' console over Lerian's native rails. → [Open](/en/rails/cabine/what-is-lerian-cabine) ### Interfaces What are Interfaces? Lerian's integrations to payment products. → [Open](/en/interfaces/introduction) Pix Lerian The interface that connects Midaz to Lerian SPI. → [Open](/en/interfaces/pix-lerian) Pix JD Direct Pix via JD: participate as a direct participant on SPI and DICT. → [Open](/en/interfaces/pix-jd/direct-pix-via-jd) Pix BTG Indirect Pix via BTG: reach SPI and DICT as an indirect participant through BTG. → [Open](/en/interfaces/pix-btg/indirect-pix-overview) TED JD Understand how the Bank Transfer plugin handles SPB communication. → [Open](/en/interfaces/ted-jd/ted-in-lerian) TED Lerian The interface that connects Midaz to Lerian SPB. → [Open](/en/interfaces/ted-lerian/what-is-ted-lerian) JD Courier Share one JD channel and one ISPB between core banking engines. → [Open](/en/interfaces/jd-courier/what-is-jd-courier) Payments BTG Issue boletos and pay bills through the Payments module in Lerian Console. → [Open](/en/interfaces/payments-btg/boleto-and-bill-payment) ## Lerian Console One web interface to operate Lerian products: dashboards, settings, and per-product modules in a single place. [About the Console →](/en/platform/console/about-lerian-console) [Console settings →](/en/platform/console/about-settings) ## Platform ### [Access Manager](/en/platform/access-manager) Control who can do what, across your Lerian products. ### [Streaming Hub](/en/platform/streaming-hub/what-is-streaming-hub) Consume platform events and fan them out to your systems through signed webhooks, queues, or a pull API (the platform's event delivery edge). ### [Multi-tenancy](/en/platform/multi-tenancy) How Lerian Cloud isolates tenants. ### [Observability](/en/platform/observability) Centralized logs, metrics, and traces across services. Also in Platform: [Deploy](https://github.com/LerianStudio/helm) · [Lifecycle Management](/en/platform/lifecycle-management) · [Licensing](/en/platform/licensing/license-manager) ## News Features, improvements, and changes across the platform and its documentation. [View latest announcements →](/en/news/latest-news) [GitHub](https://github.com/LerianStudio) [LinkedIn](https://www.linkedin.com/company/lerianstudio) [Instagram](https://www.instagram.com/lerian.studio) [Dev.to](https://dev.to/lerian) © 2026 Lerian. All rights reserved. # Our plugins Source: https://docs.lerian.studio/en/products/about-plugins Explore the plugins available across Lerian products: what each plugin does, when to enable it, and how it fits with Midaz and other core services. Instead of building custom features from scratch, you can plug in what you need and keep everything else stable, scalable, and secure. Plugins run alongside the product platform and add new logic, endpoints, or workflows to support specific business needs. Plugin availability is product-specific. The currently documented plugins below extend Midaz. In this documentation the plugins live in the [Interfaces](/en/interfaces/introduction) section of the Brazil Rails tab, as Pix JD, Pix BTG, TED JD, Payments BTG, and Plugin SISBAJUD. The same section also documents Pix Lerian, TED Lerian, and JD Courier. > [!NOTE] > > **CRM** is no longer a plugin. Midaz embeds CRM as a core component, and CRM needs no additional license. See [CRM Overview](/en/products/midaz/crm/crm-overview) for details. > [!NOTE] > > **Fees Engine** is part of Midaz rather than a standalone plugin, a licensed capability embedded in the unified Midaz Ledger process. See [Fees Engine overview](/en/products/midaz/fees/fees-engine-overview) for details. ## Available plugins for Midaz *** > [card] [Pix](/en/interfaces/pix/pix-overview) > > Integrate Pix with Midaz, including SPI and DICT services, to manage keys, transactions, claims, and regulatory workflows. > [card] [Bank Transfer (TED)](/en/interfaces/ted/ted-overview) > > Process electronic transfers between banks through TED, managing transaction validation, settlement, and regulatory compliance. > [card] [Payments (Boletos & Bill Payment)](/en/interfaces/payments-btg/boleto-and-bill-payment) > > Issue boletos and pay bills (DARF taxes and utility invoices) through the Payments module in Lerian Console, recorded in your Midaz ledger. > [card] [Plugin SISBAJUD](/en/interfaces/plugin-sisbajud/plugin-sisbajud-how-it-works) > > Receive SISBAJUD judicial orders and run the blocks, transfers and releases on Midaz accounts. ## Why plugins are separate services *** Lerian designed Midaz to be composable. This gives you: * **Flexibility**: Add, update, or remove plugins without downtime * **Separation of concerns**: Business-specific logic lives in the plugin, not the core * **Better control**: Each plugin has its own versioning, deployment, and monitoring * **Safe evolution**: The platform can grow without breaking your integrations > [!TIP] > > Think of a plugin as a microservice with a clear purpose. It feels native to the platform, but it evolves on its own schedule. ## What a plugin can do *** A plugin can: * Expose new APIs * Persist and transform data * Run background jobs and scheduled tasks * React to events, such as new transactions or ledger updates * Define its own configuration, rules, and access policies ## Enable a plugin *** > [!NOTE] > > If you're interested in enabling a plugin, talk to a Lerian representative. We'll help you evaluate, license, and deploy the right setup for your use case. # Our products Source: https://docs.lerian.studio/en/products/about-products Discover Lerian products, platform services, Brazil Rails, and Interfaces, and how modular building blocks compose into a complete core banking platform. Lerian is a complete, modular core banking platform. Each product covers one financial domain end to end. You adopt one product on its own, or you combine several into one platform. Lerian has six products: Midaz, Tracer, Matcher, Flowker, Lender, and Reporter. Lerian licenses every product to institutions. ## Products *** > [card] [Midaz](/en/products/midaz/what-is-midaz) > > Create ledgers, manage transactions, and use core entities like accounts and assets, with CRM and the Fees Engine built in as part of Midaz. Connect rails like Pix and TED. > [card] [Tracer](/en/products/tracer/what-is-tracer) > > Validate transactions in real time, apply rules and spending limits, and return ALLOW, DENY, or REVIEW decisions. > [card] [Matcher](/en/products/matcher/what-is-matcher) > > Validate external transactions against the ledger and surface mismatches. Built for accuracy, traceability, and automation. > [card] [Flowker](/en/products/flowker/what-is-flowker) > > Orchestrate transaction flows using validations, approvals, and external triggers with logic and plugin coordination. > [card] [Lender](/en/products/lender/what-is-lender) > > Run the credit journey end to end: loan products, origination, servicing, accounting, and Brazil-first regulatory support. > [card] [Reporter](/en/products/reporter/what-is-reporter) > > Generate and download reports from reusable templates, filter their data, and manage recurring reporting deadlines. Supports HTML, XML, CSV, PDF, and TXT output. ## Platform services *** Console, Access Manager, Streaming Hub, Multi-tenancy, and Observability are platform services. They serve every product and are not products themselves. > [card] [Console](/en/platform/console/about-lerian-console) > > Operate every Lerian product from one web interface, with one login and one navigation. > [card] [Access Manager](/en/platform/access-manager) > > Control human and machine access across the products, and issue the tokens each service trusts. > [card] [Streaming Hub](/en/platform/streaming-hub/what-is-streaming-hub) > > Consume platform events and fan them out to your systems through signed webhooks, queues, or a pull API. > [card] [Multi-tenancy](/en/platform/multi-tenancy) > > Serve independent institution contexts from one deployment, and keep each request inside its own tenant. > [card] [Observability](/en/platform/observability) > > Collect metrics, traces, and logs from Lerian workloads through OpenTelemetry. ## Brazil Rails and Interfaces *** A Brazil rail is Lerian-owned messaging software that connects your institution to BACEN, to a market infrastructure, or to Dataprev, with no intermediary. An interface is the product surface over a rail. Pix Lerian is the interface over Lerian SPI, and TED Lerian is the interface over Lerian SPB. Pix JD, Pix BTG, TED JD, and Payments BTG are partner interfaces that ship as separately deployed Midaz plugins. JD Courier lets two or more core banking engines share one JD channel and one ISPB. Plugin SISBAJUD runs SISBAJUD court orders on Midaz. > [card] [Brazil Rails](/en/rails/what-are-brazil-rails) > > Read what each rail carries, and how Lerian native messaging reaches BACEN and the market infrastructures. > [card] [Interfaces](/en/interfaces/introduction) > > Read the API, the ledger integration, and the operational controls for each payment product. # Building a complete core banking Source: https://docs.lerian.studio/en/products/building-a-complete-core-banking How the Lerian pieces come together into one working core banking: what connects to what, and how much you wire yourself versus what comes pre-configured. In [Fundamentals](/en/start-here/fundamentals/core-banking/what-is-core-banking) you learned the concepts. This page is how the Lerian pieces come together into one working core banking. A complete Lerian core banking combines Midaz with the products and interfaces you choose. You can adopt a product on its own. That is by design. Midaz embeds CRM and the Fees Engine. Other pieces deploy separately, and Lerian does not pre-wire them to each other. You connect them in a setup step. How much of this you do depends on who runs your infrastructure: * **Managed**: Lerian runs your infrastructure and wires the pieces at deploy time. You open the Console, enable the products, and use them. You set no environment variables and make no integration calls. (You won't need the rest of this page.) * **Self-hosted / BYOC**: you run the infrastructure, so you do the wiring. Configure each product's URLs and environment, and deploy it. The rest of this page walks that. After you connect it, you can operate from the Console or call the APIs directly. That is a UX choice and needs no extra wiring. ## Start with the ledger *** Midaz is the ledger foundation of a Lerian core banking. Stand it up first when the capabilities you adopt record to Midaz. **CRM is already part of Midaz.** Midaz includes the holders and aliases you learned about. You wire nothing extra. CRM has no switch to turn on. → [Set up Midaz](/en/products/midaz/midaz-setup) · [CRM in Midaz](/en/products/midaz/crm/crm-overview) ## Connect the pieces to the ledger *** Most other pieces are standalone services. The Fees Engine is the exception, because it runs inside the ledger process. The pieces do not all connect the same way. Here is who calls whom at runtime: ![Runtime flow across your application, the payment plugins, the Fees Engine, Tracer, Reporter, and the Midaz ledger](https://mintcdn.com/lerian-49cb71fc/Gw2zNPznAbAjotN1/images/en/d2/flow-core-banking.svg?fit=max\&auto=format\&n=Gw2zNPznAbAjotN1\&q=85\&s=c72ab5a19b8cf1cc340e0f11599bd62b) Who calls whom at runtime * **Payment interfaces write to the ledger for you.** Your application calls a [payment interface](/en/interfaces/introduction) such as TED or Pix. The interface moves the money and records the operations in Midaz, even from its own background workers. Your application does not touch the ledger for those movements. Partner interfaces ship as Midaz plugins: separately deployed services that extend Midaz. Each interface reaches Midaz at the address set in its own environment. Lerian sets it in a managed setup, and you set it in BYOC (for example `MIDAZ_URL_TRANSACTION` for Pix JD). → [TED setup](/en/interfaces/ted-jd/ted-configuration) * **The Fees Engine runs inside the ledger.** The **Fees Engine** is part of the Midaz ledger process. When a configured fee package applies, Midaz adds the fee calculations to the transaction you submit. No separate fee service sits between your application and the ledger. Your application can still call the fees endpoints on the same process to estimate fees before it submits. For any movement you record without a payment interface, your application writes to the Midaz API directly. → [Connect the Fees Engine to Midaz](/en/products/midaz/fees/connecting-fees-to-midaz) * **Reporter reads configured data sources.** It reads those sources in one direction only, to build statements and reports, and it never writes back. In a managed setup, Lerian configures the agreed data sources during onboarding. In self-hosted or BYOC deployments, configure a data source before you build reports that use it. → [Reporter](/en/products/reporter/reporter-quick-start) * **Tracer connects to Midaz through configuration.** Set `TRACER_BASE_URL` to the Tracer gRPC address, and Midaz initializes a reservation client. Midaz calls reserve, confirm, and release only when `tracer.mode` is `advisory` or `enforce`. When `TRACER_BASE_URL` is unset, Midaz makes no reservation call, and a ledger in `enforce` mode applies its `failPosture`: when it is `closed`, Midaz refuses the transaction with `0178`. On a ledger in `enforce` mode, Ledger HTTP v1 refuses a transaction that moves balances with `0574`. Midaz honors a Tracer skip only when the request asks for it and the ledger enables `allowTracerSkip`. → [Tracer integration guide](/en/products/tracer/integration-guide) Your application can also integrate with Tracer on its own. > [!NOTE] > > Tracer checks your configured policies and limits, not account balances. The ledger stays the source of truth for what an account holds. The exact URLs, credentials, and environment settings live in each product's own setup docs (linked above). ## One login across the pieces *** The pieces share authentication through **Access Manager**, so they work as one product with one login. Access Manager issues the tokens each service trusts, and it holds the credentials each piece uses. Keep those details in one place, and point every piece at it. → [Access Manager](/en/platform/access-manager) ## Deploy the stack *** There's no single "install everything" bundle. Deploy each selected component with its supported distribution artifact and bring them up in order: **Midaz → Access Manager → products and interfaces → Console** The Console comes last because it needs the others already running. → [Helm charts](https://github.com/LerianStudio/helm) ## Operate it from the Console *** After everything runs, the **Console** is your single pane of glass. Enable the pieces and manage them with one login. When you enable a module in the Console, it turns on in the interface and shares the login. The piece-to-ledger wiring is the deployment step above, and the Console does not do it for you. → [Lerian Console](/en/platform/console/about-lerian-console) ## On a managed setup *** If Lerian runs your infrastructure, Lerian already did all the wiring above. From your side, you enable the modules in the Console and start using them. You set no environment variables, and you run no deployment. The integration journey on this page is what Lerian handles underneath. ## Going further (optional) *** You assemble a complete Lerian core banking from modular building blocks. Add **[Matcher](/en/products/matcher/what-is-matcher)** for reconciliation and **[Flowker](/en/products/flowker/what-is-flowker)** for workflow automation when their capabilities fit your operation. Matcher runs in the SaaS or the BYOC model, and you sign in through Access Manager. Flowker runs in the SaaS model only. Add **[Lender](/en/products/lender/what-is-lender)** to run the credit journey, from loan products through origination and servicing. # About Midaz Source: https://docs.lerian.studio/en/products/midaz/about-midaz Explore Midaz's Ledger service, its Onboarding and Transaction domains, and its embedded CRM and Fees capabilities. Midaz is a core ledger (The core financial book that records all transactions, balances, and operations for an organization. It is the single source of truth for a business unit's finances.). Financial institutions use it to build, operate, and scale their transactions on a modular foundation. You keep full control of your stack. Midaz's Ledger service has two core domains: **Onboarding** and **Transaction**. It also embeds CRM for holders and instruments, and Fees. Together, they provide the components to configure, execute, and govern financial flows. > [!NOTE] > > This domain-driven architecture keeps configuration (Onboarding) and execution (Transaction) separate but integrated. ## Domains and APIs *** ### Onboarding domain In the **Onboarding Domain**, institutions structure their financial operations. They configure the essential entities of their ledger. This domain sets the rules, accounts, and relationships that govern how the ledger records and interprets transactions. #### Components of the Onboarding Domain * **Organizations**: A business entity that runs on Midaz, such as a bank, fintech, or subsidiary. Each organization holds its own ledgers and configurations. One platform then supports multi-entity operations. * **Ledgers**: The core financial book of an organization. Ledgers (The core financial book that records all transactions, balances, and operations for an organization. It is the single source of truth for a business unit's finances.) track every balance, transaction, and operation. They protect the integrity of all financial data. Think of a ledger as the single source of truth for a business unit's finances. * **Assets (A unit of value tracked in the ledger: traditional currencies (BRL, USD), digital currencies (BTC), or custom units like loyalty points. Every account is linked to exactly one asset.)**: The units of value that the ledger tracks, such as BRL, USD, BTC, or loyalty points. With this flexibility, institutions manage traditional currencies, digital assets, and custom reward programs in the same system. * **Account Types (A classification defining the nature and purpose of an account, such as checking, savings, escrow, or settlement. Account types enable proper transaction routing.)**: Classifications that define the nature and purpose of accounts, for example checking, savings, escrow, or settlement. With `validateAccountType` enabled, a new non-external Account's `type` must match a registered value. Operation Routes separately validate accounts during route processing. * **Accounts**: The fundamental units of value storage, where money or any asset lives. Each account always links to an Asset. You can group accounts into segments or portfolios to reflect your business structure. * **Portfolios (A grouping of accounts belonging to the same account holder, business unit, or purpose. It ties together checking, savings, and investment accounts for a unified view.)**: A group of accounts that belong to the same customer, business unit, or purpose. For example, one client may hold checking, savings, and investment accounts in different currencies. A portfolio ties them together for a unified view. * **Segments (A classification applied to accounts that share characteristics, like account holder tiers (VIP, Student) or regional divisions. Rules and pricing can differ by segment.)**: Groups of accounts that share traits, such as customer tiers or regional divisions, for example VIP or Student. Segments help you enforce different rules, prices, or benefits across your customer base. > [!TIP] > > The Onboarding Domain configures how your financial world is structured. It gives consistency before any transaction takes place. ### Transaction Domain After you configure the Onboarding Domain, the **Transaction Domain** takes over. It handles the real-time execution and movement of funds. #### Components of the Transaction Domain * **Balances**: The current balance of any account, including its available and on-hold amounts. This real-time snapshot supports validations, pre-transaction checks, and customer-facing displays. * **Operation Routes (A reusable template that defines the rules for one leg of a financial transaction: which accounts participate, in what direction, and under what accounting annotation.)**: Reusable templates that define the rules for each leg of a financial transaction. A route specifies which accounts participate, in what direction (source, destination, or bidirectional), and under what accounting annotation. Every transaction type then follows consistent business rules. * **Operations (The atomic unit of movement in the ledger: a single debit or credit. Every transaction is composed of one or more operations. Operations make transactions precisely traceable for compliance and reporting.)**: The atomic unit of movement in the ledger, a single debit or credit. The ledger breaks every financial movement into operations. This gives a complete audit trail (A chronological, immutable record of every action and transaction in the system, essential for regulatory compliance and dispute resolution.) and precise traceability for compliance and reporting. * **Accounting Routes (A complete transaction blueprint composed of multiple Operation Routes. It defines all the debits and credits involved in a transaction type, so each transaction of that type complies with double-entry rules. Exposed as transactionRoute in the API.)**: Complete transaction blueprints that combine multiple Operation Routes. For example, a Pix Transfer route defines its source and destination rules. When you enable Accounting Route validation, Midaz validates the transaction route and its Operation Routes for that transaction type. The API exposes this as the `transactionRoute` resource. * **Transactions**: The actual movement of value between accounts. A transaction can involve multiple **Operations**, such as fees, taxes, or splits. This supports complex financial flows, like marketplace payouts or multi-party settlements, in a single atomic event. > [!TIP] > > The Transaction Domain processes every movement in compliance with the business and accounting rules you configure upstream. ## Domain reference *** Midaz is a domain-driven ledger platform. | Domain | Purpose | Key APIs | | :- | :- | :- | | **Onboarding** | Structure and configuration of the financial ecosystem. | Organizations, Ledgers, Assets, Account Types, Accounts, Portfolios, Segments | | **Transaction** | Execution, movement, and accounting of financial operations. | Balances, Accounting Routes (`transactionRoute`), Transactions, Operation Routes, Operations | # Account types Source: https://docs.lerian.studio/en/products/midaz/account-types Register Account Types to enforce classification per Ledger, validate the type field on account creation, and align account behavior with your accounting rules. Account Types classify the accounts in your ledger. Each [**Account Type**](/en/reference/products/midaz/v2/create-account-type) has a name, a description, a unique key value, and a default [balance direction](/en/products/midaz/balance-overdraft). You register the Account Types that match your accounting structure. When you enable Account Type validation, the ledger checks the `type` field of every new non-external Account against these registered types. ## How Account Type validation works ### Enabling Account Type validation You enable Account Type validation per ledger through the [Ledger Settings API](/en/products/midaz/ledgers#ledger-settings). Send a `PATCH` request to the Ledger Settings endpoint: ```json PATCH /v2/organizations/{organization_id}/ledgers/{ledger_id}/settings theme={null} { "accounting": { "validateAccountType": true } } ``` ### Behavior of the `type` field in Accounts API When you create an Account, the `type` field behavior depends on the validation setting: * **Validation disabled (default):** You must provide a `type`. It accepts any string value up to 256 characters. The ledger does not compare it to registered Account Types. * **Validation enabled:** The `type` field must match the `keyValue` of a registered Account Type. Midaz stores new `keyValue` values in lowercase and compares the value case-insensitively. Use lowercase values in requests and configuration. If it does not match, the ledger rejects the account with a validation error. External accounts skip this check. > [!TIP] > > Midaz checks the `type` only when you create an Account. You cannot change the `type` of an existing Account. ### The `keyValue` field > [!NOTE] > > The `keyValue` field identifies an Account Type. It has these constraints: > > * **Immutable:** You set `keyValue` when you create the Account Type. You cannot change it afterward. The Update Account Type endpoint does not accept this field. > * **Unique per ledger:** Each `keyValue` must be unique within a ledger. > * **Used for validation:** When you enable `validateAccountType` in Ledger Settings, the ledger compares the `type` field of each non-external Account case-insensitively with a registered `keyValue`. The ledger rejects any non-external Account with an unregistered `type`. ## Managing Account Types *** You manage Account Types through the API or the Lerian Console. * [Create an Account Type](/en/reference/products/midaz/v2/create-account-type): Register a new Account Type for your Ledger. * [List Account Types](/en/reference/products/midaz/v2/list-account-types): Retrieve all Account Types configured in your Ledger. * [Retrieve an Account Type](/en/reference/products/midaz/v2/get-account-type-by-id): Get detailed information about a specific Account Type. * [Update an Account Type](/en/reference/products/midaz/v2/update-account-type): Modify the definition of an existing Account Type. * [Delete an Account Type](/en/reference/products/midaz/v2/delete-account-type): Remove an Account Type that is no longer in use. > [!NOTE] > > **See also** > > * [Transaction Routing](/en/products/midaz/transaction-routing-entities): Operation Routes use `ruleType: account_type` to validate an account's `type` against the route's configured `account.validIf` values. > * [Accounting Entries](/en/products/midaz/accounting-entries): How Midaz resolves debit and credit rubrics for the accounts these types classify. # Accounting Entries Source: https://docs.lerian.studio/en/products/midaz/accounting-entries Map transaction actions and route directions to accounting classifications, and annotate every operation with its accounting code and description. Accounting Entries (also known as **Rubricas**) map a transaction action and route direction to an accounting `code` and `description`. They annotate an operation after route resolution. Operation Route rules and transaction legs determine the participating accounts. ## What are Accounting Entries *** A **rubric** maps a transaction action and route direction to an accounting classification. Instead of computing each classification by hand, you register rubrics once. Midaz then resolves them automatically as it processes transactions. Each rubric carries: * **`code`**: an accounting code (for example, `1.1.1.001`). * **`description`**: a human-readable label for the entry (e.g., `Customer checking — outbound`). When the engine processes a transaction with route validation (`accounting.validateRoutes`) enabled and a matching rubric registered, it resolves the rubric for each operation. It records the resulting **`routeCode`** and **`routeDescription`** on the operation. This gives you a complete audit trail from transaction to operation to rubric. Your teams can trace exactly which accounting rule applied to each movement. > [!NOTE] > > Configure rubrics per action on each Operation Route. For `direct` and `commit` actions, **Source** routes require the **debit** rubric and **Destination** routes require the **credit** rubric. Dedicated `block` and `unblock` rubrics are optional. If they are absent, Midaz resolves the `direct` rubric for those actions. Source-side `hold` and `cancel` actions require **both** rubrics, and `overdraft` requires **both** on every supported route type. **Bidirectional** routes always require **both**. ## The 9 action types *** Each action is a distinct transactional event. The first five actions cover the transaction lifecycle. The next three cover overdraft, block, and unblock movements. The last one covers transactions that span Ledgers. An Operation Route can map different debit and credit rubrics for each action. Every stage of an operation then receives the right accounting annotation. The Hold and Cancel rows show a balance with `direction: credit`. On a `direction: debit` balance, a hold increases `available` and a cancel decreases it. `onHold` moves the same way on both. | Action | Identifier | Description | | :- | :- | :- | | **Direct** | `direct` | Immediate, single-step debit/credit with no intermediate stages (e.g., a fee or adjustment). | | **Hold** | `hold` | Reserves funds by creating a pending movement (moves value from `available` to `onHold` on the source account). | | **Commit** | `commit` | Confirms a previously held amount, releasing the `onHold` value to the destination account. | | **Cancel** | `cancel` | Cancels/reverses a hold, returning the `onHold` value to the `available` balance on the source account. | | **Revert** | `revert` | Reverses an `APPROVED` transaction by creating a counter-transaction that undoes the original. | | **Overdraft** | `overdraft` | Classifies overdraft movements. The **debit** rubric marks overdraft usage (the deficit grows) and the **credit** rubric marks repayment (the deficit shrinks). Both rubrics are required when this entry is configured. | | **Block** | `block` | Optionally classifies a fund-block movement that freezes value on an account (for example, an `asset-freeze`). | | **Unblock** | `unblock` | Optionally classifies the release of previously blocked funds back to the `available` balance. | | **Cross-ledger** | `crossLedger` | Classifies the External Account legs that Midaz adds when a transaction spans Ledgers. The **debit** rubric marks value that arrives from another Ledger. The **credit** rubric marks value that leaves to another Ledger. Both rubrics are required. | **Overdraft** classifies companion operations that the engine generates automatically during overdraft usage and repayment. For every supported route type and direction, configure both the debit and credit rubrics. **Block** and **unblock** can use dedicated rubrics for operations that the block and unblock transaction endpoints produce. Without those rubrics, those actions use the `direct` rubric. When needed, register dedicated rubrics for these actions in the same way as for the other actions. > [!TIP] > > Each action can point to different debit and credit rubrics on the same Operation Route. A route that maps `hold`, `commit`, `cancel`, `revert`, or `overdraft` also needs `direct` (`0164`). On source and bidirectional routes, `hold`, `commit`, and `cancel` go together (`0163`). If you enable strict validation (below), cover every action your transactions emit. ## Configuring Accounting Entries *** You register rubrics through the API as part of your Operation Routes. The `accountingEntries` block on a route defines one entry per action. Each entry carries its `debit` and/or `credit` rubric: ```json accountingEntries theme={null} { "accountingEntries": { "direct": { "debit": { "code": "1.1.1.001", "description": "Customer checking — outbound" }, "credit": { "code": "1.1.1.002", "description": "Customer checking — inbound" } } } } ``` You manage these entries through the Operation Route endpoints. See [Create an Operation Route](/en/reference/products/midaz/v2/create-operation-route) and [Update an Operation Route](/en/reference/products/midaz/v2/update-operation-route). For the full configuration flow, refer to [Transaction Routing](/en/products/midaz/transaction-routing-entities#4-configure-accounting-entries-actions). ## Validation modes *** Midaz reacts to a missing rubric based on the Ledger's accounting settings. Two distinct gates control this behavior: ### Default (graceful) By default (`accounting.validateRoutes` disabled), Midaz does not resolve rubrics at all: the transaction proceeds normally and the `routeCode` and `routeDescription` fields stay empty (nil) for every operation. It raises no error. ### Strict (opt-in) Set `accounting.validateRoutes` to `true` in the [Ledger Settings](/en/products/midaz/ledgers#ledger-settings) to enforce route validation. In strict mode, Midaz returns `0157` when no Operation Route of the Transaction Route has an entry for the requested action. It returns `0117` when a leg names no Operation Route, or one that the Transaction Route does not provide for that action. An overdraft movement on a route without an `overdraft` entry returns `0492`. ```json PATCH /v2/organizations/{organization_id}/ledgers/{ledger_id}/settings theme={null} { "accounting": { "validateRoutes": true } } ``` > [!TIP] > > Use **strict mode** in production ledgers where every transaction type needs an accounting classification. The graceful default helps while you onboard routes. In production, it can silently leave movements without a classification. When Midaz finds a matching rubric, it annotates the operation with two fields: * **routeCode**: the `code` of the resolved `AccountingRubric` for that action and direction. * **routeDescription**: the description of the resolved rubric, populated alongside `routeCode`. # Accounting Source: https://docs.lerian.studio/en/products/midaz/accounting-in-midaz Get an overview of accounting in Midaz: Chart of Accounts, Account Types, Accounting Entries, and Operations that keep every posting balanced and traceable. Midaz records accounting for real-time financial systems. It supports route-driven double-entry flows for direct transactions, as well as lifecycle actions such as cancellation. Cancellation operates on the source side only. Route validation is disabled by default. Enable it to validate the configured account and accounting-entry rules. Midaz supports digital products, embedded finance, and high-volume operations. This page is the entry point for the Accounting section. It introduces the core primitives and shows how they fit together. It also points you to the reference pages and to a hands-on walkthrough of accounting end to end. ## How the primitives relate *** Midaz turns business events into balanced ledger postings. A small set of primitives builds on each other: #### Chart of Accounts This is the structure of balances your product needs. Midaz has no dedicated Chart of Accounts API. Instead, you model it on a ledger from assets, accounts, segments, portfolios, and account types. The `code` field on an Accounting Entry (for example `1.1.1.001`) carries the traditional account number for each posting. #### Account Types These are reusable classifications that you assign to accounts. Each account type has a name, a key value, a description, and a default [balance direction](/en/products/midaz/balance-overdraft). You use account types to group accounts in your financial structure. #### Accounting Entries (Rubricas) A route does not need an entry for every transaction action. When it emits an action, the entry must satisfy the route-specific debit and credit requirements. Each configured entry contains the debit and/or credit rubric required by its operation route. Every present rubric has a `code` and description. With route validation (`accounting.validateRoutes`) enabled, Midaz stamps the matching rubric onto each operation, based on the operation's action and direction. #### Operations A transaction produces ledger movements. An **Operation** is a single leg of a transaction, one debit or one credit on a specific account. Midaz validates that the original transaction’s source, destination, and send totals agree. Its returned operation set is not always a debit/credit pair: pending creation and cancellation process only source-side legs. Each operation carries a `transactionId`, an `amount`, and an `assetCode`. When route validation (`accounting.validateRoutes`) is enabled on the ledger and the operation route defines accounting entries, the operation also carries a `routeCode` and a `routeDescription` from the resolved rubric. > [!NOTE] > > With `accounting.validateRoutes` enabled, when an operation route defines an accounting entry, Midaz resolves a rubric for the operation's action and direction. It writes the rubric `code` to the operation's `routeCode` and links the operation with a `transactionId`. Together, these fields give a complete audit trail: transaction → operation → rubric. Your teams trace which accounting rule applied to each movement, without extra lookups. At a glance, the flow is: ![Diagram showing the Accounting primitives workflow](https://mintcdn.com/lerian-49cb71fc/SFzzdxyH5SN7w_fC/images/en/d2/accounting-primitives.svg?fit=max\&auto=format\&n=SFzzdxyH5SN7w_fC\&q=85\&s=ae5fe0b8b7b390d8c8be5c76f53fe479) Accounting primitives workflow > [!TIP] > > If you are new to Midaz accounting, start with the **[Accounting Walkthrough](/en/products/midaz/accounting-walkthrough)**. It gives a step-by-step path from the chart of accounts to a working Pix payment example. # Accounting walkthrough Source: https://docs.lerian.studio/en/products/midaz/accounting-walkthrough An end-to-end, hands-on guide to designing and implementing accounting in Midaz, from chart of accounts to a working Pix payment example. This guide shows you how to implement accounting in Midaz from start to finish. It assumes you are a developer. You want only enough accounting context to model a real product. By the end, you understand how the primitives fit together. You can also wire up a complete Pix payment with correct double-entry postings. For the conceptual overview and links to each reference page, see **[Accounting](/en/products/midaz/accounting-in-midaz)**. ## 1. Double-entry accounting fundamentals *** Midaz supports double-entry bookkeeping through its transaction routes. Configure a route with source and destination Operation Routes, or a Bidirectional Operation Route that covers both sides. With **Validate Routes** enabled, Midaz validates each transaction against the configured route rules. Route validation is disabled by default. Enable it only after you configure the routes your Ledger needs. Lifecycle actions do not all use both sides: cancellation is source-only and releases held funds on the source Account. > [!NOTE] > > Think about *where value comes from* (the debit side / source) and *where it goes* (the credit side / destination). Every Midaz operation lands on one side of that equation. ## 2. Chart of Accounts in Midaz *** In traditional accounting, the Chart of Accounts (CoA) defines account categories (Assets, Liabilities, Equity, Income, Expenses), their hierarchy, and how to classify movements. > [!NOTE] > > Midaz does not have a dedicated Chart of Accounts API. The CoA is the result of how you combine assets, accounts, segments, portfolios, and account types. The `code` field on Accounting Entries (e.g. `1.1.1.001`) is where traditional account numbering appears in practice. Each `code` annotates a posting with its classification. Midaz lets you mirror or adapt a CoA digitally using a small set of primitives: * **Assets** define *what* moves: currencies (BRL, USD), points/miles, crypto tokens, or internal units of value. * **Accounts** are balance containers. Each has an asset code and type. It can also belong to a portfolio and segment. An **alias** (e.g. `@external/BRL`) identifies each account and keeps routing intuitive. * **Segments** categorize and isolate accounts (customer vs. internal funds, business units, multi-tenant separation). * **Portfolios** group accounts that share a purpose or belong to the same entity. To map a CoA in Midaz, you decide which balances you need and classify them with Account Types. You then organize them with segments and portfolios on a ledger, and assign `code` values on your Accounting Entries to match your numbering scheme. ### A recommended process **1. Map your financial model** List the balances you need: customer balances, internal accounts, reserve/settlement accounts, fee and revenue accounts. This is your CoA blueprint. **2. Define account types** Create an Account Type per conceptual category, e.g. `CASH`, `SETTLEMENT`, `FEE_REVENUE`, `FEE_EXPENSE`, `TREASURY`. **3. Create segments and portfolios** Segments separate business domains (`CUSTOMER_FUNDS`). Portfolios manage ownership and grouping (`customer_12345_wallet`). **4. Create accounts** For each logical balance, create a ledger account (customer BRL account, treasury account, provider fee expense account, merchant settlement account). ## 3. Setting up Account Types *** Account Types classify accounts by nature and purpose. With `validateAccountType` enabled, a new non-external Account's `type` must match a registered `keyValue`. An Operation Route can separately use `ruleType: account_type` to validate an account during route processing. Account Types do not themselves define permitted operations, internal or external status, or reconciliation rules. A typical setup for a payments product: * **CASH** → liquid customer funds * **SETTLEMENT** → funds awaiting clearing * **FEE_REVENUE** → fees collected * **FEE_EXPENSE** → provider fees * **TREASURY** → internal operations To enable Account Type validation, understand the `type` field, and manage Account Types via the API, see **[Account Types](/en/products/midaz/account-types)**. ### Understanding balance buckets Before you wire up two-phase flows, understand that each balance tracks funds in distinct fields: * **`available`**: funds you can spend or send right now. Debits and credits to a balance move this number. * **`onHold`**: funds that a pending `hold` reserves and does not yet commit. They still belong to the account until you commit or cancel the hold. * **`overdraftUsed`**: overdraft consumed by the balance, when overdraft is enabled. The three fields carry decimal strings with exact precision (for example, `"12.50"`). There is no separate `scale` field to interpret. See [Transaction amount](/en/products/midaz/amount) for the decimal value model. The two-phase actions change `available` and `onHold` on the source balance. These rows show a balance with `direction: credit`. On a `direction: debit` balance, a hold increases `available` and a cancel decreases it. `onHold` moves the same way on both. | Action | `available` | `onHold` | | - | - | - | | **Direct** | Debited (source) / credited (destination) | unchanged | | **Hold** | ↓ decreased on source | ↑ increased on source | | **Commit** | credited on destination | ↓ released from source | | **Cancel** | ↑ returned to source | ↓ released back to `available` | | **Revert** | restored on both sides via a counter-transaction | unchanged | For the full balance model (multiple balances per account, permission flags, overdraft, and history), see **[Balances](/en/products/midaz/balances)**. ## 4. Defining Accounting Entries (Rubricas) *** **Accounting Entries** (Rubricas) map a transaction action and route direction to an accounting `code` and `description`. You register rubrics once instead of computing accounting classifications by hand for each movement. When `accounting.validateRoutes` is enabled on the ledger and a matching rubric is configured, Midaz annotates each operation with the resulting `routeCode` and `routeDescription`. Operation Route rules and transaction legs determine the participating accounts. You configure rubrics **per action** on each Operation Route, inside the `accountingEntries` block. For `direct` and `commit` actions, source routes require the **debit** rubric and destination routes require the **credit** rubric. Dedicated `block` and `unblock` rubrics are optional. When you do not configure them, Midaz resolves the `direct` rubric for those actions. Source-side `hold` and `cancel` actions require **both** rubrics, `overdraft` requires **both** on every supported route type, and bidirectional routes always require **both**. ### The five transaction-lifecycle actions | Action | Code | What it does | | - | - | - | | **Direct** | `direct` | Immediate, single-step posting with no intermediate stages (e.g. a fee or adjustment). | | **Hold** | `hold` | Reserves funds by creating a pending movement (`available` → `onHold` on the source). | | **Commit** | `commit` | Confirms a previously held amount, releasing `onHold` to the destination. | | **Cancel** | `cancel` | Cancels a hold, returning `onHold` value to `available` on the source. | | **Revert** | `revert` | Reverses an `APPROVED` transaction via a counter-transaction when its Operation Routes are bidirectional. | Each action can point to different debit/credit rubrics on the same Operation Route. Every stage of an operation then receives the right accounting annotation. You register these mappings through the Operation Route endpoints. See [Create an Operation Route](/en/reference/products/midaz/v2/create-operation-route). ```json theme={null} { "accountingEntries": { "direct": { "debit": { "code": "1.1.1.001", "description": "Customer cash-out" }, "credit": { "code": "2.1.1.001", "description": "External settlement" } } } } ``` For the full model, see **[Accounting Entries (Rubricas)](/en/products/midaz/accounting-entries)**. ## 5. Transaction routing *** Routing is a two-layer system that resolves at runtime: * **Operation Routes** define the rules for each leg of a transaction: its side (source, destination, or both) and an optional account rule. They carry the **Accounting Entries (rubricas)** above. * **Transaction Routes** define the business event that triggers accounting (`PIX_CASH_OUT`, `WALLET_TRANSFER`, `BANK_SLIP_SETTLEMENT`, …) and combine Operation Routes into a balanced financial event. When you submit a transaction, you name its Transaction Route. With route validation enabled, Midaz checks each leg against its Operation Route and resolves the rubric for the current action. For route structure, fields, the operation-type validation matrix, and API behavior, see **[Transaction Routing](/en/products/midaz/transaction-routing-entities)**. ## 6. End-to-end example: a Pix payment *** This example is a simple Pix cash-out. A customer sends BRL out of their wallet to an external account. **1. Account setup** Create the customer account on your ledger. Midaz creates `@external/BRL` automatically together with the `BRL` Asset. Do not create it yourself. * `customer_12345_brl`: Account Type `CASH`, asset `BRL` * `@external/BRL`: the automatically created external settlement account for funds leaving the ledger **2. Enable route validation and register rubrics** Enable `accounting.validateRoutes` on the ledger. Then, on the Operation Route for the customer leg (source), register the `direct` debit rubric. On the external leg (destination), register the `direct` credit rubric: ```json theme={null} { "accountingEntries": { "direct": { "debit": { "code": "1.1.1.001", "description": "Pix cash-out — customer" }, "credit": { "code": "2.1.1.001", "description": "Pix cash-out — external settlement" } } } } ``` This block is a combined illustration of both rubrics. Register only the `debit` field on the Source route and only the `credit` field on the Destination route. **3. Transaction** Create the `PIX_CASH_OUT` Transaction Route that links both Operation Routes. Then submit a transaction that moves, say, `100.00 BRL` from `customer_12345_brl` to `@external/BRL`. Set `routeId` to the ID of the Transaction Route and `operationRouteId` on each leg to the ID of that leg's Operation Route. **4. Resulting operations** Midaz records two balanced operations: * **Debit** `customer_12345_brl` `100.00 BRL`, `routeCode: 1.1.1.001` * **Credit** `@external/BRL` `100.00 BRL`, `routeCode: 2.1.1.001` Both share the same `transactionId`. This gives you a full trail from transaction → operation → rubric. For a two-phase flow (hold → commit/cancel), register the `hold`, `commit`, and `cancel` rubrics on the source route and the `commit` rubric on the destination route. Submit the corresponding actions. Each stage resolves its own rubric. ## 7. Validation modes *** Midaz controls route validation with the `accounting.validateRoutes` setting on each ledger. The default is `false`. In this graceful mode, Midaz skips route validation. It leaves the `routeCode` and `routeDescription` fields empty on every operation and raises no error. Graceful mode is convenient while you onboard routes. In production, set `accounting.validateRoutes` to `true` in the [Ledger Settings](/en/products/midaz/ledgers#ledger-settings). Strict mode then validates the routes on every transaction: ```json theme={null} { "accounting": { "validateRoutes": true } } ``` In strict mode, Midaz returns `0157` when no Operation Route of the Transaction Route has an entry for the requested action. It returns `0117` when a leg names no Operation Route, or one that the Transaction Route does not provide for that action. When a route resolves, Midaz stamps `routeCode` and `routeDescription` from its rubric. > [!TIP] > > Use **strict mode** (`validateRoutes: true`) in production ledgers where every transaction type needs an accounting classification. Keep the graceful default only while you onboard routes. ## Next steps *** * Review the **[Accounting](/en/products/midaz/accounting-in-midaz)** overview and reference pages for full field-level detail. * Once your ledger produces structured postings, see **[Lerian Reporter](/en/products/reporter/what-is-reporter)** to transform ledger events into reconciliation files, financial statements, and COSIF-aligned regulatory outputs. # Accounts Source: https://docs.lerian.studio/en/products/midaz/accounts Use Accounts as the core financial unit of a Midaz Ledger, tied to a single Asset and recording every debit, credit, and balance for a customer or product. An Account is the core financial unit of a Midaz Ledger. Each Account links to one Asset and records every debit, credit, and balance for that Asset. In banking terms, an Account is a financial product, such as a checking account, a savings account, or a loan account. > [!TIP] > > Midaz does not limit how many accounts you create. Create as many as your structure needs. ## Account structure *** * **Account > Ledger**: You create an Account within a Ledger. The Ledger tracks and consolidates all balances and operations. * **Account > Portfolio**: You can group Accounts into [**Portfolios**](/en/products/midaz/portfolios) to represent customer clusters, product lines, or business units. * **Account > Asset**: Each Account links to a **single Asset**. The Asset defines the type of value the Account holds, such as BRL, USD, BTC, or loyalty points. * **Account > Account Type**: When you enable Account Type validation, each non-external Account must use a registered Account Type. You register Account Types for your business classification. ## Key characteristics *** * Each Account links to exactly one Asset. * Each Account has a unique identifier within a Ledger. ## Multiple accounts per customer *** A single customer often holds more than one balance. The same customer might hold balances that behave differently: * **Different nature**: a main balance, a benefit balance, or a promotional balance. * **Different operational rules**: a court-ordered account that accepts inflows but restricts outflows. * **Separate statement and reconciliation**: a product sub-account or pocket that you track on its own. When the balance, ledger, statement, or rule differs, each one becomes its own Account. You classify it by an [Account Type](/en/products/midaz/account-types), group it under the customer with a [Portfolio](/en/products/midaz/portfolios), and tie it to identity through [CRM](/en/products/midaz/crm/crm-overview). One account with labels works until the balances diverge. Separate accounts keep each balance accurate from the start. > [!TIP] > > For the full reference architecture (one customer, many accounts, with step-by-step examples), see [Midaz for multi-account customers](/en/products/midaz/midaz-for-multi-account-customers). ## External Account *** External Accounts in Midaz represent accounts outside your organization's structure. They track money that enters or leaves your ledger, usually to and from users, partners, or financial providers. External accounts have these characteristics: * **Hold the counterparty balance** for money that enters or leaves your ledger. * **The Ledger creates a canonical external Account automatically** when you create an Asset. * **The canonical external Account follows a clear naming pattern**: `@external/`, such as `@external/BRL`. These accounts record inflows and outflows at the ledger boundary. > [!CAUTION] > > **Do not try to delete or change an external account.** Midaz blocks these operations to keep the Ledger accurate and traceable. ### External account codes The canonical external Account created with an Asset follows the naming pattern `@external/`. The asset code in that alias is the lookup key. You can retrieve this canonical Account and its balances with convenience endpoints that accept only the asset code: * `GET .../accounts/external/{code}`: Retrieve the external account for an asset code (for example, `BRL` resolves to `@external/BRL`). * `GET .../accounts/external/{code}/balances`: Retrieve the balances for that external account. These endpoints are shortcuts for the canonical external Account. They prepend `@external/` to the code you provide, then perform an alias-based lookup. The result is identical to a query by that full alias. ### Entity ID (external system reference) The `entityId` field exists on any account, not only external accounts. It links the account to a record in an external system, such as a core banking platform, a CRM, or a partner system. * **Not the same as alias**: You use the alias in transactions, and it must be unique within a ledger. The `entityId` is only a reference for your integration, and Midaz does not use it to move value. * **Optional**: Set it when you create the account or when you update it. The maximum length is 256 characters. * **Use case**: When your system already has an account identifier, such as `EXT-ACC-12345`, store it in `entityId`. You can then map between Midaz and your source of truth. ```json JSON theme={null} { "name": "User Checking Account", "assetCode": "BRL", "alias": "@user_checking_123", "entityId": "EXT-ACC-12345", "type": "checking" } ``` ## Parent Account ID *** The **Parent Account ID** links two accounts within Midaz. You define the relationship based on your business logic. The parent Account must be in the same Ledger and use the same Asset. You can use it for a traditional parent-child structure or for another relationship that your business needs. ## Blocked accounts *** Set `blocked` to `true` when you create or update an Account. Midaz then refuses every transaction that moves the Account, as source or destination. The block does not stop the cancellation of a pending transaction. To allow one debit of an exact amount out of a blocked Account, [create a single-use block exception](/en/reference/products/midaz/v2/create-account-block-exceptions). Then send its ID in the `accountBlockExceptionId` field of the transaction. ## Account aliases *** An alias replaces a complex account ID with a readable label. This makes accounts easier to identify. * **For example**: Instead of the ID `3172933b-50d2-4b17-96aa-9b378d6a6eac`, you can use `@username_1`. ### Use the Account Alias in Transactions When you create a transaction, identify each Account by its **account alias**. Do not use the account ID. An alias is **optional** when you create a non-external Account. If you skip it, Midaz uses the account ID as the alias. A user-created external Account requires an alias. The alias you set can have up to 100 characters from `a-z`, `A-Z`, `0-9`, `@`, `:`, `_`, and `-`. ## Managing Accounts *** You can manage your Accounts through the API or the Lerian Console. ### Via API * [Create an Account](/en/reference/products/midaz/v2/create-account): Open a new Account linked to an Asset. * [Open a holder-owned Account](/en/reference/products/midaz/v2/create-holder-account): Open an Account that a Holder owns, and optionally its Instrument, in one call. * [List Accounts](/en/reference/products/midaz/v2/list-accounts): View all Accounts in a Ledger. * [Retrieve an Account](/en/reference/products/midaz/v2/get-account-by-id): Get details of a specific Account. * [Retrieve an Account by Alias](/en/reference/products/midaz/v2/get-account-by-alias): Get details of a specific Account by its alias. * [Retrieve an External Account](/en/reference/products/midaz/v2/get-account-external-by-code): Get details of a specific External Account by its asset code. * [Update an Account](/en/reference/products/midaz/v2/update-account): Edit the metadata or settings of an existing Account. * [Delete an Account](/en/reference/products/midaz/v2/delete-account): Delete a specific Account. Midaz also archives its Instruments, ends its [account plan](/en/products/midaz/fees/account-plans) assignment, and removes its alias from the fee and billing packages of the ledger. * [Close an Account](/en/reference/products/midaz/v2/close-account): Close an Account whose balances are all exactly zero. Midaz keeps its history and refuses any later movement. > [!WARNING] > > **Transfer any remaining balance to another account before you delete an account.** Midaz does not delete an account or sub-account that still holds a balance. Midaz also refuses to delete or close an account with a balance that owes [fee debt](/en/products/midaz/fees/fee-debt) (`0527`) or that other balances owe fee debt to (`0528`). ### Via Lerian Console You can view, create, edit, and delete Accounts on the Accounts page. This page is in the Midaz module of the Lerian Console. [**Learn more in the Managing Accounts guide.**](/en/products/midaz/console/managing-accounts) # Accounts Source: https://docs.lerian.studio/en/products/midaz/accounts-overview Learn how to create, group, and classify Midaz Accounts using Portfolios and Segments to match your customers, product lines, and business unit structure. Accounts are the core financial units in Midaz. This section covers how to create, organize, and classify Accounts. You group them to match your business structure, from individual balances to customer-level groupings. ## Content *** Here, you'll find: * [**Accounts**](/en/products/midaz/accounts): The core financial unit in a Ledger. Each Account uses one Asset and records its debits, credits, and balances. Midaz also supports External Accounts to track value that moves in or out of your organization. * [**Portfolios**](/en/products/midaz/portfolios): Groups of Accounts that belong to one entity, such as a customer or business unit. A Portfolio works like a wallet that holds that entity's Accounts across different Assets. * [**Segments**](/en/products/midaz/segments): A classification for Accounts that share characteristics. You group Accounts into Segments to organize them by tier or type, such as premium card tiers or student accounts. # Transaction amount Source: https://docs.lerian.studio/en/products/midaz/amount Use the transaction field that belongs to the endpoint version. Midaz does not use one global amount field across every transaction API. Amount fields apply to transaction-creation bodies, not every transaction endpoint. The v1 creation payloads use decimal `value`. The API accepts a JSON number or string. A string avoids client-side IEEE-754 rounding. The v2 `direct`, `hold`, `block`, `unblock`, and `batch` creation endpoints require string `amount`. Commit, cancel, and revert identify an existing transaction by its ID and take no amount. > [!WARNING] > > Do not combine field conventions from different transaction versions. Use the API reference for the specific operation you call. # Architecture Source: https://docs.lerian.studio/en/products/midaz/architecture Explore Midaz's modular architecture, centered on the Ledger service and its supporting infrastructure. > [!NOTE] > > Midaz runs the modular Ledger service and a separate Tracer service. Deploy and scale each service and its supporting infrastructure for your environment. For a business-oriented overview, see [About Midaz](/en/products/midaz/about-midaz). Midaz can run in public or private cloud environments. Select and operate the infrastructure that fits your deployment requirements. Midaz uses a modular architecture. Ledger is organized around domain boundaries, with supporting infrastructure for storage, caching, messaging, and streaming. Tracer runs as a separate service. ## Repository and deployment boundary Midaz ships two runtimes in one repository and release: the Ledger modular monolith (with CRM and Fees) and Tracer. Tracer is not embedded in the Ledger process: deploy and scale it separately. Ledger HTTP v2 can opt into the one-way reservation seam to Tracer. Ledger HTTP v1 never calls it. Tracer's public HTTP surface remains `/v1`, so the seam does not create a public Tracer v2 API. Tracer never calls Ledger. ## Modular architecture *** The diagram below (*Figure 1*) shows how the pieces fit together. ![Layered diagram of Midaz: the cluster layer that you manage, the front-end layer with Lerian Console, the back-end layer with the Ledger (with CRM and Fees) and Tracer as a separate runtime, the data layer with PostgreSQL, MongoDB, Valkey, and RabbitMQ, and the Helm chart layer.](https://mintcdn.com/lerian-49cb71fc/Wqp8NG2BwBLM-rZd/images/en/d2/midaz-macro-architecture.svg?fit=max\&auto=format\&n=Wqp8NG2BwBLM-rZd\&q=85\&s=f9045b806d418acce709ff232958ea58) Figure 1. Midaz macro-architecture ### 1. Cluster layer (managed by you) You manage this layer. It provides the Kubernetes foundation that runs Midaz. Enable these services: * **Service**: Networking abstraction to expose and route services. * **AutoScaler**: Automatically adjusts the number of pods. * **HPA (Horizontal Pod Autoscaler)**: Scales applications based on metrics. * **Secrets**: Secure management of sensitive data. * **ConfigMap**: Externalized configuration management. This layer governs and coordinates all components within the cluster. ### 2. Front-end layer The front-end layer provides the user interface for system interaction (admin panel, dashboards, and more). > [!NOTE] > > Newer releases of Midaz no longer include a bundled console. [Lerian Console](/en/platform/console/about-lerian-console) now provides the visual interface. The Lerian Console includes Midaz as one product module. > > If you use an older version of Midaz, you may still have the standalone Midaz Console. Midaz v3.5.0 and later releases do not include it. Migrate to Lerian Console for the latest features and improvements. ### 3. Back-end layer The Ledger back-end is a modular monolith that holds the core responsibilities of the Midaz ledger. Midaz also runs Tracer as a separate service. Ledger brings together four core components: * **Onboarding domain**: manages organizations, ledgers, assets, portfolios, segments, and accounts. * **Transactions domain**: handles financial transactions, operations, and asset movements. * **CRM**: is embedded in the Ledger process. * **Fees**: is embedded in the Ledger process. This approach keeps clear domain boundaries. It also simplifies deployment and lowers operational complexity. ### 4. Data layer This layer holds the databases and infrastructure components that support application data and event flows: * **PostgreSQL**: separate `onboarding` and `transaction` databases, each with a primary connection and an optional replica connection. * **Valkey**: A Redis-compatible key-value store. The ledger validates and updates live balances in it, then syncs them to PostgreSQL. It also caches data. * **MongoDB**: Stores semi-structured data: entity metadata, CRM holders and instruments, and fee and billing packages. * **RabbitMQ**: Message broker for asynchronous transaction processing and event exchanges of the ledger. * **Redpanda**: Kafka-compatible broker for Ledger event streams. Ledger publishes configured events to it only when you set `STREAMING_ENABLED=true` and configure streaming brokers. Persistence is deployment-specific. Configure production storage and retention for each service. ### 5. Helm Chart layer Midaz uses Helm Charts to deploy and configure the infrastructure. The chart connects the code to Kubernetes. It deploys each component the same way across environments. > [!TIP] > > For more details, see the [Deploying using Helm](https://github.com/LerianStudio/helm/tree/main/charts/midaz) page. ## How the layers work together *** Each layer has a focused role. * Kubernetes coordinates how the layers communicate. * Helm keeps deployments and configurations in sync. You can add new components as needed without disruption to what already runs. # Assets Source: https://docs.lerian.studio/en/products/midaz/assets Define the currencies, cryptocurrencies, and tokenized instruments your Accounts hold, with multi-asset support across a single Ledger. Assets represent the financial instruments or currencies that Accounts hold. Each Account holds exactly one Asset. Assets can include: * Currencies (e.g., BRL, USD, EUR) * Cryptocurrencies (e.g., BTC, ETH) * Non-currency assets (e.g., gold, loyalty points, tokenized securities) Midaz keeps each Asset independent within the Ledger. Balances stay clearly defined. ### Multi-Asset Midaz supports traditional currencies, cryptocurrencies, commodities, and tokenized assets in one system. Use it for multi-currency wallets, cross-border payments, or digital asset portfolios. ## Asset structure *** * **Asset > Account**: Each Account holds a single Asset. * **Asset > Ledger > Account**: You define Assets at the Ledger level. You create Accounts from the available Assets. ## Key characteristics *** * You must define each Asset before you use it. * Each Asset has a unique identifier, such as a currency code. * Midaz stores asset rates, but the Ledger transaction flow does not use them to convert values. The source and destination assets of a transaction must match. > [!NOTE] > > When you create an Asset, Midaz automatically creates an [External Account](/en/products/midaz/accounts) if one does not exist. The External Account backs every transaction that enters or leaves the Ledger. > > The External Account uses the naming convention `@external/`, for example, `@external/BRL`. ## Managing Assets *** You can manage Assets through the API or the Lerian Console. ### Via API * [List Assets](/en/reference/products/midaz/v2/list-assets): View all Assets in a Ledger. * [Retrieve an Asset](/en/reference/products/midaz/v2/get-asset-by-id): Get details of a specific Asset. * [Create an Asset](/en/reference/products/midaz/v2/create-asset): Register a new Asset in the Ledger. * [Update an Asset](/en/reference/products/midaz/v2/update-asset): Edit the properties of an existing Asset. * [Delete an Asset](/en/reference/products/midaz/v2/delete-asset): Mark an Asset as deleted. > [!CAUTION] > > Deleting an Asset marks its External Account as deleted. It does not move or clear any balance. Settle the balances in that Asset before you delete it. ### Via Lerian Console You can view, create, edit, and delete Assets on the Assets page in the Midaz module of the Lerian Console. [**Learn more in the Managing Assets guide.**](/en/products/midaz/console/managing-assets) # Async transaction processing Source: https://docs.lerian.studio/en/products/midaz/async-transaction-processing Async transaction processing validates the call fast, then persists the write through RabbitMQ, for lower API latency and higher throughput. ## When synchronous writes become the bottleneck *** A client sends a transaction. Midaz must do two things: validate it and persist the result. In synchronous mode, both steps run in the same request. This model is simple and predictable, but it has a ceiling. At high volume, database writes become the bottleneck. Each transaction holds a connection, waits for locks, and competes for I/O. Async mode breaks that dependency. Midaz validates the transaction, returns the response at once, and persists the data in the background through RabbitMQ. The client gets faster responses. For broader scaling guidance, see [Scalability strategies](/en/products/midaz/scalability-strategies). ## How it works *** ### Synchronous mode (default) ![Sequence diagram showing the client sending a POST /transaction to the Midaz API, which validates it, writes the transaction and operations to PostgreSQL, and returns 201 Created to the client.](https://mintcdn.com/lerian-49cb71fc/eJbUTctk-eLsW0J5/images/en/d2/sync-transaction-flow.svg?fit=max\&auto=format\&n=eJbUTctk-eLsW0J5\&q=85\&s=80107b258808f015d108c00ffdd6a92f) Figure 1. Synchronous transaction flow. The full flow has these steps: 1. **The client sends** a `POST /transaction` to the Midaz API. 2. **The API validates the request.** It runs request-shape validation, balance checks, and limit enforcement here. 3. **The API writes to PostgreSQL.** It persists the transaction and its operations in the same request cycle. 4. **The API returns `201 Created`** to the client with the created transaction. The response carries the `CREATED` status, and Midaz stores the transaction as `APPROVED`. A `201` means Midaz applied the transaction to balances. **Characteristics:** * Response time includes database write latency. * Each transaction is an independent database operation. * Simpler to reason about. > [!NOTE] > > Even in synchronous mode, Midaz updates balances atomically in Redis during the request. Redis is authoritative for balances. The write above persists the transaction and its operations, not the Postgres balance rows. The always-on balance-sync worker reconciles those rows (see [Balance synchronization](#balance-synchronization)). ### Asynchronous mode Midaz validates the transaction the same way. Instead of a direct database write, Midaz publishes a message to RabbitMQ. A background consumer picks up the message and handles persistence separately. ![Sequence diagram showing the client sending a POST /transaction to the Midaz API, which validates it, publishes the payload to RabbitMQ, and immediately returns 201 Created to the client. In parallel, RabbitMQ delivers the message to a background consumer, which writes the transaction and operations to PostgreSQL; balances are handled by the dedicated balance-sync worker.](https://mintcdn.com/lerian-49cb71fc/gKGrvDlaceQM1W4Y/images/en/d2/async-transaction-flow.svg?fit=max\&auto=format\&n=gKGrvDlaceQM1W4Y\&q=85\&s=be9a180c76a5d019e32f25af357905a9) Figure 2. Asynchronous transaction flow. The client receives a response as soon as the message is published, and persistence happens in the background. The full flow has these steps: 1. **The client sends** a `POST /transaction` to the Midaz API. 2. **The API validates the request.** It runs request-shape validation, balance checks, and limit enforcement exactly as in synchronous mode. 3. **The API publishes the transaction payload to RabbitMQ** instead of a direct database write. 4. **The API returns `201 Created`** to the client as soon as the queue accepts the message. The client does not wait for database persistence. The response carries the `CREATED` status, and Midaz stores the transaction as `APPROVED`. A `201` means Midaz applied the transaction to balances. 5. **RabbitMQ delivers the message** to a background consumer, decoupled from the API request. 6. **The consumer writes to PostgreSQL.** It persists the transaction and its operations from the queued message. The balance-sync worker copies balances to PostgreSQL in both modes (see the **Balance synchronization** section). **Characteristics:** * Response time excludes database write latency. * List queries show a new transaction after the consumer writes it. * Background consumers write to the database at their own pace, with retries. Batch inserts use the Bulk Recorder, which is enabled by default. > [!TIP] > > The validation step is identical in both modes. Balance checks, request-shape validation, and limit enforcement all happen before the API responds, regardless of processing mode. The difference is only in *when* the data hits the database. ## Built-in resilience *** If the publish to RabbitMQ fails in async mode, Midaz writes the transaction to the database in the request. If that write also fails, the transaction stays applied to balances. Midaz keeps the transaction record and retries the write in the background. Synchronous mode uses the same recovery when its database write fails. This means: * During a queue outage, Midaz writes directly to the database. * A failed database write does not reject a transaction that Midaz already applied to balances. * Midaz logs the queue failure and the deferred write so your operations team can investigate them. > [!WARNING] > > During a queue outage, latency can increase because writes go straight to the database. Monitor your RabbitMQ health to keep async mode active. ## Enabling async mode *** Set one environment variable in the ledger application: ```bash Environment variable theme={null} RABBITMQ_TRANSACTION_ASYNC=true ``` With `false` (the default), all transactions use synchronous processing and persist directly to PostgreSQL. The ledger still connects to RabbitMQ and runs its consumer in this mode. With `true`, the ledger publishes transaction payloads to the configured RabbitMQ exchange. A background consumer then handles persistence. ## RabbitMQ configuration *** Async mode uses the following RabbitMQ settings (all in the ledger `.env`): | Variable | Description | Example value | | :- | :- | :- | | `RABBITMQ_TRANSACTION_ASYNC` | Enable async processing. | `false` | | `RABBITMQ_HOST` | RabbitMQ server hostname. | `midaz-rabbitmq` | | `RABBITMQ_PORT_HOST` | AMQP protocol port. | `3003` | | `RABBITMQ_PORT_AMQP` | Management API port. | `3004` | | `RABBITMQ_DEFAULT_USER` | Producer credentials (user). | `transaction` | | `RABBITMQ_DEFAULT_PASS` | Producer credentials (password). | — | | `RABBITMQ_CONSUMER_USER` | Consumer credentials (user). | `consumer` | | `RABBITMQ_CONSUMER_PASS` | Consumer credentials (password). | — | | `RABBITMQ_NUMBERS_OF_WORKERS` | Number of consumer worker goroutines. | `5` | | `RABBITMQ_NUMBERS_OF_PREFETCH` | Messages prefetched per worker. | `10` | | `RABBITMQ_TRANSACTION_BALANCE_OPERATION_EXCHANGE` | Exchange name for transaction messages. | `transaction.transaction_balance_operation.exchange` | | `RABBITMQ_TRANSACTION_BALANCE_OPERATION_KEY` | Routing key. | `transaction.transaction_balance_operation.key` | | `RABBITMQ_TRANSACTION_BALANCE_OPERATION_QUEUE` | Queue name. | `transaction.transaction_balance_operation.queue` | > [!TIP] > > The consumer uses separate credentials (`RABBITMQ_CONSUMER_USER` / `RABBITMQ_CONSUMER_PASS`) from the producer. The consumer republishes the messages that it retries, so it also needs write access to the transaction exchange. ## Balance synchronization *** A dedicated balance-sync worker copies balances from Redis to PostgreSQL. This worker runs in both synchronous and asynchronous modes. | Variable | Description | Default | | :- | :- | :- | | `BALANCE_SYNC_BATCH_SIZE` | Number of balance updates to batch before flushing. | `50` | | `BALANCE_SYNC_FLUSH_TIMEOUT_MS` | Maximum wait time (ms) before flushing an incomplete batch. | `500` | | `BALANCE_SYNC_POLL_INTERVAL_MS` | How often (ms) the worker checks for pending updates. | `50` | The balance-sync worker runs automatically in both modes. You need no extra setup beyond an available Redis instance. ## RabbitMQ circuit breaker *** A built-in circuit breaker protects the RabbitMQ publishes of audit messages and overdraft events. It monitors the health of the RabbitMQ connection and fails fast when the broker goes down. This prevents request pileups and cascading failures. ### Circuit breaker configuration | Variable | Description | Default | | :- | :- | :- | | `RABBITMQ_CIRCUIT_BREAKER_CONSECUTIVE_FAILURES` | Consecutive failures before the circuit opens. | `15` | | `RABBITMQ_CIRCUIT_BREAKER_FAILURE_RATIO` | Failure percentage (0–100) that triggers open state. | `50` | | `RABBITMQ_CIRCUIT_BREAKER_MIN_REQUESTS` | Minimum requests before evaluating the failure ratio. | `10` | | `RABBITMQ_CIRCUIT_BREAKER_INTERVAL` | Time window (seconds) for counting failures. Counters reset after each interval. | `120` | | `RABBITMQ_CIRCUIT_BREAKER_TIMEOUT` | How long (seconds) the circuit stays open before transitioning to half-open. | `30` | | `RABBITMQ_CIRCUIT_BREAKER_MAX_REQUESTS` | Requests allowed through in half-open state to probe recovery. | `3` | | `RABBITMQ_CIRCUIT_BREAKER_HEALTH_CHECK_INTERVAL` | How often (seconds) the background health checker pings RabbitMQ. | `30` | | `RABBITMQ_CIRCUIT_BREAKER_HEALTH_CHECK_TIMEOUT` | Timeout (seconds) for each health check ping. | `10` | ## How async mode connects to Bulk Recorder *** Async mode and the [Bulk Recorder](/en/products/midaz/bulk-recorder) work together: 1. **Async mode** decouples the API response from persistence. Transactions go to RabbitMQ instead of directly to PostgreSQL. 2. **Bulk Recorder** optimizes how the consumer writes those messages to the database. It batches multiple messages into single bulk inserts. | Configuration | Processing behavior | | :- | :- | | Async `false` | Direct database write per transaction (synchronous) | | Async `true`, Bulk Recorder `false` | Queue-based, one message processed at a time | | Async `true`, Bulk Recorder `true` (default) | Queue-based, batched bulk inserts | ## When to use async mode *** **Use async mode when:** * You need lower API response times for transaction creation. * Your workload involves high transaction volumes (hundreds+ per second). * You run batch operations like mass payouts or settlements. * You want to decouple your API tier from database performance. **Keep synchronous mode when:** * You need direct, request-bound transaction persistence. * Transaction volume is low to moderate. * You work in a development or testing environment where simplicity matters more than throughput. > [!TIP] > > You can switch between modes at any time. Change `RABBITMQ_TRANSACTION_ASYNC` and restart the ledger application. You need no data migration, because the transaction format is the same in both paths. # Balance Overdraft Source: https://docs.lerian.studio/en/products/midaz/balance-overdraft Enable controlled Balance Overdraft in Midaz with automatic split operations, credit repayment priority, and limits for BNPL or settlement accounts. Balance Overdraft lets you debit a balance beyond its available funds. The primary balance never goes negative. Midaz tracks the deficit as **OverdraftUsed** and splits the operation between the primary balance and an internal companion balance. When credits arrive, Midaz repays the overdraft first. Any remainder flows to Available. This mechanism supports credit lines, BNPL, settlement accounts, earned wage access, and any product that needs controlled negative positions. ## Balance direction *** Balances carry a `direction` field that defines how debits and credits affect the balance: | Direction | Behavior | Typical use | | - | - | - | | `credit` | Debit decreases, credit increases | Checking accounts, wallets, reserves | | `debit` | Debit increases, credit decreases | Loans, overdraft tracking, payables | At creation, Midaz uses an explicit `direction` when provided, then the Account Type's `defaultDirection`. If neither is set, the balance uses `credit`. Midaz creates External Account balances with `debit`. An external balance created before Midaz 3.7.0 keeps the `credit` direction. > [!NOTE] > > You set direction at creation time. It is immutable. The overdraft companion balance (described below) always uses `direction=debit`. ## Balance settings *** The `settings` object on a balance controls overdraft behavior: | Field | Type | Description | | - | - | - | | `allowOverdraft` | boolean | Enables overdraft on this balance | | `overdraftLimitEnabled` | boolean | Gates whether a limit is enforced | | `overdraftLimit` | string (decimal) | Maximum overdraft amount. Required when `overdraftLimitEnabled` is `true`. Must be greater than `0`. | > [!NOTE] > > The `settings` object also carries `balanceScope`. It identifies a transactional balance (the default) or a system-managed internal balance, such as the overdraft companion. You can set `balanceScope: "transactional"` when you create or update a public balance. You cannot set `balanceScope: "internal"` through the public API. ## Configuration modes *** ### No overdraft (default) `allowOverdraft` is `false` by default. A debit cannot take a balance with `direction: credit` below zero. ```json JSON theme={null} { "key": "checking", "settings": { "allowOverdraft": false } } ``` ### Unlimited overdraft The derived position can go negative without a cap. The persisted `Available` balance remains at `0`, while Midaz tracks the deficit as `OverdraftUsed`. Use this for settlement or pool accounts, where negative positions are normal and you reconcile them externally. ```json JSON theme={null} { "key": "settlement", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": false } } ``` ### Limited overdraft The derived position can go negative up to a defined limit. The persisted `Available` balance remains at `0`, while Midaz tracks the deficit as `OverdraftUsed`. This is the most common mode for consumer credit products. ```json JSON theme={null} { "key": "checking", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "5000.00" } } ``` > [!WARNING] > > When `overdraftLimitEnabled` is `true`, you must set `overdraftLimit` to a positive decimal string. If you omit it or set it to `"0"`, Midaz returns error `0172`. ## How overdraft works *** ### Operation split When a debit transaction exceeds the available funds, Midaz automatically splits the operation: 1. The debit consumes all remaining Available and floors it at **0**. 2. Midaz accrues the excess as **OverdraftUsed** on the primary balance. **Example:** Balance has Available = 300. A debit of 500 arrives. | Step | Available | OverdraftUsed | Description | | - | - | - | - | | Before | 300 | 0 | Normal state | | After | 0 | 200 | 300 consumed from Available, 200 accrued as overdraft | The transaction succeeds as a single atomic operation. The caller does not need to handle the split. Midaz does it automatically. > [!NOTE] > > If you configure a limit, Midaz checks the resulting OverdraftUsed against `overdraftLimit` before it processes the transaction. If the result exceeds the limit, Midaz rejects the transaction with error `0167`. ### Automatic repayment (refund split) When a credit arrives and `OverdraftUsed > 0`, Midaz prioritizes repayment: 1. Midaz applies the credit to **OverdraftUsed** first and reduces the debt. 2. Any remaining amount after OverdraftUsed reaches 0 flows to **Available**. **Example:** OverdraftUsed = 200, Available = 0. A credit of 350 arrives. | Step | Available | OverdraftUsed | Description | | - | - | - | - | | Before | 0 | 200 | Overdraft active | | After | 150 | 0 | 200 repaid, 150 goes to Available | > [!TIP] > > Repayment is automatic. You cannot bypass it. Midaz reduces overdraft positions as early as possible, which keeps the balance healthy. ### Pending transactions and overdraft A `PENDING` transaction creates a hold. It does not draw overdraft. If a hold would exceed Available, Midaz rejects the transaction with error `0018 - Insufficient Funds Error`. The rejected hold does not change Available, OnHold, or `OverdraftUsed`. When you cancel a pending transaction, Midaz releases its hold. A pending transaction created by an earlier Midaz version can already carry overdraft. Midaz still unwinds that legacy state correctly during cancellation. ### Block transactions and overdraft A block transaction never draws overdraft. If a block exceeds Available, Midaz rejects it with error `0018 - Insufficient Funds Error`, even when the balance allows overdraft. An unblock repays overdraft first, like any other credit. ## Position *** Every balance response includes a computed `position` block. It gives a real-time view of the balance state: | Field | Description | | - | - | | `available` | Derived `position.available`. It can be negative when the persisted balance has `Available = 0` and `OverdraftUsed > 0`. | | `onHold` | Mirrors `Balance.OnHold` (funds reserved by pending operations). | | `overdraftLimitAvailable` | Remaining non-negative overdraft headroom. It is `"0"` when a configured limit is fully used and is omitted when overdraft is unlimited. | > [!WARNING] > > Do not cache the `position` block for accounting purposes. Midaz never persists it. It computes the block at query time from the current balance state. ## Companion balance *** When you create or update a balance with `allowOverdraft` set to `true` for the first time, Midaz auto-provisions a **companion balance** under the same account. The companion balance records the liability side of the double-entry. Midaz creates it once per account and reuses it across every overdraft draw and repayment. | Property | Value | Why | | - | - | - | | `key` | `"overdraft"` | Reserved system key | | `direction` | `debit` | The companion tracks a liability: debits grow it, credits shrink it | | `scope` | `internal` | Blocks direct user operations | | `allowSending` | `true` | Required for DEBIT operations on the companion (overdraft draws) | | `allowReceiving` | `true` | Required for CREDIT operations on the companion (overdraft repayments) | This balance is fully system-managed: * You cannot create, modify, or delete it through the public API. * Midaz reserves the key `"overdraft"`. A request that creates a balance with this key returns error `0170`. * It mirrors the liability as a proper double-entry record, so the ledger stays balanced. > [!NOTE] > > The `scope: "internal"` value blocks direct user operations, regardless of the permission flags above. Midaz rejects any direct operation on this balance with error `0168`. The companion moves only through system-driven overdraft enrichment. ## Overdraft state on operations *** Every operation exposes the overdraft state on the `balance` and `balanceAfter` blocks. The `overdraftUsed` field records the overdraft consumed before and after the operation. This gives a complete audit trail without a separate balance query. System-managed companion operations on the `"overdraft"` balance use `type: "OVERDRAFT"` (uppercase). The `direction` field carries the lifecycle: `"debit"` for a draw, `"credit"` for a repayment. ```json Primary debit drawing overdraft theme={null} { "type": "DEBIT", "direction": "debit", "amount": { "value": "300" }, "accountAlias": "@user123", "balanceKey": "checking", "balance": { "available": "300", "onHold": "0", "version": 1, "overdraftUsed": "0" }, "balanceAfter": { "available": "0", "onHold": "0", "version": 2, "overdraftUsed": "200" } } ``` ```json Companion overdraft draw theme={null} { "type": "OVERDRAFT", "direction": "debit", "amount": { "value": "200" }, "balanceKey": "overdraft", "balance": { "available": "0", "onHold": "0", "version": 1, "overdraftUsed": "0" }, "balanceAfter": { "available": "200", "onHold": "0", "version": 2, "overdraftUsed": "200" } } ``` Both the primary and the companion operation share the same `overdraftUsed` before/after pair. They mirror the primary balance's overdraft transition, so the lifecycle is visible from either row. The internal `snapshot` JSONB column on the `operations` table stores the same values for indexing and historical reconstruction. This column is not part of the public JSON wire. The values surface on `balance.overdraftUsed` and `balanceAfter.overdraftUsed` instead. Midaz can add future system-generated context to the snapshot without breaking the public contract. > [!TIP] > > Companion operations inherit the primary operation's `routeId`. For each overdraft-capable route, configure both the `debit` and `credit` rubrics of the `overdraft` entry. Midaz requires both. Midaz resolves `routeCode` and `routeDescription` from the rubric that matches the companion's direction. ## Overdraft events *** Midaz publishes each overdraft event on two channels: * To the streaming topic `lerian.streaming.ledger`, when `STREAMING_ENABLED` is `true`. * To RabbitMQ, to the exchange set in `RABBITMQ_OVERDRAFT_EVENTS_EXCHANGE`. `RABBITMQ_OVERDRAFT_EVENTS_ENABLED` controls both channels. Unset means `true`. With `false`, Midaz publishes the overdraft events on neither channel. ```bash Environment theme={null} # Midaz publishes overdraft events unless this flag is false. RABBITMQ_OVERDRAFT_EVENTS_ENABLED=true # Optional: route the RabbitMQ messages to a dedicated exchange. # When unset, the broker's default exchange is used. RABBITMQ_OVERDRAFT_EVENTS_EXCHANGE=transaction.overdraft_events.exchange # Midaz emits the streaming events only when streaming is enabled. STREAMING_ENABLED=true ``` The Ledger emits the events at the same time as the transaction events and does not order them. Correlate them with the transaction by `transactionId`. ### Event types | Streaming event | RabbitMQ routing key | Description | | - | - | - | | `balance.overdraft_drawn` | `midaz.balance.overdraft.drawn` | Overdraft was consumed (OverdraftUsed increased) | | `balance.overdraft_repaid` | `midaz.balance.overdraft.repaid` | Overdraft was partially repaid (OverdraftUsed decreased but remains > 0) | | `balance.overdraft_cleared` | `midaz.balance.overdraft.cleared` | Overdraft was fully repaid (OverdraftUsed reached 0) | ### Example event payload The streaming payload is the `data` field of the event. See [Midaz events](/en/reference/events/midaz) for the full schema. The RabbitMQ message carries the event fields in `payload`. ```json Streaming expandable theme={null} { "balanceId": "0198575f-a8f9-7924-a6d7-8122f2c77d01", "accountId": "0198575f-a8f9-7924-a6d7-8122f2c77ddd", "organizationId": "0198575d-f9fd-702b-bb15-fa4c980b32c7", "ledgerId": "0198575d-fa0b-7ac7-8b7d-9d3ab7dccafc", "assetCode": "BRL", "transactionId": "019b2c3d-4e5f-6789-0123-456789abcdef", "operationId": "019b2c3d-4e5f-6789-0123-456789abce02", "action": "drawn", "amount": "200", "overdraftBalance": "200", "occurredAt": "2026-04-28T14:30:00.000000Z" } ``` ```json RabbitMQ expandable theme={null} { "source": "midaz", "eventType": "balance", "action": "overdraft.drawn", "timestamp": "2026-04-28T14:30:00.000000Z", "version": "v4.4.1", "organizationId": "0198575d-f9fd-702b-bb15-fa4c980b32c7", "ledgerId": "0198575d-fa0b-7ac7-8b7d-9d3ab7dccafc", "payload": { "accountId": "0198575f-a8f9-7924-a6d7-8122f2c77ddd", "transactionId": "019b2c3d-4e5f-6789-0123-456789abcdef", "amount": "200", "overdraftBalance": "200", "timestamp": "2026-04-28T14:30:00.000000Z" } } ``` > [!TIP] > > Use overdraft events to trigger downstream workflows: interest accrual, customer notifications, risk alerts, or automatic collection processes. ## Use cases *** ### Checking account overdraft (cheque especial) Classic consumer credit. The checking account's derived position can go negative up to a pre-approved limit. The persisted `Available` balance remains at `0` and the outstanding amount is tracked as `OverdraftUsed`. ```json JSON theme={null} { "key": "checking", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "2000.00" } } ``` ### Buy Now, Pay Later (BNPL) A BNPL provider issues a purchase credit against the customer's balance. This creates an immediate overdraft position that the customer repays in installments. ```json JSON theme={null} { "key": "bnpl", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "10000.00" } } ``` ### Earned Wage Access / Salary advance Employees draw against future earnings. Payroll credits clear the overdraft position when they arrive. ```json JSON theme={null} { "key": "salary-advance", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "3000.00" } } ``` ### Marketplace receivables advance Sellers receive an advance on future receivables. Midaz repays the overdraft automatically as sales settlements arrive. ```json JSON theme={null} { "key": "receivables", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "50000.00" } } ``` ### Settlement / Pool accounts (unlimited mode) Settlement and pool accounts routinely go negative during intraday processing. Unlimited overdraft avoids artificial rejections while you reconcile the position by end-of-day. ```json JSON theme={null} { "key": "settlement-pool", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": false } } ``` ### Revolving credit lines (B2B) Businesses draw and repay from a revolving credit facility. The overdraft limit represents the total credit line. ```json JSON theme={null} { "key": "credit-line", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "500000.00" } } ``` ### Insurance pre-financing Insurers pre-finance claims before premium collection cycles close. The overdraft covers the gap between payout and collection. ```json JSON theme={null} { "key": "claims-prefin", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "100000.00" } } ``` ### Loyalty programs (advanced points) Customers redeem points before they earn them. The overdraft tracks the point deficit and clears as customers accrue new points. ```json JSON theme={null} { "key": "loyalty-points", "settings": { "allowOverdraft": true, "overdraftLimitEnabled": true, "overdraftLimit": "10000" } } ``` ## Protection rules *** Overdraft introduces several immutability and access constraints to maintain ledger integrity: * **Direction is immutable.** Once you set a balance's `direction` at creation, you cannot change it. * **Internal balances block writes.** You cannot create, delete, or update the `"overdraft"` companion balance through the public API. A PATCH returns error `0175`. * **Reserved keys.** Midaz reserves the key `"overdraft"` for the system-managed companion balance. * **Disabling overdraft preserves outstanding debt.** You can set `allowOverdraft: false` while `OverdraftUsed > 0` to block future draws, while incoming credits still repay the existing debt. * **Limit cannot drop below usage.** If `OverdraftUsed = 200`, Midaz rejects `overdraftLimit: "100"` with error `0173`, so repay below the new ceiling first or set a higher limit. For error codes 0167–0175, see the [Midaz error list](/en/reference/products/midaz/error-list). ## Next steps *** * Learn about [Balances](/en/products/midaz/balances), the foundation that overdraft builds on. * Understand [Operations](/en/products/midaz/operations) to trace how overdraft splits appear in the ledger. * Set up the [Event Publisher](/en/products/midaz/event-publisher) to consume overdraft lifecycle events. * Explore [Transactions](/en/products/midaz/transactions) for the full picture of double-entry accounting in Midaz. # Balances Source: https://docs.lerian.studio/en/products/midaz/balances Track multiple Balances per Account to segment funds into investment reserves, credit limits, and operational funds without extra Accounts. A **Balance** represents the value that a specific account holds in Midaz. It reflects the result of all operations (debits and credits) over time. Each balance belongs to one asset, such as BRL, USD, or BTC. ## Multiple balances *** A single account can hold several balances. A unique key identifies each one. This lets institutions segment funds without creating multiple accounts for the same customer. > [!CAUTION] > > External accounts cannot have multiple balances. **Each external account holds exactly one balance.** Typical use cases include: * Investment reserves * Credit limits * Collateral (blocked) funds * Day-to-day operational funds This approach increases flexibility. It keeps the double-entry model (debit and credit) intact for accounting consistency, traceability, and transparency. > [!WARNING] > > If a transaction does not provide a `balanceKey`, Midaz uses the account's default balance. ### Balance key A `key` field identifies each balance uniquely within the account. * **Maximum length**: 100 characters, with no whitespace. * **Default key**: `"default"`. Midaz creates the default balance automatically when the account is created. * **Uniqueness**: Each key must be unique per account. A request to create a balance with a key that already exists on the account returns an error. * **In transactions**: If a transaction does not specify a `balanceKey`, Midaz uses the balance with key `"default"`. > [!NOTE] > > You set the `key` at creation time and cannot change it later. Choose descriptive keys like `"credit"`, `"collateral"`, or `"savings"` to make your balance model self-documenting. ### Permission flags Each balance has two independent permission flags that control whether it can participate in transactions: | Flag | Type | Description | | - | - | - | | `allowSending` | boolean | Whether funds can be sent **from** this balance | | `allowReceiving` | boolean | Whether funds can be received **into** this balance | These flags are per-balance. They apply to one balance, not to the whole account. Both default to `true` when you do not set them. **Common use cases:** * **Receive-only balance**: Set `allowSending` to `false` to block outbound transfers and still accept inflows. * **Send-only balance**: Set `allowReceiving` to `false` to prevent new funds from entering this balance. You can set both flags when you create a balance. You can also update them independently through the [Update a Balance](/en/reference/products/midaz/v2/update-balance) endpoint. If an update request omits a flag, its current value stays unchanged. > [!WARNING] > > Midaz reads permission flags during transaction validation. A flag change applies to transactions validated after the update succeeds. Changes never alter operations already processed. ## Usage examples *** * **User Wallet (BRL)**: A digital wallet that shows an available balance of R\$500. * *Use case*: Show the balance in a mobile banking app and validate funds before a payment. * **Settlement Account (USD)**: A liquidity provider account with a USD balance of \$120,000. * *Use case*: Make sure daily treasury operations keep enough buffer for FX settlements. * **Blocked Balance (BRL)**: An account balance reserved as collateral. * *Use case*: Prevent the use of funds until a loan closes or the borrower meets the conditions. > [!NOTE] > > A blocked (collateral) balance restricts funds at the balance level. Midaz holds the value in a separate balance and combines it with permission flags to keep the funds unavailable. This differs from a [Block transaction](/en/products/midaz/transactions#blocking-and-unblocking-funds), which records a ledger movement with `BLOCK`-typed operations. A Block transaction flags funds for reasons like a compliance hold. Use a collateral balance for a standing operational restriction. Use a Block transaction when you need an auditable ledger entry. ## Balance structure *** * **Balance > Account**: Each Balance belongs to an Account, which holds and moves value. * **Balance > Asset**: Each Balance uses a specific Asset, such as BRL or BTC. * **Balance > Ledger**: Balances exist within a Ledger, which enables multi-book environments. * **Balance > Key**: Each Balance has a unique key within the account (e.g., `default`, `credit`, `collateral`). *Figure 2* shows an example of the structure. ![Balance structure relationships](https://mintcdn.com/lerian-49cb71fc/SFzzdxyH5SN7w_fC/images/en/d2/balance-structure-relationships.svg?fit=max\&auto=format\&n=SFzzdxyH5SN7w_fC\&q=85\&s=7b2fdced4a1a0db1ed925b210b01b16d) Figure 2. Balance structure relationships diagram. A balance includes metadata about the state of funds, such as pending operations and effective availability. ## Key characteristics *** * **Real-time tracking**: Midaz updates balances with every confirmed operation. * **Multiple balances per account**: Accounts can hold several balances, each with its own rules. * **Single source of truth**: Balances reflect the net sum of all operations on the account. * **Query by context**: You can list balances within an organization and ledger, retrieve them by account ID or alias, and retrieve an External Account’s balance by asset code. The balance-list endpoints do not filter by a generic asset code or `balanceKey`. * **Supports external accounts**: You can retrieve balances for internal or external accounts, such as liquidity pools or partners. ## Using balances in transactions *** The following transaction endpoints accept a `balanceKey` field to specify which balance to use: * [Create a Transaction using JSON](/en/reference/products/midaz/v1/create-transaction-json) * [Create an Inflow Transaction](/en/reference/products/midaz/v1/create-transaction-inflow) * [Create an Outflow Transaction](/en/reference/products/midaz/v1/create-transaction-outflow) * [Create a Transaction Annotation](/en/reference/products/midaz/v1/create-transaction-annotation) * The v2 `direct`, `hold`, `block`, `unblock`, and `batch` endpoints, with `balanceKey` on each leg If a request does not provide a `balanceKey`, Midaz uses the account's default balance. ### New fields in responses * `balanceKey` - Appears in transactions and operations to show which balance the transaction used. * `key` - Appears in balances to identify each balance uniquely. > [!CAUTION] > > Always use the `balanceKey` consistently across requests and responses. This avoids mismatches when accounts hold multiple balances. ## Balance cache key (Valkey) *** Balances in the cache (Valkey) include the `balanceKey`. ```json theme={null} balance:{transactions}:::# ``` The key carries the `balance:{transactions}:` prefix, and the `balance_key` is appended to the account alias with a `#` separator. > [!WARNING] > > Update direct Valkey readers to construct `balance:{transactions}:::#`, including `#default` for the default balance. ## Overdraft *** Balances support **overdraft**, the ability to debit a balance beyond its available funds. When you enable overdraft, Midaz tracks the deficit as `overdraftUsed`. Midaz also handles the operation split and repayment automatically. Two fields support this feature: * **`direction`**: A new balance of a non-external account takes the `defaultDirection` of its account type when that type sets one. Otherwise, direction is `credit` for non-external accounts and `debit` for External Accounts. Additional balances may set direction at creation. It cannot change afterward. * **`settings`**: Controls overdraft behavior with `allowOverdraft`, `overdraftLimitEnabled`, and `overdraftLimit`. > [!NOTE] > > Midaz reserves the key `"overdraft"` for the system-managed companion balance that records the liability side. A request to create a balance with this key returns an error. `settings.balanceScope` also distinguishes balances by scope. **Transactional** balances (the default) are user-managed and take part in regular transactions. The system operates **internal** balances exclusively, such as the overdraft companion. User transactions cannot target, modify, or delete them through the public API. For full details on configuration modes, operation splits, automatic repayment, events, and use cases, see [Balance Overdraft](/en/products/midaz/balance-overdraft). ## Balance history *** Midaz provides **point-in-time queries** for balances. You can retrieve a balance state at a past timestamp on or after the balance’s creation. If no operation exists before that timestamp, Midaz returns the initial zero state. It returns `404` when the requested timestamp precedes balance creation. This supports auditing, reconciliation, and historical reporting. ### How it works When you query balance history, Midaz returns historical identity and amount fields. It omits `allowSending`, `allowReceiving`, `deletedAt`, and `metadata`. The current implementation also does not reconstruct historical `direction` or `settings`, and returns `overdraftUsed` as zero. Do not treat it as a full regular-balance response minus permission flags. > [!TIP] > > **Why does history exclude permission flags?** > > `allowSending` and `allowReceiving` are mutable operational settings. You can toggle them at any time without a ledger entry. Balance amounts (`available`, `onHold`) change only from recorded transactions. Permission flags represent the *current* operational state of a balance, not a fact about its past. > > Historical audits and reconciliation care about amounts at a point in time. Whether sending or receiving worked at a given moment does not matter for audit or reconciliation. Mutable permission state in immutable snapshots would add ambiguity without value. ### Use cases * **Regulatory auditing**: Prove the exact balance of an account at a specific compliance checkpoint. * **Reconciliation**: Compare balance snapshots across systems at matching timestamps. * **Dispute resolution**: Retrieve the precise account state at the time of a contested transaction. * **End-of-day reporting**: Capture balance positions at market close for treasury operations. > [!WARNING] > > The `date` parameter is required. It must follow the format `yyyy-mm-dd hh:mm:ss` (e.g., `2026-01-15 10:30:00`). Midaz returns `404` when the requested timestamp precedes balance creation. ### Querying balance history You can query history for a single balance or for all balances of an account: * [Retrieve Balance History](/en/reference/products/midaz/v2/get-balance-at-timestamp) - Get the state of a specific balance at a given point in time. * [Retrieve Balance History by Account](/en/reference/products/midaz/v2/get-account-balances-at-timestamp) - Get the state of all balances for an account at a given point in time. ## Managing Balances *** You can retrieve your balances through the API. The Midaz ledger engine computes balance amounts from transactions. You cannot set `available` or `onHold` directly. You manage the balance records (key, permission flags, and settings) through the endpoints below. * [Create a Balance](/en/reference/products/midaz/v2/create-additional-balance) - Create a new balance for an account by defining a unique key. * [List Balances](/en/reference/products/midaz/v2/get-all-balances) - Retrieve all balances by organization and ledger. * [Retrieve Balance Totals](/en/reference/products/midaz/v2/get-balance-totals-by-key-and-asset) - Get the totals of one balance key and asset in a ledger: the sum of `available`, the sum of `onHold`, and the number of balances. Balances of external accounts do not count. * [Retrieve a Balance](/en/reference/products/midaz/v2/get-balance-by-id) - Get the balance of a specific account by its unique ID. * [Retrieve Balances by Account](/en/reference/products/midaz/v2/get-all-balances-by-account-id) - Get the balance for a specific account. * [Retrieve a Balance by Account Alias](/en/reference/products/midaz/v2/get-balances-by-alias) - Get the balance with a human-readable account alias (e.g., @user123). * [Retrieve a Balance of an External Account](/en/reference/products/midaz/v2/get-balances-external-by-code) - Retrieve the balance of an external account (e.g., `@external/BRL`). * [Update a Balance](/en/reference/products/midaz/v2/update-balance) - Update the permission flags and settings of a balance. * [Delete a Balance](/en/reference/products/midaz/v2/delete-balance) - Delete a balance entry from the system. Midaz refuses to delete a balance that owes [fee debt](/en/products/midaz/fees/fee-debt) (`0527`) or that other balances owe fee debt to (`0528`). A balance read can return `503` with `0542` when Midaz cannot read the current state of the balance. Retry the request. > [!TIP] > > To trace how a balance formed, use the Operations API to inspect the ledger history that affected that account. ## Next steps *** * Use the [Operations API](/en/products/midaz/operations) to trace transactions that involve multiple balances. * Combine multiple balances with [Accounting Routes](/en/products/midaz/transaction-routing-entities) to create flexible and scalable financial flows. # Production ready Source: https://docs.lerian.studio/en/products/midaz/best-practices Hub for Midaz production best practices covering common mistakes, scalability strategies, banking entity hierarchy, and hardening for high-volume workloads. For direct transactions, use Accounting Routes and enable route validation after you configure the route rules your Ledger needs. Lifecycle actions can follow a different shape. Cancellation releases held funds on the source side only. These best practices help you keep financial operations transparent, auditable, and compliant. ## Content *** This section contains the following pages: * [**Common mistakes to avoid**](/en/products/midaz/common-mistakes-to-avoid): The most common mistakes with Midaz and how to avoid them. * [**Scalability strategies**](/en/products/midaz/scalability-strategies): How to scale your Midaz deployment for high transaction volumes and multi-currency, multi-entity operations. * [**Structuring bank operations with Midaz**](/en/products/midaz/structuring-bank-operation): A strategic approach to entity hierarchy and account structure in a banking environment. * [**Midaz production best practices**](/en/products/midaz/midaz-production-best-practices): Recommendations to set up your Midaz production environment from the start. You minimize downtime, protect your data, and handle high-volume workloads. # Build on Midaz Source: https://docs.lerian.studio/en/products/midaz/build-midaz-sdk Build integrations on Midaz with the official Go SDK: typed clients, sensible defaults, and shared patterns for API calls and errors. Midaz SDKs are the public integration layer for applications that call Midaz APIs. Use an SDK to build an application, automation, backend service, or integration on Midaz. Each SDK works with Midaz resources: organizations, ledgers, accounts, portfolios, balances, transactions, assets, and metadata. The SDKs give you typed, idiomatic interfaces for the Midaz API. You focus on product behavior, not raw HTTP requests, payloads, pagination, or response parsing. ## Available SDKs *** We offer one official SDK: > [card] [Go SDK](/en/products/midaz/midaz-sdk-go) > > Use the official Go SDK to build Midaz integrations in Go. ## Why use Midaz SDKs? *** * Developer-friendly: clean interfaces, strong typing, and sensible defaults. * API-focused: SDKs connect to the public Midaz APIs. Your application keeps control of its data and business logic. ## SDKs and internal libraries *** SDKs are the public path for external applications to integrate with Midaz. Lerian also maintains internal shared libraries for its own services, plugins, and platform components. Lerian engineering teams use these libraries to standardize how services behave. These libraries are not public integration contracts. Do not treat them as supported APIs for external applications. To integrate with Midaz, start with the Go SDK or the Midaz API. # Build an account statement Source: https://docs.lerian.studio/en/products/midaz/building-account-statements Turn Midaz account operations into a clear customer statement by filtering by date, direction, and route with the List Operations by Account endpoint. You build an account statement from Midaz account operations. Each operation is a ledger movement that links to an account, such as a credit, debit, hold, release, or overdraft event. To build a statement, retrieve the account operations for the period. Keep the operations that affect the statement view. Then transform each operation into a row that users understand. ![Account balance flow](https://mintcdn.com/lerian-49cb71fc/SFzzdxyH5SN7w_fC/images/en/d2/account-balance-flow.svg?fit=max\&auto=format\&n=SFzzdxyH5SN7w_fC\&q=85\&s=1d9f29821d6e2e687c6d9bd8e4c5a89f) Account balance flow ## 1. Retrieve account operations Use the [List Operations by Account](/en/reference/products/midaz/v2/get-all-operations-by-account) endpoint to list operations for a specific account: ```json theme={null} GET /v1/organizations/{organization_id}/ledgers/{ledger_id}/accounts/{account_id}/operations ``` ## 2. Apply query filters Use query parameters to define the statement period, control pagination, and filter the operations that the endpoint returns. ### Required for statement queries | Parameter | Description | | - | - | | `start_date` | Start date of the statement period | | `end_date` | End date of the statement period | | `limit` | Number of items per page | | `sort_order=desc` | Returns the most recent operations first | You need these fields for this statement use case. They define the statement window and make the result predictable for users. ### Required for pagination | Parameter | Description | | - | - | | `cursor` | Cursor returned from the previous response | ### Optional filters | Parameter | Description | | - | - | | `direction=credit` | Returns only incoming operations | | `direction=debit` | Returns only outgoing operations | | `type` | Filters by operation type | | `route_id` | Filters by the operation route ID (UUID) | | `route_code` | Filters by the operation route code | | `sort_by=created_at` | Orders by creation date, then by ID. The default is `id`. Use the same value on every page of a cursor. | The endpoint can return the following operation types: | Type | What it means | | - | - | | `CREDIT` | Value entering the account | | `DEBIT` | Value leaving the account | | `ON_HOLD` | Amount temporarily locked | | `RELEASE` | Previously locked amount released | | `OVERDRAFT` | Movement related to overdraft usage | | `BLOCK` | An operation of a block transaction | | `UNBLOCK` | An operation of an unblock transaction | | `FEE_SETTLEMENT` | Settlement of a fee debt | | `FEE_REFUND` | Refund of a settled fee debt on a revert | Use `type` to classify the accounting movement. Use `direction` to decide whether the statement shows the amount as positive or negative. Example request: ```json theme={null} GET /v1/organizations/org_123/ledgers/ledger_001/accounts/account_456/operations?start_date=2026-05-01&end_date=2026-05-31&limit=50&sort_order=desc ``` ## 3. Transform operations into statement entries Each object in the `items` array can become one statement row. ### Required for statement rendering | Statement field | Operation field | | - | - | | Date | `createdAt` | | Description | `description` | | Movement type | `type` | | Direction | `direction` | | Amount | `amount.value` | | Currency or asset | `assetCode` | | Balance after operation | `balanceAfter.available` | | Receipt or transaction reference | `transactionId` | You need these fields to render a useful statement row. The API does not require all of them. A statement without them loses meaning, traceability, or balance context. ### Recommended for user-friendly statements | Statement context | Operation field | | - | - | | Counterparty | `metadata.counterparty` | | Document | `metadata.document` | | Pix key | `metadata.pixKey` | | End-to-end ID | `metadata.endToEndId` | | Channel | `metadata.channel` | | Category | `metadata.category` | Midaz returns the ledger movement. The integrating system should add business context in the `metadata` of each relevant `source.from[]` and `distribute.to[]` entry when it creates the transaction. Metadata does not propagate from source entries to destination entries. Example transformation: ```json theme={null} { "date": "2026-05-18T14:23:11Z", "description": "Pix transfer received", "type": "CREDIT", "direction": "credit", "amount": "150.00", "asset": "BRL", "balanceAfter": "1240.55", "transactionId": "txn_987654", "metadata": { "counterparty": "John Doe", "pixKey": "john@example.com", "category": "Transfer" } } ``` ## 4. Apply statement display rules ### Use `direction` to determine the sign | Direction | Display behavior | | - | - | | `credit` | Display as a positive amount | | `debit` | Display as a negative amount | > [!WARNING] > > Do not use `type` to determine whether the value is positive or negative. The `type` field classifies the accounting movement, while `direction` defines whether the value enters or leaves the account. ### Handle hold and release operations separately Do not display operations with the following types as regular settled movements: * `ON_HOLD` * `RELEASE` Instead: * `ON_HOLD` should appear as a balance hold or temporary lock * `RELEASE` should appear as a balance release or unlock ### Define a settled-operation policy Do not use `balanceAffected` as a settled-operation predicate. A normal `ON_HOLD` operation can set `balanceAffected` to `true` without changing the available balance. Define your statement policy explicitly from operation type and status, and show `ON_HOLD` and `RELEASE` according to the hold/release rules above. ## 5. Handle pagination The endpoint splits responses into pages according to the `limit` value. To retrieve all operations: 1. Read the `next_cursor` field from the response 2. Send it as the `cursor` parameter in the next request 3. Repeat until the response no longer returns `next_cursor` Example flow: ```text theme={null} Request 1 -> returns items + next_cursor Request 2 -> cursor=next_cursor -> returns more items + next_cursor Repeat until next_cursor is no longer returned ``` ## Example statement output After you apply filters, transform operations, and apply display rules, the final statement can look like this: | Date | Description | Amount | Balance after | | - | - | - | - | | 2026-05-18 | Pix received from John Doe | +150.00 BRL | 1,240.55 BRL | | 2026-05-18 | Card purchase | -45.90 BRL | 1,194.65 BRL | The API does not return a ready-made statement page. It returns ledger events that the integrating system turns into a statement experience. ## Add business context The operations endpoint returns accounting events. A user-facing statement needs more context than the ledger movement alone. Send business metadata in each operation's metadata when you create the transaction. Midaz stores those fields with that operation. The statement can use them later to show who, what, and why behind the movement. * `counterparty` * `document` * `pixKey` * `endToEndId` * `channel` * `category` Example metadata: ```json theme={null} "send": { "source": { "from": [{ "accountAlias": "customer_123", "metadata": { "counterparty": "John Doe", "document": "12345678900", "pixKey": "john@example.com", "endToEndId": "E1234567890123456789012345678901", "channel": "PIX", "category": "Transfer" } }] } } ``` A v2 leg carries no metadata: send the context in the transaction `metadata`, and read it for each row through the `transactionId` of the operation. This lets you display entries such as: * "Pix received from John Doe" * "Card purchase at Coffee Shop" * "Transfer to Savings Account" instead of generic accounting descriptions. If the integrating system does not send these fields, the statement still works. It can then only display the accounting data that the operation returns. > [!TIP] > > Midaz keeps the ledger consistent and auditable. The integrating system adds business context to each operation's metadata. # Bulk Recorder Source: https://docs.lerian.studio/en/products/midaz/bulk-recorder Use the Bulk Recorder to batch RabbitMQ messages into bulk PostgreSQL inserts, cutting database round trips and raising throughput on high-volume workloads. ## Batch writes for high-volume workloads *** Every transaction in Midaz creates balance operations that Midaz must persist. In the default synchronous mode, Midaz writes them directly to the database in the request cycle. This is fine for moderate volumes. At scale (thousands of transactions per second), it becomes the bottleneck. The Bulk Recorder accumulates messages and writes them in batches. It makes fewer round trips to PostgreSQL, lowers lock contention, and raises throughput. High-volume workloads gain the most: mass payouts, batch settlements, and real-time payment processing. For broader strategies to scale Midaz, see [Scalability strategies](/en/products/midaz/scalability-strategies). ## How it works *** The Bulk Recorder sits between the RabbitMQ consumer and the database layer. Instead of inserting each message at once, it collects messages in a buffer and flushes them under two conditions: 1. **Batch size reached**: the buffer fills to the configured size. 2. **Timeout elapsed**: the configured flush timeout expires, even if the buffer is not full. Whichever condition happens first triggers the flush. This gives large batches under load and low latency during quiet periods. ![Sequence diagram showing RabbitMQ delivering messages to the BulkCollector, which buffers them until the batch size or timeout is reached, then sends a chunked bulk INSERT to PostgreSQL and acknowledges each message back to RabbitMQ.](https://mintcdn.com/lerian-49cb71fc/Cb_meREQqa6luqbJ/images/en/d2/bulk-recorder-flow.svg?fit=max\&auto=format\&n=Cb_meREQqa6luqbJ\&q=85\&s=cf6291e64238dddc753da5b89a5caeba) Figure 1. End-to-end flow of the Bulk Recorder between RabbitMQ and PostgreSQL. Here is the full flow, step by step: 1. **RabbitMQ delivers messages** to the BulkCollector one at a time: Message 1, Message 2, up to Message N. 2. **The BulkCollector holds them in memory** instead of one write per message. It collects until the batch fills or the flush timeout expires. 3. **The BulkCollector sends a chunked bulk INSERT to PostgreSQL.** Midaz splits large batches into chunks that respect PostgreSQL's parameter limits. Each chunk uses `ON CONFLICT (id) DO NOTHING`, so retries and duplicate deliveries stay safe. 4. **PostgreSQL confirms the write** and stores the data. 5. **The BulkCollector acknowledges each message** back to RabbitMQ after the write. It acknowledges them one at a time, not in a single bulk ack. This stops a shared channel from acking messages that other workers still process. ## Enabling Bulk Recorder *** Bulk mode works only in a single-tenant deployment and requires async mode. The explicit Bulk Recorder setting is optional because it defaults to enabled: ```bash Environment variables theme={null} RABBITMQ_TRANSACTION_ASYNC=true BULK_RECORDER_ENABLED=true ``` ## Configuration *** | Variable | Description | Default | | :- | :- | :- | | `BULK_RECORDER_ENABLED` | Enable or disable bulk mode. | `true` | | `BULK_RECORDER_SIZE` | Number of messages to accumulate before flushing. `0` = auto-calculated. | `0` (auto) | | `BULK_RECORDER_FLUSH_TIMEOUT_MS` | Maximum time (ms) to wait before flushing an incomplete batch. | `100` | | `BULK_RECORDER_MAX_ROWS_PER_INSERT` | Maximum operation rows per `INSERT`. Values above 1,000 have no effect. | `1000` | ### Auto-calculated batch size When `BULK_RECORDER_SIZE` is set to `0` (the default), Midaz derives the batch size: ``` batch size = RABBITMQ_NUMBERS_OF_WORKERS × RABBITMQ_NUMBERS_OF_PREFETCH ``` > [!WARNING] > > If you set `BULK_RECORDER_SIZE` by hand, keep it aligned with your prefetch settings. A size much larger than `workers × prefetch` rarely fills the collector. The collector then flushes mostly on the timeout. ## Tuning for your workload *** The two main levers are **batch size** and **flush timeout**. The right balance depends on your priority: latency or throughput. ### Low latency (real-time processing) Keep batches small and timeouts short. Midaz persists messages quickly, even when batches are not full. ```bash Low-latency configuration theme={null} RABBITMQ_NUMBERS_OF_WORKERS=5 RABBITMQ_NUMBERS_OF_PREFETCH=10 BULK_RECORDER_SIZE=0 # auto: 5 × 10 = 50 BULK_RECORDER_FLUSH_TIMEOUT_MS=50 ``` ### High throughput (batch operations) Larger batches and longer timeouts maximize database efficiency. Use this for mass payouts, end-of-day settlements, or migration workloads. ```bash High-throughput configuration theme={null} RABBITMQ_NUMBERS_OF_WORKERS=10 RABBITMQ_NUMBERS_OF_PREFETCH=20 BULK_RECORDER_SIZE=0 # auto: 10 × 20 = 200 BULK_RECORDER_FLUSH_TIMEOUT_MS=300 ``` > [!TIP] > > Start with the defaults and adjust from what you observe. To confirm your settings, watch for the `Bulk mode configured for consumer` log at startup. ## Safety guarantees *** These mechanisms keep the Bulk Recorder safe: ### Idempotency Every bulk insert uses `ON CONFLICT (id) DO NOTHING`. If a message arrives twice (from a retry, a redelivery, or a network fault), PostgreSQL drops the duplicate. ### Deadlock prevention Before each bulk insert, Midaz sorts the record IDs. All concurrent writers then acquire locks in the same order. This removes the most common source of PostgreSQL deadlocks under high concurrency. ### Internal chunking Midaz splits large batches into chunks that fit within PostgreSQL's 65,535-parameter limit per query. Each `INSERT` carries at most 1,000 rows. ## When to use *** **Use Bulk Recorder when:** * You process high volumes of transactions (hundreds or thousands per second). * Your workload includes batch operations like mass payouts, settlements, or data migrations. * You already use async transaction processing (`RABBITMQ_TRANSACTION_ASYNC=true`). * You want to reduce database load and connection pressure. **Keep it disabled when:** * Your volume is low enough that individual inserts are not a bottleneck. * You debug transaction processing and want a simpler, message-by-message flow. # Closing a customer account Source: https://docs.lerian.studio/en/products/midaz/closing-a-customer-account Follow the eight-step flow to freeze, settle, close, and archive a customer account across Ledger and CRM in line with BACEN account closure and audit requirements. To close a customer account in Midaz, you work across two areas: the **Ledger** (accounts and balances) and **CRM** (holders and alias accounts). BACEN rules make account closure a regulated event, so the order matters. Stop new credits first, then settle pending activity and return any remaining funds. Then close each account. The close operation refuses an account that still holds funds. Archive the CRM records last. This guide covers the full closure flow, from the [Holder](/en/products/midaz/crm/holders) to its [Alias Accounts](/en/products/midaz/crm/alias-accounts). You can run the flow two ways. **[Via API](#via-api)** gives you the endpoint, an example payload, and the compliance rationale for each step. **[Via Console](#via-console)** gives you the same steps as point-and-click actions in the Midaz Console. > [!WARNING] > > Follow the steps in order. Do not archive CRM records before you close the accounts. ## Overview *** The closure flow has eight steps, grouped into three phases: | Phase | Steps | Goal | | :- | :- | :- | | **1. Freeze** | 1–2 | Mark the Holder inactive and stop new credits at the balance level. | | **2. Settle and zero** | 3–4 | Clear pending activity and return remaining funds to the customer. | | **3. Close and archive** | 5–8 | Close the Ledger Accounts and archive CRM records under retention policy. | > [!NOTE] > > Throughout this guide, `{organization_id}` and `{ledger_id}` identify the Midaz Organization and Ledger that own the accounts. This guide abbreviates the paths to `/v1/.../accounts/{accountId}` and `/v2/.../accounts/{accountId}` for readability. ## Prerequisites *** Before you start, make sure you have: * The `holderId` of the customer to offboard. * The `accountId` values linked to that Holder across every Ledger in the Organization. Retrieve them with `GET /v2/organizations/{organization_id}/holders/{holder_id}/accounts`. The response is paginated, so retrieve every page. Add the optional `ledger_id` query parameter only when you need to narrow the list to one Ledger. * The `instrument_id` of each Alias Account, mapped to its corresponding `accountId`. List the Holder's instruments with `GET /v2/organizations/{organization_id}/instruments?holder_id={holder_id}` (also paginated) and use each instrument's `accountId` field to map it to the Ledger Account. Step 5 targets these `instrument_id` values. * Confirmation from your compliance team that you can end the customer relationship (no legal holds, open disputes, or pending regulatory requirements). * Appropriate API credentials with permission to modify holders, instruments, balances, and accounts. Step 5 updates instruments, so the credentials must carry `patch` access on the `instruments` resource. Steps 6 and 7 need `post` and `delete` access on the `accounts` resource. > [!WARNING] > > Closing an account cannot be undone. Before you proceed, confirm there are no active products or open obligations. ## Via API *** Run the full closure flow programmatically. Each step lists the endpoint, an example payload, and the compliance rationale. ### Step 1: Freeze the Holder Mark the Holder as inactive to record the closure across your systems. Update the Holder and set the `status` field on its person profile to an inactive value. ```http theme={null} PATCH /v2/organizations/{organization_id}/holders/{holder_id} ``` ```json theme={null} { "naturalPerson": { "status": "INACTIVE" } } ``` > [!NOTE] > > Marking the Holder inactive is a record change, not a deletion. The Holder record stays fully readable for audit. This status does not block new credits on its own. Step 2 blocks inflows at the balance level. For a legal person, set `legalPerson.status` instead. ### Step 2: Block credits on the accounts For each account linked to the Holder, prevent new funds from entering. First, list the [Balances](/en/products/midaz/balances) of the account. Then update each balance to disable receiving. If a balance has a non-zero `overdraftUsed`, repay it first: a balance that refuses inflows also refuses the repayment. **Retrieve the account balances:** ```http theme={null} GET /v1/.../accounts/{accountId}/balances ``` **For each returned balance except the system-managed `overdraft` balance, block incoming funds:** ```http theme={null} PATCH /v1/.../balances/{balanceId} ``` ```json theme={null} { "allowReceiving": false } ``` > [!WARNING] > > Repeat this step for every balance except `overdraft` on **every** account belonging to the Holder. A single balance left open can still receive credits and block closure later. > [!TIP] > > When you set `allowReceiving` to `false`, the balance blocks new inflows but still allows outflows. This is exactly what you need in Step 4 to return the remaining balance to the customer. For details on the permission flags, see [Balances](/en/products/midaz/balances). ### Step 3: Settle pending activity Before you can zero a balance, the account must have no in-flight movements. * **Check for transactions in processing.** Confirm the account has no pending or uncommitted transactions. Commit or cancel them as appropriate using [Commit a pending transaction](/en/reference/products/midaz/v2/commit-transaction) or [Cancel a pending transaction](/en/reference/products/midaz/v2/cancel-transaction). > [!WARNING] > > The close operation in Step 6 refuses an account whose funds a pending transaction still holds. ### Step 4: Zero the balance Return any remaining funds to the customer (the account holder) and confirm `available = 0`, `onHold = 0`, and `overdraftUsed = 0` on every balance. * If a balance owes [fee debt](/en/products/midaz/fees/fee-debt), settle it first with [Collect open fee debts](/en/reference/products/midaz/v2/collect-a-balance-s-open-fee-debts). The close operation refuses a balance that owes fee debt (`0527`). * Record a **return transaction** that moves the remaining `available` amount from each customer account to the holder's designated destination (for example, an external settlement account). Use [Create a transaction](/en/reference/products/midaz/v1/create-transaction-json). * **Confirm `available = 0`, `onHold = 0`, and `overdraftUsed = 0`** on every balance of every account in the Ledger before you proceed. You can check this with [Retrieve balances by account](/en/reference/products/midaz/v2/get-all-balances-by-account-id). > [!WARNING] > > The close operation refuses an account with any balance whose `available`, `onHold`, or `overdraftUsed` amount is not exactly zero. ### Step 5: Register the closing date on the alias Record the official closure date on the Holder's Alias Account so the CRM and any regulatory exports reflect when the relationship ended. Do this before you delete the account in Step 7. After the delete, Midaz answers an update of the Alias Account with not found. ```http theme={null} PATCH /v2/organizations/{organization_id}/holders/{holder_id}/instruments/{instrument_id} ``` ```json theme={null} { "bankingDetails": { "closingDate": "2026-06-09" } } ``` > [!NOTE] > > The `closingDate` field lives in the `bankingDetails` object of the Alias Account and uses `YYYY-MM-DD` format. See [Alias Accounts](/en/products/midaz/crm/alias-accounts) for the full field reference. BACEN account-lifecycle reporting needs an accurate closing date. ### Step 6: Close the Ledger Accounts in Midaz After you zero the balances and clear pending activity, close each Ledger Account. ```http theme={null} POST /v2/.../accounts/{accountId}/close ``` The request takes no body. A successful request returns `204 No Content`, and every later read of the account shows the closing instant in `closedAt`. Repeat for every account linked to the Holder. See [Close an account](/en/reference/products/midaz/v2/close-account) for the full contract and the [Midaz error list](/en/reference/products/midaz/error-list) for each refusal. > [!NOTE] > > Midaz refuses every later movement on a closed account, and unblocking the account does not reopen it. An external account cannot be closed. ### Step 7: Delete the Ledger Accounts Delete each closed account. The delete also archives (soft-deletes) every Alias Account linked to the account. ```http theme={null} DELETE /v2/.../accounts/{accountId} ``` Step 8 refuses to archive a Holder that still owns an account that is not deleted. See [Delete an account](/en/reference/products/midaz/v2/delete-account). > [!NOTE] > > Deleting an account is a logical removal. Its transactions remain available for audit and reporting. ### Step 8: Archive the Holder in CRM After you delete all of its accounts, archive the Holder itself with a soft delete. ```http theme={null} DELETE /v2/organizations/{organization_id}/holders/{holder_id} ``` > [!WARNING] > > Do **not** pass `hard_delete=true`. Keep the Holder record under the applicable retention policy for audit and regulatory inspection. See [Delete a holder](/en/reference/products/midaz/v2/delete-holder). ## Via Console *** Run the same eight-step closure flow from the [Midaz Console](/en/products/midaz/console/midaz-module). The Console covers most of the flow point-and-click. Settling pending transactions (Step 3), registering the closing date (Step 5) and closing the accounts (Step 6) require the API. Each step below notes the equivalent API step on this page. > [!WARNING] > > The order is the same as the API flow. Do not archive CRM records before you close the accounts. ### Step 1: Freeze the Holder Mark the Holder as inactive to record the closure. This is a record change and does not block new credits on its own. **Step 1** From the **Holders** page, find the Holder to close. **Step 2** Click the three dots () in the **Actions** column, and select **Edit**. **Step 3** In the Holder form, set the **Status** to **Inactive**. **Step 4** Confirm the update. > [!NOTE] > > Marking the Holder inactive is a record change, not a deletion. The record stays fully readable for audit. It does not block new credits on its own. Step 2 blocks inflows at the balance level. See [Editing a Holder](/en/products/midaz/console/crm-editing-a-holder). ### Step 2: Block credits on the accounts **Step 1** From the **Accounts** page, open each account linked to the Holder. **Step 2** In its balances, open each balance except `overdraft` and turn off **Receive**. > [!NOTE] > > Repay any non-zero `overdraftUsed` first. ### Step 3: Settle pending activity > [!WARNING] > > **This step requires the API.** The Console cannot commit or cancel a pending transaction. Follow [Step 3: Settle pending activity](#step-3-settle-pending-activity) in the Via API section. ### Step 4: Zero the balance Return any remaining funds to the customer and confirm `available = 0`, `onHold = 0`, and `overdraftUsed = 0` on every balance. **Step 1** From the **Transactions** page, click **New Transaction**. Create a **return transaction** that moves the remaining `available` amount from each customer account to the holder's designated destination, for example an external settlement account. See [Creating a Transaction](/en/products/midaz/console/creating-a-transaction). **Step 2** Open each account and confirm **available = 0** and **onHold = 0** before you continue. Confirm `overdraftUsed = 0` on the **Raw** tab of each balance. > [!WARNING] > > The close operation refuses an account with any balance whose `available`, `onHold`, or `overdraftUsed` amount is not exactly zero. ### Step 5: Register the closing date on the alias > [!WARNING] > > **This step requires the API.** The Console Alias Account form has no closing date field. Follow [Step 5: Register the closing date on the alias](#step-5-register-the-closing-date-on-the-alias) in the Via API section before you delete the account in Step 7. ### Step 6: Close the Ledger Accounts in Midaz > [!WARNING] > > **Closing requires the API.** Follow [Step 6: Close the Ledger Accounts in Midaz](#step-6-close-the-ledger-accounts-in-midaz) in the Via API section. ### Step 7: Delete the Ledger Accounts Delete each closed account. The delete also archives every Alias Account linked to the account. **Step 1** From the **Accounts** page, find the Account linked to the Holder, click the three dots () in the **Actions** column, and select **Delete**. **Step 2** A confirmation dialog will appear. Click **Confirm** to finalize the deletion. **Step 3** Repeat for every account linked to the Holder. See [Deleting an Account](/en/products/midaz/console/deleting-an-account). ### Step 8: Archive the Holder in CRM After you delete all of its accounts, archive the Holder itself with a **soft delete**. **Step 1** From the **Holders** page, find the Holder to archive, click the three dots () in the **Actions** column, and select **Delete**. **Step 2** A confirmation dialog will appear. Click **Confirm** to finalize. > [!WARNING] > > The Console deletes the Holder with a soft delete. See [Deleting a Holder](/en/products/midaz/console/crm-deleting-a-holder). ## BACEN compliance notes *** * **Order is mandatory.** Freeze first (Steps 1–2), then settle and zero (Steps 3–4). This order stops funds from entering an account that is mid-closure. * **Return funds before closing.** Return any residual balance to the customer before you close an account. The close operation refuses an account that holds funds. * **Archive, don't erase.** A soft delete (no `hard_delete`) keeps Holders and alias accounts available for the regulatory retention period. Permanent deletion would remove evidence that BACEN audits need. * **Record the closing date.** The `closingDate` on the alias gives regulators an authoritative timestamp for when the relationship ended. * **Preserve the audit trail.** The operations of a deleted account remain queryable for reconciliation and reporting. > [!TIP] > > Treat the eight steps as a single transaction from a compliance standpoint. If any step fails, pause and resolve it before you continue. Do not leave the customer in a partially closed state. # Common mistakes to avoid Source: https://docs.lerian.studio/en/products/midaz/common-mistakes-to-avoid Avoid the typical pitfalls of Midaz implementations in Ledger structuring, Asset segregation, Accounting Routes, and external Accounts. A reliable Midaz implementation depends on a few structural choices you make early. Avoid the common mistakes below to keep balances accurate and access under control. ## Poor Ledger structuring *** * **Mistake:** You design ledgers that are too complex or too simplistic. For example, one ledger per customer creates fragmentation. Grouping unrelated processes creates confusion. * **Best practice:** Structure ledgers around key business areas or legal entities. Use organized groupings instead of a one-to-one approach. This improves manageability and internal transfers. ## Not using Portfolios for clients *** * **Mistake:** You treat each account in isolation instead of grouping it under a portfolio. This makes it hard to track all accounts linked to a single customer. * **Best practice:** Create a portfolio for each customer. Group their accounts for simple queries, relationship management, and reporting. ## Mixing Assets in one Account *** * **Mistake:** You manage multiple currencies or asset types in a single account, often through metadata overrides. This leads to unclear balances and reporting inconsistencies. * **Best practice:** Assign one asset per account. If a customer needs multi-currency support, create separate accounts. Use naming conventions or portfolios to structure them. ## Inadequate Accounting Routes *** * **Mistake:** You submit transactions without properly configured Operation Routes or Accounting Routes (Transaction Routes in the API). This causes inconsistent validations, misrouted funds, and unreliable ledger data. * **Best practice:** Define Accounting Routes that reflect your business logic and compliance requirements, then set the Ledger setting `accounting.validateRoutes` to `true` to enforce them. Its default is `false`. Use Operation Routes to validate the source and destination of each operation when route validation is enabled. ## Overlooking External Account handling *** * **Mistake:** You mishandle external transactions. For example, you delete an account when funds leave the bank, which causes imbalances. * **Best practice:** Use the canonical `@external/` Account (for example, `@external/BRL`) for money that flows into and out of Midaz. This keeps the ledger balanced and matches real bank statements. ## Security lapses in access control *** * **Mistake:** You grant excessive privileges to administrators or use shared accounts. This compromises security and accountability. * **Best practice:** Implement role-based access control (RBAC) from the start. Do not use root or admin accounts for daily operations. Enforce strict credential management. Audit permissions regularly to prevent unauthorized privilege escalation. ## Improper error handling in transactions *** * **Mistake:** You fail to handle failed transactions in the integration layer. This leads to false assumptions about successful operations. * **Best practice:** Always validate transaction API responses. Implement retries with backoff for transient errors, and send the same `X-Idempotency` key on each retry. Log permanent failures. Make sure upstream systems, such as core banking applications, handle rejected transactions and notify the user. # Midaz entities Source: https://docs.lerian.studio/en/products/midaz/core-entities See how Midaz core entities (Organizations, Ledgers, Assets, Portfolios, Accounts, Segments, and Balances) connect to support financial operations at scale. This diagram shows how the main building blocks of Midaz connect to support financial operations at scale. Figure 1 gives an overview of how the system works. ![Midaz core building blocks and how its interconnected domains fit together to support financial operations at scale](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/midaz-entities-v3.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=bda0ca5101ade6a55c127a3375af6e62) Figure 1. Midaz and its interconnected domains and modular structure. ## Core components *** ### Midaz Midaz is at the center. It coordinates everything, from data persistence to business logic. ### Data Layer All data flows into the persistent **data layer**. This layer gives the system durability, consistency, and performance. ## Domains and relationships *** ### Organizations Each organization is a distinct environment in Midaz. It can hold one or many ledgers, based on how you structure your data. ### Ledgers A ledger holds all financial activity. It tracks balances, stores assets, and processes transactions. Every ledger belongs to an organization. From here, the system branches into: * **Assets**: define the kind of value you track. * **Portfolios**: group related accounts under a shared purpose. ### Assets Assets define the units of value, like BRL, USD, points, or tokens. Each account uses one specific asset. ### Portfolios Portfolios group accounts by business logic. You can create as many portfolios as you need to organize your financial structure. ### Accounts & Segments An account can belong to a portfolio. **Segments** group accounts, so you can isolate data by customer, product, region, or any other dimension. **Account Types** classify accounts by nature and purpose. They enable transaction routing and operational validation across account categories. ### Balance A **Balance** represents the net amount an **Account** holds of a given **Asset** in a specific **Ledger**. * An account can carry **multiple balances**. Each has a `balanceKey` (e.g. `default`, `collateral`, `operational`) to partition funds without splitting the account. * An **external account** has only one balance (`default`). * If you omit `balanceKey` in a transaction, Midaz uses the default balance. * Midaz derives balance amounts from ledger operations. You can add and delete balances and change their settings. ### Transactions A transaction moves value between accounts. Each transaction contains **operations** (debits and credits). This keeps your logic consistent, traceable, and aligned with your business model and accounting policies. ### Accounting Routes entities The [Accounting Routes entities](/en/products/midaz/transaction-routing-entities) extend Midaz. They create a structured system that guarantees correct annotations and correct financial-flow directions. It has two parts: * **Operation Routes:** define atomic transaction behaviors. Each route sets how Midaz annotates and directs one financial movement, based on your business rules and accounting standards. * **Accounting Routes:** orchestrate multiple Operation Routes into balanced financial events. When route validation is enabled in the ledger settings, they enforce the configured transaction structure. (The API calls this `transactionRoute`.) This pair defines the transaction structure. When you enable route validation in the ledger settings, Midaz validates transactions against the configured route. ## Get help *** > [!TIP] > > **Need help designing your Midaz setup?** > > Our consulting service can help you tailor the structure to your organization's needs. This applies whether you start from scratch or optimize an existing setup. > > [Contact us](https://lerian.studio/contact) to learn more. # Key features Source: https://docs.lerian.studio/en/products/midaz/core-features Explore the core capabilities that make Midaz adaptable and scalable: native events, multi-asset support, segments, and double-entry accounting. Midaz is a core ledger. Financial institutions use it to build, operate, and scale their transactions on a modular foundation. You keep full control of your stack. Use Midaz to launch new financial products or to modernize existing processes. The features below show how the ledger records value, scales across organizations, and keeps balances consistent. ## Native event publisher *** Midaz emits supported domain events through its configured streaming publisher. Configure and operate the delivery path required by your environment before relying on an event stream for downstream processing. ## Client segments *** Group Accounts into ledger-scoped Segments. These persisted associations support scoped rules and operational grouping. ## Double-entry accounting *** Midaz records Transactions as Operations, including debit, credit, hold, and release movements. When Accounting Route validation is enabled, configured routes validate applicable participation and posting rules. ## Multi-currency/asset support *** Midaz supports transactions in multiple currencies and assets. You operate across different financial ecosystems from one ledger. ## Multi-organization/ledger support *** One Midaz instance can run multiple Organizations and Ledgers. The domain model scopes financial resources by Organization and Ledger. ## N:N transactions *** A single transaction can move value between many source and destination accounts. This N:N model supports complex business flows. ## Native race condition handling *** Race conditions happen when multiple operations change the same balance at the same time. Midaz validates and updates all balances of a transaction in one atomic step. Transactions stay reliable and accurate under high concurrency. ## Wallets portfolio management *** Group accounts into portfolios to manage them together. You get full visibility and control over assets and balances. ## Visual interface *** A web console gives you a single place to manage transactions, configuration, and system insights. > [!NOTE] > > In newer releases, **[Lerian Console](/en/platform/console/about-lerian-console)** provides the visual interface for Midaz. Midaz runs there as the **[Midaz Module](/en/products/midaz/console/midaz-module)**. If you run an older version, you may still have the standalone Midaz Console. # Data model Source: https://docs.lerian.studio/en/products/midaz/data-model Reference the core tables and schemas that power Midaz, designed for developers and database administrators working close to the data. > [!TIP] > > **This page is for developers and database administrators.** It contains detailed database schemas and table structures. For a business-level overview of Midaz entities and their relationships, see [About Midaz](/en/products/midaz/about-midaz). Explore the core tables that power Midaz. As Midaz evolves, it may add new fields and tables. Midaz keeps the tables on this page in two PostgreSQL databases: * **Onboarding database**: `organization`, `ledger`, `asset`, `account_type`, `account`, `portfolio`, and `segment`. * **Transaction database**: `balance`, `operation_route`, `operation`, `transaction_route`, and `transaction`. Midaz stores the `metadata` of each entity in MongoDB, not in these tables. Column names are database names and can differ from the API field names. ## Tables *** ### Table: `organization` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Organization. | | **parent_organization_id** | `uuid` | The unique identifier of the parent Organization. | | **legal_name** | `text` | The legal name of the Organization. | | **doing_business_as** | `text` | The trade name of the Organization. | | **legal_document** | `text` | The document of the Organization. | | **address** | `jsonb` | The address of the Organization. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `ledger` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Ledger. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **name** | `text` | The name of the Ledger. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **settings** | `jsonb` | The [Ledger settings](/en/products/midaz/ledgers#ledger-settings). | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `asset` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Asset. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **name** | `text` | The name of the Asset. | | **type** | `text` | The type of Asset (`currency`, `fiat`, `crypto`, `commodity`, `others`). | | **code** | `text` | The code used to refer to the Asset. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `account_type` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Account Type. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **name** | `varchar(100)` | Name of the Account Type. | | **description** | `text` | Description of the Account Type. | | **key_value** | `varchar(50)` | The key that identifies the Account Type in the Ledger. | | **default_direction** | `varchar(16)` | The default [balance direction](/en/products/midaz/balance-overdraft) for Accounts of this type: `credit` or `debit`. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `account` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Account. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **asset_code** | `text` | The code used to refer to the Asset. | | **name** | `text` | The name of the Account. | | **alias** | `text` | The alias that transactions use to address the Account. | | **type** | `text` | The type of account. | | **parent_account_id** | `uuid` | The unique identifier of the Parent Account. | | **entity_id** | `text` | A reference to a record in an external system. | | **holder_id** | `uuid` | The unique identifier of the Holder that owns the Account. | | **holder_check_skipped** | `boolean` | `true` when a `skip` flag bypassed the Holder check at creation. | | **portfolio_id** | `uuid` | The unique identifier of the Portfolio. | | **segment_id** | `uuid` | The unique identifier of the Segment. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **blocked** | `boolean` | `true` when the Account is blocked. | | **closed_at** | `timestamptz` | Timestamp of closing, if applicable (UTC). | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `portfolio` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Portfolio. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **entity_id** | `text` | The unique identifier of the user responsible for the Portfolio. | | **name** | `text` | The name of the Portfolio. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `segment` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Segment. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **name** | `text` | The name of the Segment. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `balance` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Balance. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **account_id** | `uuid` | The unique identifier of the Account. | | **alias** | `text` | The alias of the Account. | | **key** | `text` | The balance key. The default balance uses `default`. | | **asset_code** | `text` | The code used to refer to the Asset. | | **available** | `decimal` | The available amount. | | **on_hold** | `decimal` | Amount on hold/reserved. | | **version** | `bigint` | Balance version. | | **account_type** | `text` | The type of account. | | **allow_sending** | `boolean` | If true, indicates that sending transactions is permitted. | | **allow_receiving** | `boolean` | If true, indicates that receiving transactions is permitted. | | **direction** | `varchar(16)` | The [balance direction](/en/products/midaz/balance-overdraft): `credit` or `debit`. | | **overdraft_used** | `decimal` | The overdraft amount in use. | | **settings** | `jsonb` | The balance settings, such as the overdraft limit. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `operation_route` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Operation Route. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. Empty for a route that belongs to the Organization. | | **title** | `varchar(255)` | Short text summarizing the purpose of the operation. Used as an entry note for identification. | | **description** | `varchar(250)` | Detailed description of the Operation Route purpose and usage. | | **code** | `text` | The code of the Operation Route. | | **operation_type** | `varchar(20)` | The entry's applicability: `source`, `destination`, or `bidirectional`. | | **account_rule_type** | `varchar(20)` | The rule that selects the account: `alias` or `account_type`. | | **account_rule_valid_if** | `text` | The values that the account rule accepts. | | **accounting_entries** | `jsonb` | The [accounting entries](/en/products/midaz/accounting-entries) of the route. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `operation` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Operation. | | **transaction_id** | `uuid` | The unique identifier of the Transaction. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **account_id** | `uuid` | The unique identifier of the Account. | | **account_alias** | `text` | The alias for the account used in the operation. | | **balance_id** | `uuid` | The unique identifier of the Balance. | | **balance_key** | `text` | The key of the Balance. | | **description** | `text` | Description of the operation. | | **type** | `text` | The type of the operation, such as `DEBIT`, `CREDIT`, `ON_HOLD`, or `RELEASE`. | | **direction** | `varchar(10)` | The direction of the operation: `debit` or `credit`. | | **asset_code** | `text` | The code used to refer to the Asset. | | **amount** | `decimal` | The amount of the operation. | | **available_balance** | `decimal` | The available amount before the operation. | | **on_hold_balance** | `decimal` | The amount on hold before the operation. | | **available_balance_after** | `decimal` | The available amount after the operation. | | **on_hold_balance_after** | `decimal` | The amount on hold after the operation. | | **balance_version_before** | `bigint` | The balance version before the operation. | | **balance_version_after** | `bigint` | The balance version after the operation. | | **balance_affected** | `boolean` | `false` when the operation does not change the balance, as in an annotation transaction. | | **chart_of_accounts** | `text` | The name of the chart of accounts that the operation belongs to. | | **route** | `text` | **\[Deprecated]** Legacy route identifier, kept for backward compatibility. Use `route_id` instead. | | **route_id** | `uuid` | Identifier of the route used by the operation (the current route field). | | **route_code** | `text` | The code of the accounting rubric that Midaz resolved for the operation. | | **route_description** | `text` | The description of the accounting rubric that Midaz resolved for the operation. | | **snapshot** | `jsonb` | System context of the operation, such as the overdraft use before and after it. | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **recorded_at** | `timestamptz` | Timestamp of when the ledger recorded the operation (UTC). | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ### Table: `transaction_route` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the Transaction Route. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. Empty for a route that belongs to the Organization. | | **title** | `varchar(255)` | Short text summarizing the purpose of the transaction. Used as an entry note for identification. | | **description** | `varchar(250)` | A description for the Transaction Route. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | The `operation_transaction_route` table links each Transaction Route to its Operation Routes. ### Table: `transaction` | Column | Type | Description | | :- | :- | :- | | **id** | `uuid` | The unique identifier of the transaction. | | **parent_transaction_id** | `uuid` | The unique identifier of the parent transaction, such as the transaction that a revert reverses. | | **group_id** | `uuid` | Links the transactions that one cross-ledger request creates. | | **organization_id** | `uuid` | The unique identifier of the Organization. | | **ledger_id** | `uuid` | The unique identifier of the Ledger. | | **description** | `text` | Description of the transaction. | | **route** | `text` | **\[Deprecated]** Legacy route identifier, kept for backward compatibility. Use `route_id` instead. | | **route_id** | `uuid` | Identifier of the route used by the transaction (the current route field). | | **status** | `text` | The status code. | | **status_description** | `text` | The description of the status. | | **amount** | `decimal` | The sent amount. | | **asset_code** | `text` | The code used to refer to the Asset. | | **scheme** | `varchar(50)` | The payment scheme of the transaction, such as `PIX`, `WIRE`, `CARD` or `CRYPTO`, in upper case. A revert keeps the scheme of the transaction it reverses. | | **chart_of_accounts_group_name** | `text` | The name of the chart of accounts group used to categorize the operations of a transaction. | | **body** | `jsonb` | Internal copy of the transaction request. | | **fees_skipped** | `boolean` | `true` when a `skip` flag bypassed the fee calculation. | | **tracer_skipped** | `boolean` | `true` when a `skip` flag bypassed Tracer. | | **created_at** | `timestamptz` | Timestamp of creation (UTC). | | **updated_at** | `timestamptz` | Timestamp of last update (UTC). | | **deleted_at** | `timestamptz` | Timestamp of soft deletion, if applicable (UTC). | ## Data model *** *Figure 1* shows the core Midaz tables and their relationships. Use it to guide data handling and integration. ![Core Midaz database tables and the relationships between them, as a reference for data handling and integration](https://mintcdn.com/lerian-49cb71fc/0kJvev-xNu0CYwa1/images/en/d2/midaz-data-model-v3.svg?fit=max\&auto=format\&n=0kJvev-xNu0CYwa1\&q=85\&s=a5eb57d19d7615145bcf1d20b23c419c) Figure 1. Midaz tables and their relations. # Event publisher Source: https://docs.lerian.studio/en/products/midaz/event-publisher Publish Midaz transaction lifecycle CloudEvents to Kafka-compatible brokers for downstream integrations. ## Uses for transaction lifecycle events *** Transaction lifecycle events let downstream systems react without coupling to the transaction API. Use them for notifications, reconciliation, analytics, and compliance workflows. For the complete catalog and consumer contract, see [Receiving Midaz events](/en/products/midaz/receiving-midaz-events). ## Enable transaction lifecycle events *** Midaz publishes lifecycle CloudEvents to a Kafka-compatible broker. Publication is off by default. Configure the ledger application with a broker list and its CloudEvents source: ```env theme={null} STREAMING_ENABLED=true STREAMING_BROKERS= STREAMING_CLOUDEVENTS_SOURCE=ledger ``` You must set `STREAMING_CLOUDEVENTS_SOURCE` when you enable streaming. The ledger, CRM, and Fees binary uses `ledger`. The transaction facts publish to `lerian.streaming.ledger`. If you enable streaming without `STREAMING_BROKERS`, Midaz refuses to start. When streaming is off, Midaz uses a no-op emitter. ## Lifecycle events *** Midaz emits these public facts for eligible persisted transaction state changes: | Fact | When Midaz emits it | | - | - | | `transaction.posted` | A newly created transaction is `APPROVED` and has no parent transaction. | | `transaction.reverted` | A newly created `APPROVED` transaction has a parent transaction. | | `transaction.committed` | A transaction status update reaches `APPROVED`. | | `transaction.canceled` | A transaction status update reaches `CANCELED`. | Midaz does not emit a lifecycle fact for a newly created `PENDING` transaction, a `NOTED` transaction, or a no-op state change. A pending transaction emits only when a later status update commits or cancels it. When one request moves value across ledgers, Midaz also emits one fact for the whole movement: `transaction_group.posted`, `transaction_group.committed`, `transaction_group.canceled`, or `transaction_group.reverted`. ## Consume events *** Subscribe to `lerian.streaming.ledger` and select the facts you need using the CloudEvents headers. Do not infer event type from the Kafka topic: Midaz uses one application topic for ledger, CRM, and Fees facts. Use the producer manifest as the deployment-time contract: ```http theme={null} GET /v1/streaming/manifest ``` The manifest remains available even when publication is off. The [Midaz event reference](/en/reference/events/midaz) lists the event payloads. > [!NOTE] > > Event publication is best effort and does not make the broker write transactional with the ledger mutation. Consumers must be idempotent and deduplicate on `(ce-source, ce-id)`. # FAQ Source: https://docs.lerian.studio/en/products/midaz/faq Answers to common Lerian and Midaz questions on API pagination limits, SaaS data isolation, tenant JWT scoping, and multi-organization platform configuration. ## Lerian APIs *** This section answers common questions about Lerian's APIs. > [accordion] Is there a maximum number of records per page in API listings? Can I increase this limit? > > Yes. In Midaz, the default maximum is **100** records per page. This limit keeps performance consistent and controls the data volume in each request. To raise it, set the `MAX_PAGINATION_LIMIT` environment variable in your deployment configuration. Most listings accept larger page sizes after you restart the application. > > **Important**: A larger page size can slow response times, especially with large datasets. Test in staging before you change production. ## Tenants on Lerian Cloud *** These questions cover data isolation and tenant scoping on Lerian Cloud. > [accordion] Is my data isolated from other institutions in SaaS? > > Yes. Your data is isolated from every other tenant, with its own credentials. The platform resolves your tenant from the JWT on every request. There is no way to access another tenant's data through the API. > [accordion] Do I need to pass a tenant ID in my API requests? > > No. The JWT access token you receive during authentication carries your tenant context. The platform resolves it automatically. You do not need to include a tenant identifier in headers or request bodies. > [accordion] Can I have multiple Organizations under a single tenant? > > Yes. A tenant can contain multiple Organizations. Each Organization has its own Ledgers, accounts, and transactions. The platform scopes all of them to your tenant automatically. > [accordion] Is the API different between SaaS and self-hosted deployments? > > No. The API surface is identical: same endpoints, same payloads, same responses. SaaS requires authentication on every request, and your token scopes all operations to your tenant. ## Midaz *** These questions cover Organizations, Ledgers, Accounts, Transactions, and more in Midaz. ### Organizations > [accordion] Do different Organizations communicate with each other? > > Each Organization operates independently. A cross-ledger transaction can move value between Ledgers of different Organizations in the same tenant. > [accordion] Can I use a single license across multiple Organizations? > > Yes. A license key covers the whole deployment, not one Organization. A key that Lerian issued for organization identifiers works only with them: ask Lerian for a new key. See [License Manager](/en/platform/licensing/license-manager) and [Lerian's License](/en/start-here/evaluate-and-deploy/lerians-license). > [accordion] Can an Organization have multiple Plugins? > > Yes. An Organization can have more than one Plugin. > [accordion] Can an Organization have multiple Ledgers? > > Yes. An Organization can manage multiple Ledgers. > [accordion] Can I create transactions between a Parent Organization and a Child Organization? > > You can create a **Parent Organization** and a **Child Organization**. Each Organization keeps its own Ledger and operates independently. To move value between their Ledgers, send one cross-ledger transaction. Every participating Ledger must set `settings.crossLedger.enabled` to `true`, and none can have `accounting.validateRoutes` set to `true`. You can also orchestrate the transfer with these steps: > > **Step 1** > > In the source ledger, create a transaction from the original account (**source**) to the asset's **external account** (distribute). This removes the value from the source ledger. > > **Step 2** > > In the destination ledger, create a second transaction. The **source** is now the asset's **external account**, and the destination is the receiving account (**distribute**). > > This pattern moves value between ledgers in different Organizations. ### Ledgers > [accordion] Do different Ledgers communicate with each other? > > Ledgers keep separate books. A cross-ledger transaction moves value between Ledgers that set `settings.crossLedger.enabled` to `true`. > [accordion] How can I make transactions between Ledgers? > > Send one `POST /v2/transactions/direct` or `POST /v2/transactions/hold` request with legs in each Ledger. Every participating Ledger must set `settings.crossLedger.enabled` to `true`. Midaz creates one balanced transaction per Ledger. You can also move the amount through an External Account in two steps: > > **Step 1** > > Ledger A -> External Account. > > **Step 2** > > External Account -> Ledger B. > [accordion] Do I need a separate Ledger for each Plugin? > > No. A single Ledger can support multiple Plugins. For example, one Ledger can handle both Exchange and Pix Plugins. ### Assets > [accordion] Can an Asset be linked to multiple Accounts? > > Yes. Many Accounts can use the same Asset. Each Asset also links to an External Account. Midaz creates that External Account automatically when you create the Asset. > [accordion] What types of Assets can I use? > > Midaz supports several Asset types: > > * *currency*: Traditional fiat currencies like BRL, USD, and EUR. > * *fiat*: An alternative type for fiat currencies; like `currency`, the Asset code must follow ISO 4217. > * *crypto*: Digital assets such as BTC, ETH, and other cryptocurrencies. > * *commodity*: Tangible goods like gold, soybean, and oil. > * *others*: Custom Assets, including loyalty points and tokenized securities. ### Portfolios > [accordion] How does a Portfolio work? > > A **Portfolio** groups accounts that belong to the same entity (**CPF/CNPJ**). For example, one CPF with two different `segmentId` values has two matching accounts. You create a Portfolio for that CPF to link both accounts under one structure. ### Accounts > [accordion] Can an Account be associated with multiple Assets? > > No. Each Account links to a single Asset. You cannot change this link. > [accordion] What is an External Account? > > An External Account receives funds from outside the Ledger. It brings money into the system. > [accordion] How can I create an External Account? > > Midaz creates an **External Account** automatically when you create an Asset. You can also create one yourself: send `type` as `external` with an `alias`. > [accordion] Can an Account be linked to several Segments? > > No. Each account links to only one Segment (`segmentId`). > [accordion] Is there a limit to how many Accounts I can create in Midaz? > > No. You can create as many Accounts as you need. Midaz sets no limit on the number of Accounts. > [accordion] What is the process for adding funds to an account or performing a cash-in using money coming from outside the Ledger (Midaz) environment? > > The balance top-up process works as follows: > > 1. When you create an Asset (for example, BRL) in the Midaz Ledger, Midaz also creates an External Account for that Asset. > 2. This External Account mirrors the balances the institution holds outside Midaz. Those balances can sit in a PI account, a settlement account, a reserve account, or a traditional bank or payment account. > 3. To deposit funds from outside the Midaz Ledger into a user account, follow these steps: > * Create a transaction with the External Account as the source and the target accounts as the destination. > * Midaz debits the External Account by the amount and credits the destination accounts by the values in the transaction payload. ### Transactions > [accordion] What is the minimum structure of a Transaction? > > A direct transfer of R\$ 100 from Account A to Account B has two operations: > > * **Operation 1:** Debit R\$ 100 from Account A. > * **Operation 2:** Credit R\$ 100 to Account B. > [accordion] Is it possible to generate a PDF transfer receipt containing the details of a completed transaction? > > Lerian gives clients several ways to access transaction receipts: > > 1. **Via APIs**: retrieve transaction data through the APIs, then generate a visual receipt in any format you choose. > 2. **With the Reporter**: extract transaction data and create custom visual receipts. > 3. **Through the Console**: access transaction data directly in the Lerian Console. ### Entities > [accordion] How can I create an Entity? > > The `entityId` field accepts external IDs of up to 256 characters. Midaz does not validate their format. You can use the IDs that already exist in your database and integrate them into your system. ### Idempotency > [accordion] Can I reuse an idempotency key across endpoints? > > No. Scope each key to a single operation and endpoint. > [accordion] What happens if I change the TTL on a retry? > > Midaz uses only the TTL from the first request. A later change has no effect. > [accordion] Will the replayed response always be identical? > > Yes. For a completed request, Midaz returns the same result it stored from the first request. It also sets the `X-Idempotency-Replayed` header to `true`. > [accordion] What's the default TTL if I don't send X-TTL? > > The default TTL is **300 seconds** (5 minutes). Send the `X-TTL` header to set a custom value in seconds. ### Accounting in Midaz > [accordion] How can I reflect my own Chart of Accounts in Midaz? > > Midaz lets you mirror your organization's official **Chart of Accounts** in the platform. You configure two core features: > > * [Account Types](/en/products/midaz/accounts): create the logical categories from your chart, such as Assets, Liabilities, Revenue, and Expenses. Assign them to accounts in your ledger. When you enable account type validation (`validateAccountType`), the `type` field in the Accounts API must match a registered value. > * [Accounting Routes](/en/products/midaz/transaction-routing-entities): use Operation Routes to validate each leg of a transaction. For example, a debit must come from an account of type `user_wallet`. Use Accounting Routes (the `transactionRoute` resource in the API) to define complete transaction patterns that match your accounting logic. > > Account Types and Accounting Routes together enforce your accounting rules at the ledger level. Midaz validates every transaction against your Chart of Accounts when you enable route validation (`validateRoutes`). You do not hardcode rules in your business logic. ## Plugins *** Plugins extend Midaz with integration and process orchestration. They provide abstractions so you can focus on your business model instead of system logic outside your domain. The questions below cover how plugins work, how you deploy them, and the options available. > [accordion] What are Plugins? > > Plugins are technologies that integrate into the Midaz ledger. They simplify process integration and orchestration. They provide abstractions so clients can focus on their business model. Clients do not build or manage system logic outside their domain. > [accordion] How are plugins distributed? > > After you contract a plugin, Lerian provides it. In the [BYOC model](/en/start-here/evaluate-and-deploy/deployment-models), the plugin runs in your infrastructure, next to your Midaz instance. Applications connect to each plugin according to its function. > [accordion] What plugin options does Lerian offer? > > Lerian provides two types of plugins, grouped by origin: > > * **Native Plugins:** Lerian develops and integrates these plugins into the Midaz ledger. Lerian provides full support for them. > * **Marketplace Plugins:** Lerian's partners create these plugins for specific market niches. Lerian helps integrate them into Midaz. The partners provide and support them directly. ## Fees Engine *** These questions cover Fees Engine. Fees Engine is a licensed Midaz capability that runs inside the unified ledger process. ### General Concepts > [accordion] What is Fees Engine? > > Fees Engine is part of Midaz. It runs in the Midaz ledger process to calculate fees for financial transactions. Configure and deploy it with Midaz. Learn more in the [Fees Engine overview](/en/products/midaz/fees/fees-engine-overview). It works across four main domains: > > * **Fee Packages (`/v2/organizations/{organization_id}/ledgers/{ledger_id}/packages`):** defines charging rules per transaction (flat fee, percentage, or whichever is greater). > * **Billing Packages (`/v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages`):** defines periodic charges based on transaction volume or account maintenance. > * **Account Plans (`/v2/organizations/{organization_id}/ledgers/{ledger_id}/account-plans`):** defines fees that you assign to accounts, with a free quota per calendar month. See [Account plans](/en/products/midaz/fees/account-plans). > * **Calculation and estimation:** the Ledger evaluates fees during the transaction flow. Use `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/estimates` for a package-specific preview and `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing/calculate` for periodic billing. > [accordion] How does Fees Engine fit into the Lerian ecosystem? > > Fees Engine runs inside the Midaz ledger process. When a configured fee package applies, Midaz incorporates its fee calculations into the transaction. It uses ledger query use cases rather than an external HTTP connection to Midaz. > [accordion] What do I need to send in every request to Fees Engine? > > Fees endpoints are organization-scoped through the organization ID in the `/v2` URL path. The platform resolves tenant context from the authenticated request; send the authorization material required by your Access Manager configuration. > > ``` > Authorization: Bearer *** > ``` > [accordion] What database does Fees Engine use for storage? > > Fees Engine uses MongoDB for storage. Deletions follow the **soft-delete** pattern. Fees Engine does not remove records physically. It marks them with `deletedAt` instead. A deleted record does not appear in listings, but you can still audit it. > [accordion] What Midaz version provides the integrated Fees module? > > Midaz v4 exposes Fees inside the unified Ledger on `/v2`. ### Fee Packages > [accordion] What is a Fee Package? > > A Fee Package (`Package`) is a set of charging rules under one `feeGroupLabel`. Each package links to an **Organization + Ledger**, and optionally to a **Segment**. A package can contain several fees (`Fee` objects), each with its own calculation logic. Learn more about [Fee Packages](/en/products/midaz/fees/using-fee-engine). > [accordion] How do I create a Fee Package? > > Send a `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/packages` with the following body. See the [Create Package API reference](/en/reference/products/midaz/v2/create-package) for full details. > > ```json theme={null} > { > "feeGroupLabel": "Digital Account Fees", > "segmentId": "{segment_id}", > "minimumAmount": "100.00", > "maximumAmount": "50000.00", > "transactionRoute": "{transaction_route_id}", > "enable": true, > "waivedAccounts": ["exempt-account-1", "exempt-account-2"], > "fees": { > "adminFee": { > "feeLabel": "Administrative Fee", > "calculationModel": { > "applicationRule": "percentual", > "calculations": [ > { "type": "percentage", "value": "1.50" } > ] > }, > "referenceAmount": "originalAmount", > "priority": 1, > "isDeductibleFrom": true, > "creditAccount": "fee-revenue-account" > } > } > } > ``` > [accordion] Can a package be temporarily disabled? > > Yes. Set the `enable` field to `false` when you create or update the package. Fees Engine skips a disabled package during fee calculation, even when the transaction context matches its scope. > [accordion] How does the package scope work (minimumAmount / maximumAmount)? > > Fees Engine applies the package only to transactions whose value falls within the `[minimumAmount, maximumAmount]` range. If the transaction value falls outside this range, Fees Engine ignores the package. > > **Example:** A package with `minimumAmount: 100` and `maximumAmount: 5000` charges fees only on transactions between 100 and 5,000. > [accordion] Can I filter a package by transaction route? > > Yes. Set the `transactionRoute` field to a transaction route ID. Fees Engine then considers the package only for transactions that carry that `routeId`. > [accordion] What are waivedAccounts? > > These are account aliases that the package **exempts** from fees. When every source account of a transaction is in `waivedAccounts`, Fees Engine does not apply the package fees. A waived account does not pay a package fee. > > ```json theme={null} > "waivedAccounts": ["vip-account", "employee-account"] > ``` > > This package does not charge these accounts. > [accordion] Do listing endpoints have pagination? > > Yes. The listing endpoints (`GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/packages`, `GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages`) support the `limit` and `page` query parameters for pagination. > > ``` > GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/packages?limit=20&page=2 > ``` ### Calculation Models > [accordion] What calculation models are available? > > The `applicationRule` field inside `calculationModel` defines how Fees Engine calculates the fee. See [Calculation Models](/en/products/midaz/fees/fee-engine-calculation) for full details. There are three options: > > | Rule | Description | > | - | - | > | `flatFee` | Fixed-amount fee | > | `percentual` | Percentage fee based on the reference amount | > | `maxBetweenTypes` | Evaluates 2 or more calculations; applies the **greater** result | > [accordion] How do I configure a flat fee (flatFee)? > > Use exactly **1 calculation** of type `flat`: > > ```json theme={null} > "calculationModel": { > "applicationRule": "flatFee", > "calculations": [ > { "type": "flat", "value": "5.00" } > ] > } > ``` > > This charges a fixed 5.00 regardless of the transaction amount. > [accordion] How do I configure a percentage fee (percentual)? > > Use exactly **1 calculation** of type `percentage`: > > ```json theme={null} > "calculationModel": { > "applicationRule": "percentual", > "calculations": [ > { "type": "percentage", "value": "2.50" } > ] > } > ``` > > This charges 2.5% of the transaction's reference amount. > [accordion] How does maxBetweenTypes work? > > `maxBetweenTypes` requires **2 or more calculations**. Fees Engine calculates each and applies the **greater result**. > > **Example:** Minimum fee of 3.00 or 1% of the value, whichever is greater: > > ```json theme={null} > "calculationModel": { > "applicationRule": "maxBetweenTypes", > "calculations": [ > { "type": "flat", "value": "3.00" }, > { "type": "percentage", "value": "1.00" } > ] > } > ``` > > For a 200 transaction: 1% = 2.00 vs. 3.00 flat → charges **3.00**. > For a 500 transaction: 1% = 5.00 vs. 3.00 flat → charges **5.00**. > [accordion] Can I mix multiple percentages in maxBetweenTypes? > > Yes. You can include any combination of `flat` and `percentage`. Fees Engine evaluates all of them and applies the greatest. `flatFee` and `percentual` require exactly 1 calculation. Only `maxBetweenTypes` accepts 2 or more. ### Important Fields > [accordion] What is referenceAmount and how does it affect calculation? > > The `referenceAmount` defines **which value** Fees Engine calculates the fee on: > > * `originalAmount`: the original transaction value, **before** any fees. > > * `afterFeesAmount`: the transaction value **after** higher-priority fees apply. > > > [!NOTE] > > > > The fee with `priority: 1` runs first, so it **must** use `originalAmount`. No prior fees exist to consider. > [accordion] What is isDeductibleFrom and when should I use it? > > When `isDeductibleFrom: true`, Fees Engine deducts the fee from the amount the sender sends. The recipient receives the discounted amount. > > When `false`, Fees Engine charges the fee **separately**. The sender sends the full amount, and Fees Engine debits the fee apart. > > **Constraints:** > > * `isDeductibleFrom: true` requires `referenceAmount: originalAmount` > * If the type is `percentage`: the value cannot exceed 100 > * If the type is `flat`: the value cannot exceed the package's `minimumAmount` > [accordion] How does the priority field work? > > The `priority` defines the **execution order** of fees within a package. Fees Engine runs lower values first. > > * `priority: 1` → executed first (must use `originalAmount`) > * `priority: 2` → executed after, can use `afterFeesAmount` > > Use priorities to chain fees. For example, run an administrative fee on the original amount. Then run an IOF fee on the amount after the administrative fee. > [accordion] What is creditAccount? > > It is the alias of the ledger account that receives the fee revenue. Each fee can have a different `creditAccount`. This helps when different fees belong to different cost centers. > > ```json theme={null} > "creditAccount": "admin-fee-revenue-account" > ``` > [accordion] What are routeFrom and routeTo inside a fee? > > These fields define the routes of the **accounting legs** that the fee charge generates. They are optional. They let you track the origin and destination of fee movements in the ledger. ### Billing Packages > [accordion] What are Billing Packages? > > Billing Packages are **periodic** charge packages, independent of per-transaction fee calculation. See [Billing Package examples](/en/products/midaz/fees/billing-package-examples) for use cases. There are two types: > > * **`volume`:** charges based on the **number of transactions** in a period, with tiered pricing. > * **`maintenance`:** charges a **fixed fee per account** in a given scope. > [accordion] When should I use volume billing? > > Use volume billing to charge clients by the **number of processed transactions**. This is a common model for payment platforms with volume-based pricing. You define price tiers that apply as volume grows. > > ```json theme={null} > { > "label": "Pix volume billing", > "type": "volume", > "eventFilter": { > "transactionRoute": "PIX", > "status": "approved" > }, > "pricingModel": "tiered", > "tiers": [ > { "minQuantity": 0, "maxQuantity": 1000, "unitPrice": "0.50" }, > { "minQuantity": 1001, "unitPrice": "0.30" } > ], > "assetCode": "BRL", > "debitAccountAlias": "client-account", > "creditAccountAlias": "volume-revenue-account" > } > ``` > [accordion] When should I use maintenance billing? > > Use maintenance billing to charge a **fixed periodic fee per account**. For example, charge a monthly fee per active account. You specify the scope (`segmentId`, `portfolioId`, or `aliases`) and the fee amount. > > ```json theme={null} > { > "label": "Monthly account maintenance", > "type": "maintenance", > "feeAmount": "15.00", > "assetCode": "BRL", > "maintenanceCreditAccount": "maintenance-revenue-account", > "accountTarget": { > "segmentId": "{segment_id}" > } > } > ``` > > > [!NOTE] > > > > `accountTarget` must have exactly **one** of the three fields: `segmentId`, `portfolioId`, or `aliases` (maximum 100 aliases). > [accordion] How do tiers work in volume billing? > > Tiers define the **unit price per tier** as volume increases. The rules are: > > 1. Must be **contiguous**: no gaps between tiers (`minQuantity` of the next = `maxQuantity` of the previous + 1). > 2. Must not **overlap**. > 3. For multiple tiers, the last tier must omit `maxQuantity`. A single bounded tier is accepted. A positive billable count outside that tier fails the entire calculation call. > > **Example of correct tiers:** > > ```json theme={null} > "tiers": [ > { "minQuantity": 0, "maxQuantity": 500, "unitPrice": "0.80" }, > { "minQuantity": 501, "maxQuantity": 2000, "unitPrice": "0.60" }, > { "minQuantity": 2001, "unitPrice": "0.40" } > ] > ``` > [accordion] What is freeQuota? > > It is a **free allowance**. Fees Engine does not charge a set number of transactions before tiers apply. This helps pricing models with a minimum included volume. > > **Example:** `freeQuota: 100` means Fees Engine does not charge the first 100 transactions in the period. > > An account plan fee has its own `freeQuota`, counted per account and calendar month. See [Free quota](/en/products/midaz/fees/account-plans#free-quota). > [accordion] What are discountTiers? > > These are discount tiers for volume billing. They reduce the charged amount based on extra criteria. They complement the logic of the main `tiers`. > [accordion] What is countMode in volume billing? > > `countMode` accepts `perRoute` and `perAccount`. Fees Engine counts the transactions that match the `eventFilter` route and status of the package in the billing period, across the Ledger. ### Fee calculation and billing > [accordion] How are transaction fees calculated in Midaz v4? > > The Ledger evaluates fees in the transaction flow when a matching package applies. A source account with an active account plan pays no package fee. Its plan charges it only when a plan fee matches the transaction, after the free quota of that fee. Use `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/estimates` for a package-specific preview. > [accordion] Which v4 endpoints configure fees? > > Configure transaction fee packages at `/v2/organizations/{organization_id}/ledgers/{ledger_id}/packages` and periodic billing packages at `/v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages`. Configure account plans at `/v2/organizations/{organization_id}/ledgers/{ledger_id}/account-plans`, and assign one to an account at `/v2/organizations/{organization_id}/ledgers/{ledger_id}/accounts/{account_id}/account-plan`. > [accordion] How do I calculate periodic billing? > > Call `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing/calculate` after you configure billing packages. It processes the configured rules for that Ledger. ### Common Errors > [accordion] What does error 0188 "originalAmount is required when priority is one" mean? > > The fee with `priority: 1` must have `referenceAmount: "originalAmount"`. It is the first fee to run, so no prior fees exist to base the calculation on. > > **Fix:** > > ```json theme={null} > { > "priority": 1, > "referenceAmount": "originalAmount" > } > ``` > [accordion] How do I fix error 0205 "originalAmount is required when isDeductibleFrom is true"? > > Fees with `isDeductibleFrom: true` can only use `referenceAmount: "originalAmount"`. Update the field: > > ```json theme={null} > { > "isDeductibleFrom": true, > "referenceAmount": "originalAmount" > } > ``` > [accordion] Why do I get error 0208 "calculation value flat invalid"? > > When `isDeductibleFrom: true` and the type is `flat`, the fee value cannot exceed the package's `minimumAmount`. This prevents a fee that is larger than the minimum transaction value. > > **Example:** If `minimumAmount: 100`, the flat fee cannot exceed 100. > [accordion] When does error 0207 "calculation value percentage invalid" occur? > > This error occurs when `isDeductibleFrom: true`, the type is `percentage`, and the value is above 100. A deductible percentage fee of 100% would zero out the transaction. Values above 100 are invalid. > [accordion] How do I fix error 0218 "tiers have a gap"? > > Volume billing tiers must cover all ranges without gaps. Check that the `minQuantity` of each tier is exactly `maxQuantity + 1` of the previous tier. > > ```json theme={null} > // ❌ Wrong — gap between 500 and 600 > { "minQuantity": 0, "maxQuantity": 500, "unitPrice": "0.80" }, > { "minQuantity": 600, "unitPrice": "0.40" } > > // ✅ Correct > { "minQuantity": 0, "maxQuantity": 500, "unitPrice": "0.80" }, > { "minQuantity": 501, "unitPrice": "0.40" } > ``` > [accordion] Error 0229: "Exactly one of segmentId, portfolioId, or aliases must be provided" > > In maintenance billing, the `accountTarget` field accepts only **one** of the three options. Do not combine fields: > > ```json theme={null} > // ❌ Wrong > "accountTarget": { > "segmentId": "{segment_id}", > "portfolioId": "{portfolio_id}" > } > > // ✅ Correct > "accountTarget": { > "segmentId": "{segment_id}" > } > ``` > [accordion] Is there a limit on aliases in accountTarget? > > Yes. The `aliases` field accepts a maximum of **100 aliases** per maintenance Billing Package. > [accordion] Errors 0189 and 0191: flatFee needs exactly 1 calculation of type flat > > The `applicationRule: "flatFee"` accepts exactly 1 calculation, and it must be of type `flat`. Do not use `percentage` with `flatFee`. > > ```json theme={null} > // ✅ Correct > "calculationModel": { > "applicationRule": "flatFee", > "calculations": [{ "type": "flat", "value": "10.00" }] > } > ``` > [accordion] Errors 0189 and 0190: percentual needs exactly 1 calculation of type percentage > > Like `flatFee`, the `applicationRule: "percentual"` accepts exactly 1 calculation of type `percentage`. > [accordion] Error 0201: "applicationRule maxBetweenTypes must have more than 1 calculation" > > `maxBetweenTypes` requires at least 2 calculations, because it needs values to compare. > [accordion] What should I check when the package is not applied to the transaction? > > Diagnostic checklist (see also [Best Practices](/en/products/midaz/fees/fees-engine-best-practices)): > > * **`enable`:** is the package active (`enable: true`)? > * **Ledger:** did you create the package in the ledger of the transaction? > * **`minimumAmount` / `maximumAmount`:** is the transaction value within the range? > * **`transactionRoute`:** if the package has `transactionRoute`, does the transaction use the same route? > * **`segmentId`:** if the package is scoped to a segment, does the account belong to it? > * **`waivedAccounts`:** is the account listed as exempt? > * **Account plan:** does the source account have an active account plan? Its plan replaces the packages. > * **`metadataSelector`:** does the transaction metadata carry every pair the package selects? > * **`skip.fees`:** did the request skip fees, with `allowFeeSkip` enabled on the Ledger? > [accordion] Can a deleted record be recovered? > > Fees Engine soft-deletes records. It marks them with `deletedAt` and does not remove them from the database. The API has no restoration endpoint. Contact the Lerian team if you need to recover a deleted record. # Foundation Source: https://docs.lerian.studio/en/products/midaz/foundation-overview Meet the foundation layer of Midaz: Organizations, Ledgers, and Assets, the structural building blocks that all Accounts, Balances, and Transactions rely on. The foundation layer defines the structural building blocks of your financial data in Midaz. Organizations, Ledgers, and Assets form the base on which all accounts, balances, and transactions operate. ## Content *** * [**Organizations**](/en/products/midaz/organizations): The top-level entity that represents a financial institution. Organizations govern all financial data. They can also establish parent-child hierarchies for structures like subsidiaries, regional branches, or business units. * [**Ledgers**](/en/products/midaz/ledgers): Ledgers track all transactions and operations. Organizations can use multiple Ledgers to segregate financial operations by business line, geography, or regulatory requirement. * [**Assets**](/en/products/midaz/assets): Define the units of value your system works with: currencies like BRL and USD, cryptocurrencies, loyalty points, or tokenized securities. Each Account uses a single Asset. Midaz supports multi-asset operations within one system. # Getting help Source: https://docs.lerian.studio/en/products/midaz/getting-help Find the support channel for Midaz: the Lerian Clients portal. When you get stuck, this section points you to the right support channel. ## Content *** * [**Lerian Clients**](/en/products/midaz/lerian-support-portal): If you have a support agreement, this is the official channel. Raise tickets, request services, and get help with production issues. # Ledgers Source: https://docs.lerian.studio/en/products/midaz/ledgers Use Ledgers to track the Transactions and Operations of each Organization and to orchestrate cross-ledger transfers through the External Account of each Ledger. A **Ledger** keeps a precise record of all the Transactions and Operations of an Organization. A Ledger tracks every financial event: deposits, withdrawals, transfers, and fees. Organizations can use multiple Ledgers to segregate financial operations. For example, a bank keeps separate Ledgers for different business lines, regions, or regulatory requirements. A single Ledger can also handle all operations for a simpler setup. ## Ledger structure *** * **Ledger > Organization:** Each Organization can own multiple Ledgers, but each Ledger belongs to only one Organization. * Use multiple Ledgers only when you need to segregate data or operations, for example internal treasury operations versus customer accounts. > [!WARNING] > > By default, a transaction **cannot** move funds between Ledgers. A transaction can span Ledgers only when every Ledger it touches enables the `crossLedger.enabled` setting. ### How to orchestrate cross-Ledger transactions When every Ledger involved enables `crossLedger.enabled`, send one `direct` or `hold` transaction through the v2 API. Each leg names the `organizationId` and `ledgerId` of its account. Midaz splits the transfer into one balanced transaction per Ledger: 1. **Debit from the source Ledger:** The account in Ledger 1 sends the amount to the External Account of Ledger 1 (`@external/`). 2. **Credit to the destination Ledger:** The External Account of Ledger 2 sends the amount to the target account. The transactions share one `groupId`. In a `direct` transaction, they succeed or fail together. When a participating Ledger enables `accounting.validateRoutes`, the transaction route must link exactly one Operation Route with a `crossLedger` entry (errors `0255` and `0256`). Midaz refuses a transaction that spans Organizations when any participating Ledger validates routes (error `0251`). ## Key characteristics *** * All Accounts and Transactions exist within a Ledger. * Each Ledger keeps a balanced set of Accounts. * You can use multiple Ledgers for segmentation, but cross-ledger transactions need explicit handling. ## Multiple Ledgers *** Midaz lets you create multiple Ledgers for each organization. For example, a company can separate financial records by country, department, or business function. ### Example use case Consider a global enterprise with business in multiple regions: * Ledger 1: US Business * Ledger 2: EU Business * Ledger 3: APAC Business With separate Ledgers, the company keeps region-specific transaction records, tax rules, and currency settings. It still has unified oversight of all operations. ### When to create a new Ledger A Ledger is a hard boundary. Every movement between Ledgers passes through the External Account of each Ledger (see [How to orchestrate cross-Ledger transactions](#how-to-orchestrate-cross-ledger-transactions)). This cost drives the decision. Create a new Ledger only when the segments rarely move money between each other. Use this heuristic to pick the right level of separation: | Mechanism | What it separates | Reach for it when | | - | - | - | | **Ledger** | A complete, self-contained set of books, with its own accounts, balances, and asset configuration | You need true isolation: a separate legal entity, country, or regulatory regime, where balances should never mix and cross-segment movements are rare. | | **[Portfolio](/en/products/midaz/portfolios)** | A grouping of accounts *within* one Ledger | You want a consolidated view of a customer or business unit, but the accounts still transact freely with the rest of the Ledger. | | **[Account](/en/products/midaz/accounts) / [Account Type](/en/products/midaz/account-types)** | An individual balance and its rules | A single balance needs its own statement, nature, or restrictions. | If two sets of balances often transact with each other, keep them in the **same** Ledger. Separate them with Portfolios or Accounts. Split into multiple Ledgers only when the isolation is worth the orchestration overhead. ## Customizing Ledgers *** In Midaz, you can tailor each Ledger's configuration to your requirements. Assets are scoped to a Ledger, so the same code is an independent record in each Ledger with its own name, type, status, and metadata. **Example** To represent Bitcoin (BTC) across Ledgers, create the BTC asset independently in each Ledger and set the name, status, and metadata each Ledger needs. > [!NOTE] > > Amounts in Midaz are arbitrary-precision decimals. There is no per-asset or per-Ledger decimal-place setting. You do not configure a scale when you create an asset. ## Benefits of using Ledgers in Midaz *** * **Clear organization**: Keep clear, distinct financial records for each part of your business. * **Custom configurations**: Adjust asset settings, currencies, or other parameters per Ledger for local or departmental needs. * **Scalability**: Add or change Ledgers as your organization grows or diversifies. * **Transparency**: Get a complete view across all financial activities. Each Ledger adds to one operational picture. ## Ledger settings *** Each Ledger has configurable settings that control how it validates transactions. For example, you can require every transaction to follow a predefined route. You can also require account types to match your business rules. The Ledger then rejects invalid movements before it records them. You can change these settings at any time through the API. You do not need to restart the service or change code. ### Available settings | Setting | Default | Description | | - | - | - | | `accounting.validateAccountType` | `false` | When enabled, each new account must use an account type registered for the Ledger. The Ledger rejects the account creation if the type is not registered. | | `accounting.validateRoutes` | `false` | When enabled, every transaction must include an associated transaction route. Each operation is also validated against its operation route rules. | | `accounting.requireHolder` | `false` | When enabled, each account that you create through the v2 API must name an existing holder. | | `overrides.allowFeeSkip` | `false` | When enabled, a transaction request can set `skip.fees` to `true` to post without the fee calculation. If the setting is disabled, Midaz refuses that request with error `0490`. | | `overrides.allowTracerSkip` | `false` | When enabled, a transaction request can set `skip.tracer` to `true` to skip the Tracer call. If the setting is disabled, Midaz refuses that request with error `0490`. | | `overrides.allowHolderSkip` | `false` | When enabled, an account creation request can skip the holder check. | | `tracer.mode`, `tracer.failPosture`, `tracer.timeoutMs` | `off`, `open`, `250` | Control how the Ledger calls Tracer. See the [Tracer integration guide](/en/products/tracer/integration-guide#midaz-ledger-reservation-seam). | | `crossLedger.enabled` | `false` | When enabled, the Ledger can take part in a transaction that spans Ledgers. | > [!TIP] > > Start with `validateAccountType` and `validateRoutes` disabled while you configure your operation routes and transaction routes. Once your routing setup is complete, enable validation to enforce your business rules. ### How settings affect transactions When you enable `validateRoutes` for a Ledger: 1. Every transaction to that Ledger **must** reference a valid transaction route. 2. The Ledger validates each operation against the corresponding operation route rules. 3. The Ledger rejects any non-compliant transaction before it records the movement. When you enable `validateAccountType`: 1. The Ledger checks each new account against its registered account types. 2. If the account type is not registered, the Ledger rejects the account creation. > [!WARNING] > > If you enable validation on a Ledger that already processes transactions, existing records do not change. Validation applies to the requests that you submit after you enable the setting. This includes a commit, cancel, or revert of an earlier transaction. ### Managing settings via API Use the Ledger Settings endpoints to retrieve and update these configurations: * [Retrieve Ledger Settings](/en/reference/products/midaz/v2/get-ledger-settings): view the current settings for a Ledger. * [Update Ledger Settings](/en/reference/products/midaz/v2/update-ledger-settings): change one or more settings with a partial update (deep merge). > [!NOTE] > > Midaz applies changes with a deep merge and modifies only the fields you include in the request. ## Managing Ledgers *** You can manage your Ledgers through the API or Lerian Console. ### View API * [List Ledgers](/en/reference/products/midaz/v2/list-ledgers) - View the details of all Ledgers. * [Retrieve a Ledger](/en/reference/products/midaz/v2/get-ledger-by-id) - Get details of a specific Ledger. * [Create a Ledger](/en/reference/products/midaz/v2/create-ledger) - Register a new Ledger. * [Update a Ledger](/en/reference/products/midaz/v2/update-ledger) - Edit the details of an existing Ledger. * [Delete a Ledger](/en/reference/products/midaz/v2/delete-ledger) - Mark a Ledger as deleted. > [!NOTE] > > When you delete a Ledger, Midaz does not remove it permanently. > > Instead, Midaz sets a `deletedAt` timestamp. Midaz then excludes the Ledger from every read, and you can no longer use it. Its `status.code` does not change. This preserves historical data for audit trails. Midaz rejects Ledger deletion in a production environment. ### Via Lerian Console You can view, create, edit, and delete Ledgers on the Ledgers page in the Midaz Module of Lerian Console. [**Learn more in the Managing Ledgers guide.**](/en/products/midaz/console/managing-ledgers-via-console) > [!TIP] > > If you create your first Ledger in Lerian Console, you do it as part of the onboarding flow. To learn more, see the [Midaz Module onboarding](/en/products/midaz/console/midaz-console-onboarding) guide. # Lerian Clients Source: https://docs.lerian.studio/en/products/midaz/lerian-support-portal Open support tickets with Lerian, follow them to resolution, and answer the Lerian team in Lerian Clients. [Lerian Clients](https://clients.lerian.studio) is the portal where your institution's users open support tickets with Lerian. Use it to report an incident, request a service, or ask a question. You follow each ticket in the same place, and you answer the Lerian team there. ## Sign in *** **Step 1** Go to [clients.lerian.studio](https://clients.lerian.studio). **Step 2** Enter your email and select **Continue**. **Step 3** Sign in with your password, or with single sign-on when your institution uses it. If you registered a passkey, the page also offers it. **Step 4** If two-factor authentication is on for your account, enter the 6-digit code from your authenticator app, or a backup code. ![The Lerian Clients sign-in page. The page shows the text "Sign in", the email address the user entered, a password field, a "Forgot password?" link, and a Sign in button.](https://mintcdn.com/lerian-49cb71fc/8b2Qz1z6saOPQouP/images/en/support-portal/sign-in.png?fit=max\&auto=format\&n=8b2Qz1z6saOPQouP\&q=85\&s=33c5ec170d8ed7922a4ab2fc96cecd7c) Figure 1. The password step of the sign-in page Select **Forgot password?** to reset your password. When the page offers **Trust this device**, do not turn it on for a shared or public computer. ## What you see after you sign in *** The sidebar lists only the areas your permissions give you, such as **Tickets**, **Dashboard**, and **Reports**. The portal shows its labels in English unless the user picks another language in the account menu. * **Tickets** lists your institution's tickets and opens each one. **New ticket** is at the top of the sidebar. * **Dashboard** shows ticket and SLA metrics. * **Reports** has ticket reports that you filter, preview, and export. You see the tickets of your institution. You do not see the tickets of other institutions. ## Open a ticket *** **Step 1** Select **New ticket**. **Step 2** Choose the **Type**, the **Environment**, and the **Priority**. **Step 3** Write a **Summary** and a **Description**. **Step 4** Attach files if they help, then select **Create Ticket**. ![The New ticket form in Lerian Clients. The Customer field shows the institution. The Type is Question, the Environment is Production, and the Priority is Medium. The Summary reads "How to set up a fee package for Pix transfers", and the Description explains the question.](https://mintcdn.com/lerian-49cb71fc/8b2Qz1z6saOPQouP/images/en/support-portal/new-ticket.png?fit=max\&auto=format\&n=8b2Qz1z6saOPQouP\&q=85\&s=cf4dc1a8c1f1dc1699446d892cb200f6) Figure 2. The New ticket form, filled in | Field | What to enter | | :- | :- | | **Customer** | Your institution. The form fills it in. | | **Type** | The kind of request. The form lists the types that you can choose, such as an incident, a service request, or a question. | | **Environment** | The environment where the issue happens, for example Production or Homologation. | | **Priority** | The impact on your business. The levels run from Critical, for severe business-critical impact, down to Informational, for no impact. | | **Summary** | A short description of the issue. 80 characters at most. | | **Description** | What happened, what you expected, and any technical context. 4,000 characters at most. The editor supports formatting, links, images, and tables. | | **Attachments** | Optional. Up to 5 files of 25 MB each. Attach logs, screenshots, or request IDs. Do not attach sensitive data. | Some ticket types add more fields to the form. Fill in each field that has an asterisk. > [!TIP] > > The more context you give, the fewer follow-up questions the team needs to ask. For a Critical or High priority, give as much detail as you can in the description. ## Follow a ticket *** **Tickets** lists your institution's tickets with their number, title, status, priority, and SLA. Select a ticket to open it. ![The Tickets page in Lerian Clients. A table lists tickets with number, title, status, priority, and SLA badge. Next to the table, an SLA Health panel counts the clocks by state and the tickets by priority.](https://mintcdn.com/lerian-49cb71fc/8b2Qz1z6saOPQouP/images/en/support-portal/ticket-list.png?fit=max\&auto=format\&n=8b2Qz1z6saOPQouP\&q=85\&s=b2efe7fd00da7e53cae5174cee22ac38) Figure 3. The ticket list, with the SLA badge on each ticket and the SLA health summary on the right Each ticket page shows: * The status. The Lerian team moves a ticket from one status to the next. **Pending on Customer** means the team waits for information from you. * The SLA badge. It shows the time left, or how long ago the SLA was breached. * The priority, the assignee, the requester, and the watchers. * The description, the attachments, and the conversation. ![A ticket page in Lerian Clients. The header shows the ticket number and the status Open. The right side shows the SLA badge, the priority, the assignee, the requester, and the watchers. The conversation lists the replies in order.](https://mintcdn.com/lerian-49cb71fc/8b2Qz1z6saOPQouP/images/en/support-portal/ticket-conversation.png?fit=max\&auto=format\&n=8b2Qz1z6saOPQouP\&q=85\&s=e4a7798936acb1647bab89e46dfec9a1) Figure 4. A ticket page with the SLA badge and the conversation Lerian's internal notes do not appear in it. ## Answer a ticket *** **Step 1** Open the ticket. **Step 2** Write your reply in the **Write a comment** box under the conversation. You can format the text, add links and images, and attach files. **Step 3** Send the comment. You see the **Write a comment** box only when your permissions let you comment and the ticket is not in a final status, such as Done. ## Who can do what *** Permission groups decide what each user does in Lerian Clients. Opening a ticket, commenting on a ticket, seeing the SLA, seeing the history of a ticket, and exporting reports are separate permissions. Creating, editing, blocking, and deleting the users of your institution need two things. The user needs a permission group that grants it, and the account needs the user-management setting. To change your access, ask a user manager of your institution. ## Still need help? *** If you are still unsure where your issue fits, email us at [**suporte@lerian.studio**](mailto:suporte@lerian.studio). We route your message to the right team. # Metadata indexes Source: https://docs.lerian.studio/en/products/midaz/metadata-indexes Create MongoDB metadata indexes on transactions, operations, and routes to speed up queries and filters on custom metadata keys in high-volume Midaz setups. ## Metadata filters on large collections *** Every entity in Midaz supports [metadata](/en/reference/metadata): custom key-value pairs that extend the standard data model. Queries that filter a large collection by a metadata field can become slow without an index. A metadata index is a MongoDB index on a specific metadata key. It turns an expensive collection scan into a fast indexed lookup. Indexes help most in production, where transaction volumes are high and you filter or sort by metadata values. ## How it works *** When you create a metadata index, Midaz builds a MongoDB index on the `metadata.` field of the entity collection. After that, a query that filters by the metadata key can use the index. MongoDB finds the documents directly, without a full collection scan. Indexes are: * **Per-entity**: Each index targets a specific entity type (e.g., `transaction`, `operation`). * **Per-key**: Each index covers a single metadata key. * **Optional uniqueness**: You can require that no two documents share the same value for the indexed metadata key. * **Sparse by default**: The index includes only documents that have the metadata key. This saves storage and speeds up writes. ## Supported entity types *** Midaz supports metadata indexes for these entities: | Entity | Collection | Module | | :- | :- | :- | | `transaction` | Transactions | Transaction | | `operation` | Operations | Transaction | | `operation_route` | Operation Routes | Transaction | | `transaction_route` | Transaction Routes | Transaction | | `organization` | Organizations | Onboarding | | `ledger` | Ledgers | Onboarding | | `account` | Accounts | Onboarding | | `asset` | Assets | Onboarding | | `segment` | Segments | Onboarding | | `portfolio` | Portfolios | Onboarding | | `account_type` | Account Types | Onboarding | ## Creating a metadata index *** Use the [Create a Metadata Index](/en/reference/products/midaz/v2/create-metadata-index) endpoint: ```json POST /v1/settings/metadata-indexes/entities/{entity_name} theme={null} { "metadataKey": "tier", "unique": false, "sparse": true } ``` **Parameters:** | Field | Type | Required | Description | | :- | :- | :- | :- | | `metadataKey` | string | Yes | The metadata key to index. Must start with a letter and contain only alphanumeric characters and underscores. Max 100 characters. | | `unique` | boolean | No | Whether the index enforces uniqueness across documents. Default: `false`. | | `sparse` | boolean | No | Whether the index only includes documents that have the metadata key. Default: `true`. | **Response:** ```json JSON theme={null} { "indexName": "metadata.tier_1", "entityName": "transaction", "metadataKey": "tier", "unique": false, "sparse": true } ``` ## Listing metadata indexes *** Use the [List Metadata Indexes](/en/reference/products/midaz/v2/get-all-metadata-indexes) endpoint. It returns all indexes across all entity types with their usage statistics: ```json GET /v1/settings/metadata-indexes theme={null} [ { "indexName": "metadata.tier_1", "entityName": "transaction", "metadataKey": "tier", "unique": false, "sparse": true, "stats": { "accesses": 1523, "statsSince": "2024-12-01T10:30:00Z" } } ] ``` The `stats.accesses` field shows how many queries used the index since statistics collection started. Use it to find unused indexes that you can safely delete. ## Deleting a metadata index *** Use the [Delete a Metadata Index](/en/reference/products/midaz/v2/delete-metadata-index) endpoint: ``` DELETE /v1/settings/metadata-indexes/entities/{entity_name}/key/{index_key} ``` Set `{index_key}` to the metadata key, such as `tier`, not to the index name. > [!CAUTION] > > Deletion takes effect immediately. It affects query performance for any operation that used the index. Before you delete an index, make sure no critical query depends on it. ## Performance considerations *** **When to create indexes:** * You frequently filter transactions or operations by a specific metadata key (e.g., `tier`, `channel`, `partner_id`). * List queries on a large collection are slow when they filter by metadata. * You need to enforce uniqueness on a metadata field (e.g., external reference IDs). **When NOT to create indexes:** * You rarely query by the metadata key. The index only costs storage and slows writes. * The collection is small enough that full scans are fast. * You want to add an index speculatively, "just in case." **Limits:** Midaz does not enforce its own cap on the number of metadata indexes per entity. MongoDB's per-collection index limit applies instead. Keep the index count deliberate: list the indexes and delete any with low or zero `accesses`. > [!TIP] > > Start with indexes on the metadata keys you query in production. Use the `stats.accesses` field from the list endpoint to make sure queries use each index. Delete the indexes that no query uses. ## Related pages *** * [Metadata](/en/reference/metadata): how metadata works across all Midaz entities. * [Create a Metadata Index](/en/reference/products/midaz/v2/create-metadata-index): API reference. * [List Metadata Indexes](/en/reference/products/midaz/v2/get-all-metadata-indexes): API reference. * [Delete a Metadata Index](/en/reference/products/midaz/v2/delete-metadata-index): API reference. # Midaz for academic records Source: https://docs.lerian.studio/en/products/midaz/midaz-for-academic-record-management Use Midaz to record enrollments, grades, and achievements as immutable Ledger transactions, with automated transcripts and audit-ready histories. Universities manage thousands of student records across many departments. The data sits in separate enrollment systems, grading platforms, and administrative databases. When an audit starts or a student requests a transcript, staff rebuild a complete history by hand. This process is slow and error-prone. Midaz treats each academic activity as a Ledger transaction. It records every enrollment, grade, and achievement immutably, with a full audit trail, the same way it records financial movements. ### Benefits * **Security and integrity**: Every academic record is an immutable transaction. You cannot change its accounts or amounts after you record it. * **Transparency**: Students, advisors, and administrators see a single, consistent view of the complete academic record. * **Efficiency**: Transcript generation, GPA calculations, and audit preparation become automated queries instead of manual processes. ## What changes with Midaz *** | Without Midaz | With Midaz | | :- | :- | | Student records spread across enrollment, grading, and admin systems | Single ledger tracks all academic activities as immutable transactions | | Transcript generation requires manual cross-referencing | Query the operations of a student's accounts for a complete academic history | | Grade disputes involve digging through logs and email chains | Every grade assignment is a timestamped, immutable transaction with full audit trail | | GPA calculations done manually or in disconnected spreadsheets | Balance queries on grade accounts return grade totals for GPA calculations | | Audit preparation takes weeks of data gathering | Query transactions for any date range through the API | ## Using Midaz *** * **Organization & Ledger:** The university registers as an Organization in Midaz. It creates a Ledger to track all academic activities as transactions. * **Assets:** Create an Asset for each academic metric, such as `ENROLLMENT`, `GRADE`, `ATTENDANCE`, and `ACHIEVEMENT`. Asset codes use uppercase letters only. * **Student Portfolios:** For each student, create a Portfolio. The Portfolio is the academic record and holds all relevant academic metrics. * **Accounts for academic metrics:** Create accounts for the academic metrics inside each student's Portfolio. Each account holds one Asset. Examples include: * **Course enrollments Account**: Records the courses the student enrolls in. * **Grades Account**: Tracks the grades the student receives. * **Attendance Account**: Monitors class attendance. * **Achievements Account**: Records extracurricular achievements and recognitions. * **Transactions**: Use transactions to update accounts based on academic activities. Record the course or activity in each transaction's metadata: * **Course enrollment**: When a student enrolls in a course, create a transaction. The transaction moves one `ENROLLMENT` unit from `@external/ENROLLMENT` to the student's "Course Enrollments" account. * **Grade assignment**: When an instructor assigns a grade, create a transaction. The transaction moves the grade, in `GRADE`, from `@external/GRADE` to the student's grade account. * **Attendance marking**: To mark attendance, move `ATTENDANCE` from `@external/ATTENDANCE` to the student's "Attendance" account. * **Achievements**: Similarly, add achievements to the "Achievements" account via transactions. * **Reports**: Query the ledger to build a full academic record for each student, across enrollments, grades, attendance, and achievements. These queries support academic counseling and transcript generation. * For example, retrieve all operations of the Grades Account. Use the available balance to calculate the student's GPA. # Midaz for multi-account customers Source: https://docs.lerian.studio/en/products/midaz/midaz-for-multi-account-customers Model multiple Midaz accounts under a single customer, with segregated balances, ledgers, statements, and external identifiers per account. A single customer rarely has a single balance. The same person can hold a main account, a benefit account, a blocked account, a product sub-account, or a promotional balance. Each balance has its own rules, its own statement, and its own reconciliation needs. The common shortcut treats these as labels on one account and sorts them out in application code. That works until balances, ledgers, statements, or operational rules must diverge. At that point, a single account can no longer show where the money is. This page shows the reference architecture for **one customer with many Midaz accounts**. It maps each part of the model to a native platform entity. Then it walks through an example: three accounts for the same customer document. ## Each balance as its own account *** For **product and operations teams**, each balance becomes its own account. The Ledger then enforces segregation rules, such as a blocked outflow or a benefit-only spend. The rule lives in the Ledger, not in application logic. Each account carries its own statement and reconciliation trail. For **engineering teams**, each external address resolves to a specific account before Midaz posts a transaction. Core banking numbers and payment-rail identifiers each point to one balance. You never guess which balance an incoming event belongs to. There is no separate balance store to keep in sync with the Ledger. | One account with labels | Many accounts per customer | | - | - | | Balance "types" live in metadata or app code | Each balance is its own Account with its own ledger and statement | | Blocking or restricting funds requires custom logic | Account Type and route rules enforce restrictions at the Ledger | | Statements must be filtered and reassembled per balance | Each account produces a clean, independent statement | | External identifiers all point to the same balance | Each external identifier resolves to a specific account | | Reconciliation mixes unrelated movements | Reconciliation is separated by account by design | ## The reference architecture *** The model is **one owner, N accounts, N external identifiers**: * **One owner**: the customer, identified by a document (CPF, CNPJ, tax ID). The owner represents *who* holds the relationship. It does not carry a balance and does not decide transaction routing. * **N accounts**: each account is a self-contained accounting position, with its own balance, ledger, statement, and rules. * **N external identifiers**: the addresses other systems (a core banking platform, a payment rail) use to reach a specific account. Each identifier resolves to exactly one account. A middleware layer keeps the map between external identifiers and accounts. It resolves each identifier to the correct account *before* the call to Midaz. Midaz remains the source of truth for accounts, balances, and entries. ![One customer, many accounts: reference architecture](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/flowchart-multiaccounts.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=4bc292432ee995aeabaa2061bfee73ff) Reference architecture: one customer, many accounts. > [!NOTE] > > When balance, ledger, statement, or operational rule differs by destination, point each identifier at a distinct account. Do not treat an external identifier as a nickname for one shared balance. ## How Midaz maps the model *** Every part of this architecture maps to a native Midaz entity. You do not build a separate balance store or invent an accounting layer. | Concept | Midaz entity | What it does | | - | - | - | | The owner (customer) | [**Holder**](/en/products/midaz/crm/holders) | Identity behind the accounts (`NATURAL_PERSON` or `LEGAL_PERSON`), keyed by `document`. Owns each account through its `holderId`. Holds no balance. | | Each balance position | [**Account**](/en/products/midaz/accounts) | Source of truth for balance, entries, and statement. | | The nature of each balance | [**Account Type**](/en/products/midaz/account-types) | Classifies an account (main, benefit, blocked) and enables route validation. | | All accounts of one customer | [**Portfolio**](/en/products/midaz/portfolios) | Groups a customer's accounts to view the total relationship. | | External address → account | [**Account alias**](/en/products/midaz/accounts#account-aliases) + [**`entityId`**](/en/products/midaz/accounts#entity-id-external-system-reference) | The alias is how transactions address an account; `entityId` links it to an external system's identifier. | | Banking and regulatory context | [**Instrument (CRM)**](/en/products/midaz/crm/crm-getting-started) | Attaches branch, account number, and regulatory fields. Links a Holder to a specific account. | > [!TIP] > > Much of what an external "alias registry" would do is already native. The account **alias** is the in-Ledger address. **`entityId`** stores your external system's identifier. The middleware's job is narrow: translate an external rail identifier into the right account alias, then post. ## Prerequisites *** This example assumes a running Midaz environment with the following in place: | Requirement | Details | | - | - | | **Midaz** (v4.x.x+) | Core Ledger with an Organization and Ledger already created | | **A registered asset** | `BRL` registered as the operating asset in the Ledger | | **Account Type validation** | Enabled per-Ledger so new accounts must use a registered type (see Step 1) | | **CRM** | Part of the ledger binary. Use it to attach identity, banking, and regulatory context | ## Building three accounts for one customer *** The customer with document `12345678900` needs three accounts. The **main** account is free for ordinary movement. The **benefit** account follows product rules. The **blocked** account accepts inflows but restricts outflows. **1. Enable Account Type validation** Turn on validation so new accounts must declare a registered type. ```json theme={null} PATCH /v2/organizations/{org_id}/ledgers/{ledger_id}/settings { "accounting": { "validateAccountType": true } } ``` Settings take effect immediately. You do not need to redeploy. **2. Register the Account Types** Create one Account Type per balance nature. The `keyValue` is what each account's `type` field must match. ```json theme={null} POST /v2/organizations/{org_id}/ledgers/{ledger_id}/account-types { "name": "Main Account", "description": "Ordinary account, free for regular movement", "keyValue": "main_account" } ``` Repeat for `benefit_account` (movement under product rules) and `restricted_account`. The `restricted_account` is the **blocked** account. The type alone restricts nothing. With route validation on, transaction routes can condition its outflows. To block them, set `allowSending` to `false` on its balance. **3. Register the customer as a Holder** Create one Holder for the customer. The same Holder owns all three accounts and keeps identity in one place. > [!NOTE] > > In Midaz v4, CRM is part of the ledger binary, so it needs no separate service or port. The organization ID travels in the URL path. See [Getting started with CRM](/en/products/midaz/crm/crm-getting-started) for the full schema. ```bash theme={null} curl -X POST http://localhost:3002/v2/organizations/{org_id}/holders \ -H "Content-Type: application/json" \ -d '{ "type": "NATURAL_PERSON", "name": "Jane Smith", "document": "12345678900", "contact": { "primaryEmail": "jane.smith@example.com" } }' ``` Save the returned `id`. It is the `holderId` for the next steps. **4. Create the three accounts** Each account links to the `BRL` asset and declares its `type`. It carries an `alias` (its in-Ledger address) and an `entityId` (its identifier in your external system). The `holderId` makes the Holder the owner of the account. You cannot change the owner later. ```json theme={null} POST /v2/organizations/{org_id}/ledgers/{ledger_id}/accounts { "name": "Main account - 12345678900", "assetCode": "BRL", "alias": "@cust_12345678900_main", "entityId": "0001/12345-1", "holderId": "", "type": "main_account" } ``` Create the benefit account with `alias` `@cust_12345678900_benefit`, `entityId` `0001/88888-2`, and `type` `benefit_account`. Create the blocked account with `alias` `@cust_12345678900_blocked`, `entityId` `0002/77777-0`, and `type` `restricted_account`. Use the same `holderId` for both. > [!TIP] > > The `entityId` is where you store the external address that other systems use to reach this account. It is your map between Midaz and your source system. **5. Link each account to the Holder** Create one Instrument per ledger account to attach banking and regulatory context. The Instrument remains inside the unified Ledger binary while keeping customer-facing details outside the transactional account and balance model. ```bash theme={null} curl -X POST http://localhost:3002/v2/organizations/{org_id}/holders/{holder_id}/instruments \ -H "Content-Type: application/json" \ -d '{ "ledgerId": "", "accountId": "", "bankingDetails": { "branch": "0001", "account": "12345", "type": "CACC", "countryCode": "BR" }, "metadata": { "purpose": "main" } }' ``` The main account's `entityId` (`0001/12345-1`) decomposes into the `branch` (`0001`) and `account` (`12345`) you record here. That external address now resolves to one specific account. Repeat for the benefit and blocked accounts, and point `accountId` at each one. You now have one customer, three accounts, and three distinct external addresses. Each account keeps its own balance, statement, and rules under a single Holder. | Owner | External identifier | Midaz account | Use | Treatment | | - | - | - | - | - | | `12345678900` | `0001/12345-1` | `@cust_..._main` | Main account | Free for ordinary movement | | `12345678900` | `0001/88888-2` | `@cust_..._benefit` | Benefit account | Movement governed by product rules | | `12345678900` | `0002/77777-0` | `@cust_..._blocked` | Court-ordered / blocked | Inflow allowed, outflow conditioned or blocked | ## The transaction boundary *** When an external event arrives, the resolution happens *before* the call to Midaz. Each layer stays in its lane, and that preserves accounting clarity. **1. External event** A transaction, query, or settlement arrives with an external identifier. **2. Middleware resolves the identifier** The middleware looks up the external identifier and resolves it to the correct Midaz account alias. It also applies status validation (active, blocked, closed). **3. Midaz posts to the right account** Midaz records the entry against the resolved account and preserves balance and ledger. Statement and reconciliation stay separate by account. | Layer | Responsibility | Should not do | | - | - | - | | **CRM / registration** | Hold the commercial and identity view of the customer, including the link between document and relationship. | Transaction routing, destination decisions, or settlement rules. | | **Middleware** | Resolve external identifiers to a Midaz account before the transaction, and apply status validation. | Invent balances, duplicate accounting, or depend on the CRM in real time for routing. | | **Midaz** | Record accounts, balances, entries, ledgers, and statements as the financial source of truth. | Know external-rail details beyond the identifiers needed for integration. | > [!TIP] > > An identifier for a blocked or closed account must fail validation before the call to Midaz. Routing decisions belong in the middleware. The Ledger stays the source of truth for balances and entries. ## Outcomes of many accounts per customer *** * **Real segregation**: each balance has its own ledger and statement. You cannot spend a blocked balance through the main account by accident. * **Unambiguous routing**: every external event has a single, well-defined destination account. * **Centralized identity**: one Holder owns many accounts. Identity and contact data live in one place while balances stay separate. * **Native**: accounts, types, aliases, and `entityId` are platform primitives, so there's no parallel balance store to reconcile against the Ledger. ## What you need to get started *** | Requirement | Details | | - | - | | **Midaz** (v4.x.x+) | Organization, Ledger, and a registered asset | | **Account Type validation** | Enabled per-Ledger via the [Ledger Settings API](/en/products/midaz/ledgers#ledger-settings) | | **Account Types** | One per balance nature (main, benefit, blocked, …) | | **Accounts** | One per balance, each with an `alias` and an `entityId` | | **CRM** | A Holder per customer, plus an optional Instrument per ledger account | ## Next steps *** > [card] [Accounts](/en/products/midaz/accounts) > > The core financial unit: aliases, `entityId`, and external accounts. > [card] [Account Types](/en/products/midaz/account-types) > > Classify accounts and enforce their nature with route validation. > [card] [Portfolios](/en/products/midaz/portfolios) > > Group a customer's accounts to view the total relationship. > [card] [CRM: Holders & Instruments](/en/products/midaz/crm/holders) > > Centralize identity and attach banking and regulatory context. # Midaz for supply chains Source: https://docs.lerian.studio/en/products/midaz/midaz-for-supply-chain-management Use Midaz as a ledger for supply chain management, recording every raw material, production, and shipping movement as an immutable, auditable transaction. Manufacturing companies manage complex material flows. Raw materials arrive from many suppliers, move through production stages, become finished goods, and ship to customers. A quality issue or a regulatory audit asks where a material came from and where it went. Today that answer takes days of cross-referencing spreadsheets and ERP exports. Midaz records every material movement as an immutable ledger transaction. From receiving to production to shipping, you get a complete and auditable history of your supply chain. ### Benefits * **Transparency and traceability**: An immutable audit trail documents every step. Recall investigations and compliance audits become straightforward. * **Efficiency**: Real-time balance queries show inventory levels and production stages. You avoid manual stock checks and planning delays. ## What changes with Midaz *** | Without Midaz | With Midaz | | :- | :- | | Material tracking spread across ERP modules, spreadsheets, and emails | Every material movement is a ledger transaction with full audit trail | | Recall investigations take days of cross-referencing multiple systems | Query the ledger for the complete journey of any material | | Inventory counts done manually or through periodic reconciliation | Real-time balance queries show current stock at any stage (raw, in-production, finished) | | Supplier disputes lack authoritative records | Immutable transactions record every delivery and movement | | Regulatory audits require weeks of data preparation | Query transactions for any date range through the API | ## Using Midaz *** * **Assets**: Set up each supply chain item as an Asset. Asset codes use uppercase letters only, such as `STEEL` or `WIDGET`. Assets cover everything from raw materials to final products. * **Portfolios**: Create a portfolio for each warehouse. A portfolio groups the accounts that track material and goods flow. * **Accounts**: Within each portfolio, create an account for each item at each supply chain stage. Each account holds one Asset. For example: * **Raw materials account**: Tracks raw materials held in the warehouse. * **In-production account**: Monitors materials in the production process. * **Finished goods account**: Records completed products ready for distribution. * **Shipment account**: Tracks items in transit to customers or other warehouses. * **Transactions**: Use a transaction to update accounts as materials move through each stage. For example: * **Receiving materials**: When materials arrive, a transaction moves the amount from the item's external account, such as `@external/STEEL`, to the warehouse's Raw Materials account. Record the supplier in the transaction metadata. * **Production**: During production, a transaction moves the amount from the Raw Materials account to the In-Production account. * **Production completion**: When production finishes, one transaction per consumed material moves it from its In-Production account to the material's external account. Another transaction moves the finished products from the product's external account to the Finished Goods account. * **Shipping**: When goods ship, a transaction moves the amount from the Finished Goods account to the Shipment account. * **Reports**: Query Midaz for current inventory levels, production output, and shipment status. Use the data to plan stock, production schedules, and logistics. * **Compliance and audits**: The immutable Midaz ledger keeps supply chain records secure and audit-ready. # Getting started with Midaz Source: https://docs.lerian.studio/en/products/midaz/midaz-getting-started Run your first Midaz workflow: check your ledger, create your first Organization, Ledger, and Accounts, and process a first transaction. In this guide, you check a running Midaz ledger. You then run the core workflow behind any financial application on the platform. You create an organization, a ledger, and accounts, and then process your first transaction. By the end, you have a running ledger ready for your use case. This can be payments, lending, marketplace settlement, or internal treasury. ## Prerequisites *** Before you begin, install Midaz. Midaz ships as public container images on Docker Hub. See [Installing Midaz](/en/products/midaz/midaz-setup). This guide calls the ledger at `http://localhost:3002`, the default `SERVER_ADDRESS` (`:3002`). If your ledger runs at another address, use that address instead. ## Step 1: Check that Midaz responds *** ```bash Terminal theme={null} curl http://localhost:3002/health ``` You should receive a `200 OK` response. ## Step 2: Create an organization *** An organization represents the business entity behind the financial operation: your company, a client, or a regulated institution. In production, it maps to the legal entity that holds your ledgers, accounts, and transactions. > [!TIP] > > For the complete endpoint specification, see [Create an Organization](/en/reference/products/midaz/v2/create-organization). ```bash Terminal theme={null} curl -X POST http://localhost:3002/v2/organizations \ -H "Content-Type: application/json" \ -d '{ "legalName": "Acme Corp", "legalDocument": "12345678000100", "status": { "code": "ACTIVE" }, "address": { "country": "BR" } }' ``` > [!NOTE] > > Save the `id` returned in the response. You use it in the next steps as `{organization_id}`. ## Step 3: Create a ledger *** A ledger is an isolated book of records within an organization. You can create separate ledgers for different financial domains, such as payments, fee collection, or settlement. Each ledger has its own accounts and transaction history. > [!TIP] > > For the complete endpoint specification, see [Create a Ledger](/en/reference/products/midaz/v2/create-ledger). ```bash Terminal theme={null} curl -X POST http://localhost:3002/v2/organizations/{organization_id}/ledgers \ -H "Content-Type: application/json" \ -d '{ "name": "Primary Ledger", "status": { "code": "ACTIVE" } }' ``` Save the returned `id` as `{ledger_id}`. ## Step 4: Create an asset *** An asset defines the unit of value tracked in the ledger. This can be a fiat currency like BRL or USD. It can also be loyalty points, crypto tokens, securities, or any custom unit your business tracks. You must create at least one asset before you create accounts. > [!TIP] > > For the complete endpoint specification, see [Create an Asset](/en/reference/products/midaz/v2/create-asset). ```bash Terminal theme={null} curl -X POST http://localhost:3002/v2/organizations/{organization_id}/ledgers/{ledger_id}/assets \ -H "Content-Type: application/json" \ -d '{ "name": "Brazilian Real", "type": "currency", "code": "BRL", "status": { "code": "ACTIVE" } }' ``` ## Step 5: Create accounts *** Accounts represent the participants or buckets in your financial flow: a customer wallet, a revenue pool, a merchant account, or an internal reserve. Each account links to a single asset and follows double-entry accounting rules. You need at least two accounts to process a transaction: one to debit (source) and one to credit (destination). > [!TIP] > > For the complete endpoint specification, see [Create an Account](/en/reference/products/midaz/v2/create-account). Midaz created the source account `@external/BRL` when you created the BRL asset. Create a destination account: ```bash Terminal theme={null} curl -X POST http://localhost:3002/v2/organizations/{organization_id}/ledgers/{ledger_id}/accounts \ -H "Content-Type: application/json" \ -d '{ "name": "Customer Account", "assetCode": "BRL", "type": "deposit", "status": { "code": "ACTIVE" }, "alias": "@customer-001" }' ``` ## Step 6: Process your first transaction *** A transaction moves value between accounts with full traceability. Midaz records every transaction as a balanced operation. It debits the source and credits the destination, so your books stay consistent by design. > [!TIP] > > For the complete endpoint specification, see [Create a Transaction using the v2 direct model](/en/reference/products/midaz/v2/create-transaction-direct). ```bash Terminal theme={null} curl -X POST http://localhost:3002/v2/transactions/direct \ -H "Content-Type: application/json" \ -d '{ "description": "First transaction", "asset": "BRL", "amount": "1000", "debits": [ { "alias": "@external/BRL", "organizationId": "{organization_id}", "ledgerId": "{ledger_id}", "amount": "1000" } ], "credits": [ { "alias": "@customer-001", "organizationId": "{organization_id}", "ledgerId": "{ledger_id}", "amount": "1000" } ] }' ``` > [!NOTE] > > This transaction sends `"1000"` from `@external/BRL` to `@customer-001`. Midaz stores monetary values as decimal strings and does not apply an asset-specific scale. > > Your integration defines the display and rounding rules for BRL amounts. Do not parse monetary values as binary floating point. ## Step 7: Verify the balance *** Check the destination account balance to confirm the transaction. > [!TIP] > > For the complete endpoint specification, see [Retrieve a Balance by Account Alias](/en/reference/products/midaz/v2/get-balances-by-alias). ```bash Terminal theme={null} curl http://localhost:3002/v2/organizations/{organization_id}/ledgers/{ledger_id}/accounts/alias/@customer-001/balances ``` The returned balance should reflect the credited amount. At this point, you have a working ledger that processes real transactions. ## Explore the API *** Midaz can serve its OpenAPI 3.1 spec and interactive API documentation. The docs surface is off by default. To enable it, set `OPENAPI_DOCS_ENABLED=true` on the ledger and restart it. Then access: * **API docs**: `http://localhost:3002/docs` * **OpenAPI spec**: `http://localhost:3002/openapi.json` (or `/openapi.yaml`) ## Next steps *** > [!TIP] > > New to Midaz? Start with [Midaz entities](/en/products/midaz/core-entities) to understand organizations, ledgers, accounts, and transactions. > [card] [Creating transactions](/en/products/midaz/transactions-overview) > > Learn the different ways to create transactions, including JSON, inflow, and outflow, and when to use each. > [card] [Deploy to production](https://github.com/LerianStudio/helm/blob/main/charts/midaz/README.md#install-midaz-helm-chart) > > Deploy Midaz to Kubernetes using the official Helm chart. > [card] [Setting up CRM](/en/products/midaz/crm/crm-getting-started) > > Manage holders and alias accounts to connect real-world identities to your Midaz accounts. > [card] [Extend with plugins](/en/products/about-plugins) > > Add Pix and other capabilities to your Midaz deployment. # Midaz in a global portfolio Source: https://docs.lerian.studio/en/products/midaz/midaz-in-a-global-portfolio Model multi-currency customer relationships in Midaz: group BRL, USD, and EUR Accounts under a single Portfolio for a unified global banking view. With Midaz, you can build a global account structure like the ones major banks offer. Clients hold accounts in multiple currencies, such as BRL, USD, and EUR. You manage every currency account under a single client profile. ## What changes with Midaz *** | Without Midaz | With Midaz | | :- | :- | | Multi-currency accounts require separate systems or complex workarounds | Each currency is an Asset (A unit of value tracked in the ledger: traditional currencies (BRL, USD), digital currencies (BTC), or custom units like loyalty points. Every account is linked to exactly one asset.); accounts in different currencies grouped under one Portfolio (A grouping of accounts belonging to the same account holder, business unit, or purpose. It ties together checking, savings, and investment accounts for a unified view.) | | No unified customer view across currencies | A single portfolio shows all of a client's accounts (BRL, USD, EUR) in one place | | Currency-specific reporting built manually per system | Filter the account list by portfolio through the API | | Adding a new currency means provisioning new infrastructure | Create a new Asset and an account. The ledger handles the rest | ## Using Midaz *** * **Organization and Ledger:** ABC Bank registers as an Organization in Midaz. It then creates a Ledger to track all customer transactions. * **Assets:** The bank defines an Asset for each currency it supports. * **Customer Portfolios:** Each customer has a Portfolio. It groups their checking, savings, and credit accounts in one place. * **Customer Accounts:** Create an Account for each currency the customer uses. Group these accounts under the customer's Portfolio. # Midaz in banking Source: https://docs.lerian.studio/en/products/midaz/midaz-in-banking Model retail, corporate, and personalized banking in Midaz with Portfolios, Segments, and dedicated settlement Accounts. Midaz supports three banking models: **retail banking**, **corporate banking**, and **personalized banking services**. It uses portfolios (A grouping of accounts belonging to the same account holder, business unit, or purpose. It ties together checking, savings, and investment accounts for a unified view.) and segments (A classification applied to accounts that share characteristics, like account holder tiers (VIP, Student) or regional divisions. Rules and pricing can differ by segment.) to model each one. ## What changes with Midaz *** | Without Midaz | With Midaz | | :- | :- | | Customer accounts scattered across legacy systems with no unified view | Single ledger (The core financial book that records all transactions, balances, and operations for an organization. It is the single source of truth for a business unit's finances.) with portfolios grouping all accounts per customer | | Adding new products (savings, credit) requires core system changes | New account types and segments configured via API, with no code changes to the ledger | | Fee and interest tracking mixed with operational accounts | Dedicated internal accounts for fee income, interest expense, and settlement (The process of finalizing a financial transaction by transferring actual funds between institutions. Settlement accounts act as clearing points where money is held temporarily before reaching its final destination.) | | Segmentation (VIP, Student) enforced manually per product | Segments classify accounts, and the Fees Engine waives fees for a whole segment | | Corporate hierarchies require custom workarounds | Native child accounts (A sub-account under a parent account, used for budgeting or organizational purposes. Each tracks its own balance.) and multi-portfolio support for subsidiaries | ## Adding products without changing the core ledger *** Banks add products without changing core ledger structures. You configure new account types and segments through the API. ## Retail banking for individual customers *** A retail bank runs on a single organization and a primary ledger. Each customer maps to a portfolio. ### Using Midaz * **Organization & Ledger:** ABC Bank registers as an organization. It creates a "Retail Banking Ledger" for all customer transactions. * **Assets (A unit of value tracked in the ledger: traditional currencies (BRL, USD), digital currencies (BTC), or custom units like loyalty points. Every account is linked to exactly one asset.):** The bank defines an asset for every currency it operates. This gives multi-currency support for domestic and international accounts. * **Customer portfolios:** Each customer has a portfolio. It holds their checking, savings, and credit accounts. * **Transactions:** Midaz records deposits, transfers, and payments with full traceability. * **Internal accounts:** Fee and interest accounts track the bank's revenue and expenses. * **Segments for personalization:** You classify accounts into service tiers, such as Standard or Gold. The Fees Engine can waive fees for a tier. * **Child accounts (A sub-account under a parent account, used for budgeting or organizational purposes. Each tracks its own balance.) for budgeting:** Customers create sub-accounts under their savings account for better money management. #### Example: ATM withdrawal John Doe withdraws \$100 from an ATM: **1. Debit** \$100 from John’s checking account. **2. Credit** \$100 to an "ATM Cash Dispensed" internal account. **3. Fee** Midaz debits \$3 from John’s account and credits the Fee Income account. ## Corporate banking for business and enterprise customers *** Corporate banking needs a more detailed structure. It often uses separate ledgers or segments to keep it apart from retail banking. ### Using Midaz * **Dedicated Ledger:** ABC Bank creates a "Corporate Banking Ledger" for business accounts. * **Portfolios for enterprises:** Each corporate client, such as ACME Corp, gets a portfolio with accounts for operations, payroll, and taxes. * **Hierarchical accounts:** Child accounts let a business split funds across departments under one parent account. * **Bulk transactions:** Midaz supports large operations, such as payroll with many simultaneous debits and credits. * **Segments & Products:** You classify companies as SME or Large Enterprise to offer tailored services. * **Multi-entity clients:** You give each subsidiary its own portfolio under the same organization. #### Example: loan disbursement & supplier payments ACME Corp receives a \$1,000,000 loan: **1. Credit** \$1,000,000 to ACME’s loan account. **2. Debit** \$1,000,000 from the bank’s Loans Receivable account. **3. ACME uses funds** * \$100,000 payment to a supplier at ABC Bank (internal transfer). * \$50,000 payment to an external supplier (external transfer recorded in the clearing account). ## Portfolios and Segments for personalized services *** Banks offer custom financial products. Midaz supports this through portfolios and segments. ### Customization strategies * **Youth & student accounts:** You assign these accounts to a "Student" segment. The Fees Engine waives their fees. * **Premium banking:** You group "Diamond" accounts in a premium segment. You apply fee rules to the whole segment. * **Co-branded & special products:** You define loyalty points as an asset and track them in a customer's account. * **Unified account views:** An application filters the account list by portfolio. * **Cross-portfolio operations:** A customer with a personal and a business portfolio transfers funds between them. The accounts stay separate in each portfolio. #### Example: student account perks **Step 1** A new customer signs up as a student. **Step 2** You assign their account to the "Student" segment. **Step 3** The Fees Engine waives their monthly fees. **Step 4** When the customer reaches a set age, you move the account to a different segment. # Midaz production best practices Source: https://docs.lerian.studio/en/products/midaz/midaz-production-best-practices Set up Midaz for production with multi-AZ deployment, autoscaling, managed services, and the Kubernetes resilience patterns Lerian recommends. Midaz runs in production at high volume. This guide gives you the deployment, high-availability, and observability patterns Lerian recommends. Follow them to keep downtime low and protect your data. ## Best-fit setup *** Start a production deployment with these choices: * Deploy across multiple availability zones. * Run at least 3 worker nodes with autoscaling. * Separate application and database workloads. * Use managed services such as RDS and MongoDB Atlas. * Apply Kubernetes patterns for resilience, security, and observability. * Automate backups and alerting from day one. ## Infrastructure planning *** ### Cluster architecture Plan the cluster for resilience and performance: * Deploy across multiple availability zones. * Run at least 3 worker nodes for high availability. * Enable node autoscaling to absorb workload spikes. * Separate application and database workloads when possible. ### Resource sizing * Match node sizes to the expected workload. * Give critical services enough resources first. * Apply resource quotas to prevent contention. * Monitor usage and tune the sizing over time. ### Storage * Use SSD-backed storage for all database components. * Define a storage class for each cloud provider. * Provision volumes with headroom for growth. * Use replicated or durable storage for critical data. ## Database architecture and high availability *** Midaz uses CQRS (Command Query Responsibility Segregation) to separate reads from writes. This design lets you scale each path on its own. ### PostgreSQL * Use a dedicated primary for writes and replicas for reads. * Enable synchronous replication for critical data. * Configure automatic failover with Patroni or AWS RDS. * Monitor replication lag and consistency. * Prefer managed services such as AWS RDS or GCP Cloud SQL. ### Redis / Valkey * Deploy one primary with replicas across multiple zones. Midaz does not support Redis Cluster mode for transactions. * Enable automatic failover with a Sentinel topology via `REDIS_MASTER_NAME`, or with a managed service with cluster mode disabled. Set `REDIS_HOST` to one address, or set `REDIS_MASTER_NAME` for Sentinel. Without `REDIS_MASTER_NAME`, a comma-separated `REDIS_HOST` selects Cluster mode. * Run Valkey with `maxmemory-policy` set to `noeviction` and `appendfsync` set to `always`. Midaz requires both settings. A managed service must accept both settings. ### MongoDB * Use replica sets with members across zones. * Monitor role transitions and lag. * Schedule regular backups. * Use managed services such as MongoDB Atlas or AWS DocumentDB. ## Messaging infrastructure *** Midaz runs two messaging surfaces. Kafka-compatible streaming and asynchronous transaction processing are off by default. `RABBITMQ_OVERDRAFT_EVENTS_ENABLED=false` turns off the overdraft events on both surfaces. * **RabbitMQ** carries the optional write-behind pipeline that stores confirmed transactions in PostgreSQL and MongoDB (`RABBITMQ_TRANSACTION_BALANCE_OPERATION_*`, enabled with `RABBITMQ_TRANSACTION_ASYNC=true`), the overdraft events, and the audit messages when you set `AUDIT_LOG_ENABLED` to `true`. Use a managed RabbitMQ service such as AWS MQ or CloudAMQP in production. * **RedPanda** is the event backbone. Set `STREAMING_ENABLED=true`, `STREAMING_BROKERS`, and `STREAMING_CLOUDEVENTS_SOURCE` set to exactly `ledger` for ledger, CRM, and Fees, or `tracer` for Tracer. Facts publish to `lerian.streaming.ledger` or `lerian.streaming.tracer`. Route by CloudEvents headers. Transaction-lifecycle facts and the `balance.overdraft_*` events publish through this surface. Optional PostgreSQL read replicas (`DB_ONBOARDING_REPLICA_*` and `DB_TRANSACTION_REPLICA_*`) serve reads. Transactional reads go to the primary by default. ## High availability strategies *** ### Service redundancy * Deploy multiple replicas for every service. * Use anti-affinity rules to spread services across zones. * Apply Pod Disruption Budgets to limit downtime during updates. ### Load balancing * Use ingress controllers with health checks. * Avoid session affinity unless a service requires it. * Enable connection draining for smooth rollouts. ## Security considerations *** ### Network security * Apply Kubernetes network policies to control traffic. * Give each service account minimal permissions. * Secure external access with TLS. * Restrict admin interfaces with IP allowlists. ### Secret management * Use Kubernetes Secrets for credentials and tokens. * Rotate secrets on a regular schedule. * Never hardcode secrets in containers or config files. * Use an external secret manager for a stronger posture. ## Monitoring and observability *** ### Metrics * Monitor the key application and infrastructure KPIs. * Set alert thresholds that lead to action. * Use dashboards for real-time visibility. ### Logging * Centralize logs across all services. * Use a structured format for easier filtering. * Apply log retention and rotation policies. * Define log-based alerts for critical events. ### Tracing * Enable distributed tracing across services. * Sample traces to balance performance and cost. * Correlate traces with logs and metrics for full visibility. ### Alerting * Create clear, reliable alerts. * Tune thresholds to reduce noise. * Route each alert through the right channel. * Keep runbooks for recurring issues. ## Backup strategy *** * Automate regular backups for critical systems. * Store backups in more than one location or region. * Test the restore procedure on a regular schedule. * Keep the backup documentation current and accessible. ## Idempotency *** Protect critical operations against duplicate processing in production: * Send an idempotency key on every transaction create request with the `X-Idempotency` header. * Use explicit, deterministic keys tied to your business IDs (order IDs, payment references), not auto-generated keys. * Read the `X-Idempotency-Replayed` response header to tell a new transaction from a cached replay. * Set the `X-TTL` header in seconds to match your retry window. The default is 300. Use a shorter value for synchronous flows and a longer one for asynchronous flows. > [!NOTE] > > Several Lerian products support idempotency through their own header conventions. For implementation details and a comparison across products, see [Retries and idempotency](/en/reference/retries-idempotency). ## Aligning infrastructure to the Midaz architecture *** Align your infrastructure to the Midaz architecture and you gain: * Clean read/write separation with CQRS. * Compatibility with managed cloud services. * A clear path to observability, failover, and secure operations. Review your setup on a regular schedule. ## What’s next? *** * Read the [Midaz deployment guide](/en/products/midaz/deployment). * [Contact Lerian support](/en/products/midaz/lerian-support-portal) for tailored support. # Midaz SDK for Go Source: https://docs.lerian.studio/en/products/midaz/midaz-sdk-go Build Go applications on top of Midaz with the official Go SDK: typed pagination, structured errors, retries, and OpenTelemetry observability. The **Midaz SDK for Go** is the Go client for the Midaz ledger and Tracer APIs. It gives you typed access to the services that the Services table lists (Organizations, Ledgers, Accounts, Transactions, and more) with one surface for authentication, pagination, errors, retries, logging, and observability. ## Getting started *** ### Step 1 – Install Go Install Go before you use the SDK. The SDK declares **Go 1.26** in `go.mod`. Its public API uses `iter.Seq2` and `log/slog`. **Step 1** Go to the [official Go website](https://golang.org/dl/). **Step 2** Download the installer for your OS (Windows, macOS, or Linux). **Step 3** [**Follow the installation instructions.**](https://go.dev/doc/install) ### Step 2 – Create or use an existing Go project **Create a Go project:** To create a Go project, use the following command: ```bash Bash theme={null} mkdir my-midaz-app cd my-midaz-app go mod init my-midaz-app ``` **Use an existing Go project:** If you're working in an existing project, make sure there's a `go.mod` file in the root. If not, run the following command to create one: ```bash Bash theme={null} go mod init your-module-name ``` ### Step 3 – Add the Midaz SDK Inside your project directory, run the following command to add the SDK to your `go.mod` and `go.sum` files: > [!WARNING] > > **The module path requires the `/v6` suffix.** If you omit it, Go resolves an old v1 release. Import `github.com/LerianStudio/midaz-sdk-golang/v6`. ```bash Bash theme={null} go get github.com/LerianStudio/midaz-sdk-golang/v6 ``` > [!TIP] > > In VS Code or GoLand, your IDE may automatically run `go get` when you import a new package. ### Step 4 – Import the SDK Create or open a `main.go` file and add the following content. The example builds a client against your local Midaz stack with anonymous authentication, lists organizations, then creates a new one. > [!NOTE] > > The example below targets a local Midaz stack with auth disabled. If you don't have one running yet, see [Getting started with Midaz](/en/start-here/getting-started) to spin one up before running the snippet. ```go Go expandable theme={null} package main import ( "context" "fmt" "log" midaz "github.com/LerianStudio/midaz-sdk-golang/v6" "github.com/LerianStudio/midaz-sdk-golang/v6/models" ) func main() { // Build a client. The SDK requires exactly one auth source: use // midaz.WithAnonymous() for a local stack, or midaz.WithAccessManager(...) // for a development or production environment. c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentLocal), midaz.WithAnonymous(), ) if err != nil { log.Fatalf("midaz.New: %v", err) } defer c.Shutdown(context.Background()) ctx := context.Background() // List the first 5 organizations using a typed list-opts struct. page, err := c.V2.Organizations.List(ctx, models.OrganizationsListOpts{ PageListOpts: models.PageListOpts{Limit: 5}, }) if err != nil { log.Fatalf("list organizations: %v", err) } for _, org := range page.Items { fmt.Printf("- %s (%s)\n", org.LegalName, org.ID) } // Create a new organization. midaz.CreateOrganizationInput is the same // type as models.CreateOrganizationInput, re-exported on the midaz package. dba := "Example Inc." org, err := c.V2.Organizations.Create(ctx, &midaz.CreateOrganizationInput{ LegalName: "Example Corporation", LegalDocument: "123456789", DoingBusinessAs: &dba, // optional fields are *string Address: midaz.Address{ Line1: "123 Main St", City: "New York", State: "NY", ZipCode: "10001", Country: "US", }, }) if err != nil { log.Fatalf("create organization: %v", err) } fmt.Printf("Organization created: %s\n", org.ID) } ``` This gives you access to: * The Midaz client for calling each API service. * Built-in data models (like `CreateOrganizationInput`). * Auth via **Access Manager** (production) or **Anonymous** (local development). * A typed configuration system that fails at construction time. > [!TIP] > > For the full setup, see the [Authentication](#authentication) section. ### Step 5 – Run the project Run the following command: ```bash Bash theme={null} go run main.go ``` ## SDK architecture *** #### Layered design | Layer | What it handles | | :- | :- | | **Client** | The main entry point. `midaz.New(...)` wires authentication, retries, and observability. | | **Services** | The Midaz services the SDK wraps, grouped by the API version that serves them. | | **Models** | The data structures of the Midaz domain. The common ones are re-exported on the `midaz` package. | | **Utility packages** | Helpers for config, errors, observability, retries, idempotency, and more. | ### Services Midaz serves two ledger API versions: `/v1`, which is deprecated, and `/v2`. The SDK groups the ledger services by the version that serves them. **Build against `c.V2`.** A resource that one version does not serve is a compile error, not a 404. ```go Go theme={null} orgs, err := c.V2.Organizations.List(ctx, opts) account, err := c.V2.Accounts.Get(ctx, orgID, ledgerID, accountID) tx, err := c.V2.Transactions.CreateDirect(ctx, orgID, ledgerID, input) // /v1 only: rate, err := c.V1.AssetRates.GetAssetRate(ctx, orgID, ledgerID, externalID) ``` | Group | Services | | :- | :- | | `c.V2` and `c.V1` | `Organizations`, `Ledgers`, `Accounts`, `AccountTypes`, `Assets`, `Balances`, `Operations`, `Portfolios`, `Segments`, `OperationRoutes`, `TransactionRoutes`, `Transactions`, `MetadataIndexes` | | `c.V2` only | `Holders`, `Instruments`, `Encryption`, `Composition`, `ProtectionAudit`, `BillingPackages`, `FeePackages`, `FeeEstimates`, `BillingCalculations` | | `c.V1` only | `AssetRates` | | Tracer, on the client | `c.Rules`, `c.Limits`, `c.Validations`, `c.AuditEvents` | `Transactions` has a different contract on each version. On `/v1`, you create a transaction through one of six creation methods with a nested `send` body. On `/v2`, `c.V2.Transactions` creates transactions with a flat body through `CreateDirect`, `CreateHold`, `CreateBlock`, and `CreateUnblock`. It returns `models.TransactionV2`. To post several `direct` and `hold` transactions as one ordered batch, use `c.V2.Transactions.CreateBatch`. Midaz applies all the items in order, or none. Each item is a `models.TransactionBatchItemV2` with an `Action` (`direct` or `hold`) and an `Order` (one-based and consecutive). The call returns the transactions in that order. The batch has one idempotency key, which you set with `sdkctx.WithIdempotencyKey`. An item that sets its own `IdempotencyKey` is refused. > [!NOTE] > > A `201` response means that Midaz applied the transaction to balances. ### Read the server version `c.ServerVersion` reads the version of the Midaz ledger that the client talks to. It returns an error when the ledger does not answer with a version. `midaz.SupportsRulesOnly` tells you if the Tracer behind that version accepts rules-only validation. `c.Validations.EvaluateRulesOnly` judges a transaction by its rules alone: it checks no spending limit and counts nothing against one. ```go Go theme={null} v, err := c.ServerVersion(ctx) if err != nil { return fmt.Errorf("read server version: %w", err) } if midaz.SupportsRulesOnly(v) { verdict, err := c.Validations.EvaluateRulesOnly(ctx, input) // input is a *models.ValidateTransactionInput if err != nil { return err } _ = verdict } ``` ### Models Each model type represents a business concept. You use them in each service call. The most common model types are re-exported on the `midaz` package. `midaz.Account` and `models.Account` are the same type, so most code needs only one import. `midaz.Account` carries `ClosedAt`, the time Midaz closed the account. It is `nil` while the account is open. Closing an account does not change `Status`. #### Common model types | Model | What it represents | | :- | :- | | `midaz.Organization` | A business entity that owns ledgers and accounts. | | `midaz.Ledger` | A collection of accounts and transactions. | | `midaz.Asset` | A unit of value (currency, token, etc.) that can be stored or moved. | | `midaz.Account` | An account for tracking assets and balances. | | `midaz.Portfolio` | A collection of accounts for grouping and management. | | `midaz.Segment` | A categorization unit for granular organization. | | `midaz.Transaction` | A financial event composed of multiple operations. | | `midaz.Operation` | An individual debit or credit entry within a transaction. | | `midaz.Balance` | The current state of an account's holdings. | > [!TIP] > > For a type that is not re-exported, such as `models.TransactionV2`, import `github.com/LerianStudio/midaz-sdk-golang/v6/models` directly. The `midaz` aliases keep the type identity, so the two import paths work together. ### Utility packages The `pkg` folder of the SDK holds utility packages. **Core** packages serve concerns that apply to the whole SDK. **Helper** packages give domain-specific or low-level utilities. #### Core packages | Package | What it solves | | :- | :- | | `auth` | Access Manager OAuth and the token lifecycle. | | `config` | Config handling, environment loading, and custom service URLs. | | `concurrent` | Tools for batching, rate-limiting, and worker pools. | | `errors` | Structured error types, classifiers, and the `Retryable()` predicate. | | `observability` | Tracing, metrics, and logs through one OpenTelemetry provider. | | `retry` | Retry policy options with exponential backoff and jitter. | | `sdkctx` | Per-request context flags, such as idempotency keys. | | `validation` | Input validation with structured error messages. | #### Helper packages | Package | What it solves | | :- | :- | | `accounts` | Account-specific helpers and convenience functions. | | `conversion` | Type conversion helpers between models and external formats. | | `data` | Data utilities and faker helpers for testing and demos. | | `format` | Utilities for formatting data the Midaz way (dates, times, etc.). | | `generator` | Demo and mass-data generation for end-to-end scenarios. | | `integrity` | Checksum and integrity verification utilities. | | `performance` | Helpers for tuning bulk operations and high-throughput tasks. | | `security` | Security utilities, including SSRF protection and TLS validation. | | `stats` | Processing statistics and metrics aggregation. | | `transaction` | Transaction helpers, such as the settlement wait. | | `utils` | General-purpose helpers used across the SDK. | | `version` | SDK version metadata and identification. | ## Authentication *** The SDK requires exactly one authentication source at construction time. If you call `midaz.New(...)` with neither, it returns a typed configuration error. You have two choices: * **`midaz.WithAccessManager(...)`**: OAuth through the Lerian Access Manager. Use it for any non-local stack. * **`midaz.WithAnonymous()`**: no authentication. Use it only for a local Midaz stack with auth disabled. If you apply both options, the last one wins. ### Production: Access Manager Put your Access Manager credentials in `midaz.WithAccessManager`. The SDK requests a token from your Access Manager, attaches it to each API call, and refreshes it when it expires. > [!WARNING] > > Replace the values in the `// Configure Access Manager` block with your own credentials before running. ```go Go expandable theme={null} package main import ( "context" "log" "os" midaz "github.com/LerianStudio/midaz-sdk-golang/v6" ) func main() { // Configure Access Manager. Load ClientID and ClientSecret from // environment variables; do not hardcode them. c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentProduction), midaz.WithAccessManager(midaz.AccessManager{ Address: "https://auth.example.com", ClientID: os.Getenv("MIDAZ_CLIENT_ID"), ClientSecret: os.Getenv("MIDAZ_CLIENT_SECRET"), }), ) if err != nil { log.Fatalf("midaz.New: %v", err) } defer c.Shutdown(context.Background()) // Use c.V2.Organizations, c.V2.Ledgers, c.V2.Accounts, ... } ``` ### Local development: Anonymous For a local Midaz stack with auth disabled, opt out explicitly: ```go Go theme={null} c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentLocal), midaz.WithAnonymous(), ) ``` ### Configure via environment variables You can also point the SDK at your Access Manager with environment variables. Export them in your shell or your process manager: ```bash Bash theme={null} export PLUGIN_AUTH_ENABLED=true export PLUGIN_AUTH_ADDRESS=https://your-auth-service.com export MIDAZ_CLIENT_ID=your-client-id export MIDAZ_CLIENT_SECRET=your-client-secret ``` > [!NOTE] > > `config.FromEnvironment()` reads the **process environment**, not a `.env` file. If you keep variables in a `.env` file during development, load them with a library like `godotenv` before calling `config.NewConfig(config.FromEnvironment())`. Then opt in to environment loading at config time: ```go Go theme={null} import "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/config" cfg, err := config.NewConfig(config.FromEnvironment()) if err != nil { log.Fatalf("config: %v", err) } c, err := midaz.New(midaz.WithConfig(cfg)) ``` > [!NOTE] > > Environment loading is **explicit**. Put `config.FromEnvironment()` in the option chain. The SDK does not read environment variables during construction without it. > [!TIP] > > For the full auth walkthrough, see the [Authentication guide](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/auth.md) in the SDK repo. ## Tenant scope *** **Tenant scope comes from the Access Manager / JWT claims** used to obtain the token. The SDK has no tenant configuration and does not send a tenant header. To run calls under a different tenant scope, use a separate set of Access Manager credentials, or build a second client with its own token context. ## Listing and iteration *** Most list endpoints come in three methods. Pick the one that matches your use case. | Method | Returns | Use when | | :- | :- | :- | | `List` | `*models.ListResponse[T]` (one page) | You want exactly one page and decide when to advance. | | `All` | `iter.Seq2[T, error]` | You want each item. The SDK handles paging internally. | | `Pages` | `iter.Seq2[*models.ListResponse[T], error]` | You need page-level metadata for checkpointing or batching. | ### Typed list options Each list method takes a typed opts struct. The struct embeds one of two base structs, based on how the endpoint paginates: | Pagination shape | Endpoints | Base struct | | :- | :- | :- | | **Page-based** | Organizations, Ledgers, Assets, Portfolios, Segments, Accounts, AccountTypes, FeePackages, BillingPackages | `models.PageListOpts{Limit, Page, SortDirection, StartDate, EndDate}` | | **Cursor-based** | Transactions, Balances, Holders, Operations, OperationRoutes, TransactionRoutes, AssetRates | `models.CursorListOpts{Limit, Cursor, SortDirection, StartDate, EndDate}` | Some endpoints also expose a typed `Filters` sub-struct. If you set a field of the wrong shape (for example, `Page` on a cursor endpoint), the code does not compile. > [!WARNING] > > The transaction list does not filter by `Status`, `AssetCode`, `Reference`, `SourceAccount`, `DestinationAccount`, or `Route`. If you set one of these filters on `List`, the SDK refuses the call with an error. `Count` accepts `Status` and `Route`. ### Iterate every item with `All` The simplest shape is a `range` loop over each item across each page. The SDK fetches the pages internally. ```go Go theme={null} opts := models.AccountsListOpts{ PageListOpts: models.PageListOpts{Limit: 100}, Filters: models.AccountsFilters{ Status: "ACTIVE", AssetCode: "USD", }, } for account, err := range c.V2.Accounts.All(ctx, orgID, ledgerID, opts) { if err != nil { return fmt.Errorf("list accounts: %w", err) } process(account) } ``` ### Iterate page envelopes with `Pages` When you need page-level metadata (for checkpointing, batching, or stopping mid-page), iterate over `Pages`. Each entry is a `*models.ListResponse[T]` with its `Pagination` block. ```go Go theme={null} opts := models.TransactionsListOpts{ CursorListOpts: models.CursorListOpts{Limit: 50}, } for page, err := range c.V2.Transactions.Pages(ctx, orgID, ledgerID, opts) { if err != nil { return fmt.Errorf("page iter: %w", err) } log.Printf("items=%d next_cursor=%q", len(page.Items), page.Pagination.NextCursor) for _, tx := range page.Items { process(tx) } if shouldStop(page) { break // The SDK stops paging. } } ``` See the [Pagination guide](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/pagination.md) in the SDK repo for `NextCursor` handling and the page-vs-cursor decision table. ## Error handling *** The SDK service layer returns errors as `*pkg/errors.Error` with structured fields: | Field | What it carries | | :- | :- | | `Category` | The error class (validation, authentication, network, configuration, and so on). | | `Code` | A stable string code for branching or telemetry. | | `Operation` | The SDK operation that produced the error. | | `Resource` | The resource family the error refers to, when relevant. | You can branch with typed predicates, read fields with `errors.As`, or use the `Retryable()` method to drive retry policy. ### Branch with typed predicates The SDK has a set of `Is*` predicates, so you can match errors without reading internals: ```go Go expandable theme={null} import ( "errors" "fmt" sdkerrors "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/errors" ) acc, err := c.V2.Accounts.Get(ctx, orgID, ledgerID, accountID) if err != nil { switch { case sdkerrors.IsNotFoundError(err): return fmt.Errorf("account not found: %w", err) case sdkerrors.IsAuthError(err): return fmt.Errorf("auth failure: %w", err) case sdkerrors.IsValidationError(err): return fmt.Errorf("invalid input: %w", err) case sdkerrors.IsInsufficientBalanceError(err): return fmt.Errorf("not enough balance: %w", err) case sdkerrors.IsTransactionReservationDenied(err): return fmt.Errorf("refused by Tracer: %w", err) case sdkerrors.IsConflictError(err): return fmt.Errorf("already exists: %w", err) case sdkerrors.IsRateLimitError(err): return fmt.Errorf("rate limited: %w", err) case sdkerrors.IsNetworkError(err): return fmt.Errorf("transient transport: %w", err) case sdkerrors.IsConfigurationError(err): return fmt.Errorf("setup mistake: %w", err) } // Read the structured fields when you need them. var sdkErr *sdkerrors.Error if errors.As(err, &sdkErr) { log.Printf("op=%s resource=%s code=%s retryable=%v", sdkErr.Operation, sdkErr.Resource, sdkErr.Code, sdkErr.Retryable()) } } ``` ### Drive retry decisions with `Retryable()` The `Error.Retryable()` method derives from `Category`. Use it instead of your own classification. ```go Go theme={null} var sdkErr *sdkerrors.Error if errors.As(err, &sdkErr) && sdkErr.Retryable() { // Apply your retry logic: backoff, jitter, max attempts, etc. } ``` ### Wrap raw transport errors If you call lower-level HTTP code outside the SDK and want the same structured error shape, use `ClassifyTransportError`: ```go Go theme={null} import sdkerrors "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/errors" resp, err := httpClient.Do(req) if err != nil { return sdkerrors.ClassifyTransportError("PaymentService.Charge", err) } ``` ### Local validation: FieldErrors Local input validation returns `*pkg/validation.FieldErrors`, a collection of per-field errors that the SDK finds before any HTTP call. Use `errors.As` to read them. ```go Go theme={null} import ( "errors" "fmt" "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/validation" ) var fieldErrs *validation.FieldErrors if errors.As(err, &fieldErrs) { for _, fe := range fieldErrs.Errs() { fmt.Printf("- %s: %s\n", fe.Field, fe.Message) } } ``` > [!TIP] > > For the full category map, each code, and retry boundaries, see the [Error handling guide](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/errors.md) in the SDK repo. ## Retries *** The default policy retries 3 times with exponential backoff and 25% jitter. It retries transport errors and the statuses `408`, `425`, `429`, `500`, `502`, `503`, and `504`. The SDK retries a `POST`, `PUT`, `PATCH`, or `DELETE` when the request has an `X-Idempotency` header, or when it is a transaction, holder, or instrument create, which Midaz answers with the first outcome when the same request comes again. It sends every other write once. After a write fails, the SDK stops retrying when the idempotency window has passed since the call started. The window is the `X-TTL` value of the request, or 300 seconds when the header is absent. A `409` with code `0084` under a key you set comes back as an error. The SDK retries a `0084` only under its own random key or on a keyless create. ```go Go theme={null} import ( "time" "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/retry" ) c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentLocal), midaz.WithAnonymous(), midaz.WithRetryOptions( retry.WithMaxRetries(5), retry.WithInitialDelay(200*time.Millisecond), ), ) ``` Use `midaz.WithCustomRetryPolicy` for your own retry predicate. To turn retries off, use `midaz.WithoutRetries()`. ## Logging *** **`*slog.Logger` is the logger surface of the SDK.** Wire it with `midaz.WithLogger(...)`. The SDK is **silent by default**: it uses `slog.DiscardHandler` until you opt in. You decide the handler, the level, and the destination. ```go Go expandable theme={null} package main import ( "context" "log" "log/slog" "os" midaz "github.com/LerianStudio/midaz-sdk-golang/v6" ) func main() { logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, })) c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentLocal), midaz.WithAnonymous(), midaz.WithLogger(logger), ) if err != nil { log.Fatalf("midaz.New: %v", err) } defer c.Shutdown(context.Background()) // SDK log lines now go to your handler. } ``` charmbracelet/log, zap, and zerolog integrate through `slog.Handler`. > [!TIP] > > The [Logging guide](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/logging.md) has adapter recipes for common logging libraries. ## Observability *** An observability provider gives you spans, metrics, and OpenTelemetry-correlated logs. Pass a provider that you build, or pass options that the SDK assembles for you. ### Wire a provider ```go Go expandable theme={null} package main import ( "context" "log" midaz "github.com/LerianStudio/midaz-sdk-golang/v6" "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/observability" ) func main() { ctx := context.Background() provider, err := observability.New(ctx, observability.WithServiceName("payments-api"), observability.WithEnvironment("production"), observability.WithComponentEnabled(true, true, true), // tracing, metrics, logs ) if err != nil { log.Fatalf("observability.New: %v", err) } defer provider.Shutdown(ctx) c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentProduction), midaz.WithAccessManager(midaz.AccessManager{ /* ... */ }), midaz.WithObservabilityProvider(provider), ) if err != nil { log.Fatalf("midaz.New: %v", err) } defer c.Shutdown(ctx) } ``` ### Or pass options inline ```go Go theme={null} import "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/observability" c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentProduction), midaz.WithAccessManager(am), midaz.WithObservabilityOptions( observability.WithServiceName("payments-api"), observability.WithComponentEnabled(true, true, true), ), ) ``` Without `observability.WithCollectorEndpoint`, the SDK uses the OpenTelemetry providers of your application and does not replace them. `c.Shutdown` closes only a provider that the SDK built. If you pass your own provider, shut it down after the last client that uses it. Calls such as `c.V2.Accounts.Get` create no span and send no `traceparent` header by themselves. To trace them, wrap the transport of the client with the observability middleware: ```go Go theme={null} c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentProduction), midaz.WithAccessManager(am), midaz.WithObservabilityProvider(provider), midaz.WithHTTPTransport(observability.NewHTTPMiddleware(provider)), ) ``` `WithHTTPTransport` keeps the SDK's own HTTP client, its timeout, authentication, and retries, and wraps its transport. You can also wrap a block of business logic in a span with `Client.Trace`: ```go Go theme={null} err = c.Trace("create-organization", func(ctx context.Context) error { _, err := c.V2.Organizations.Create(ctx, input) return err }) ``` > [!WARNING] > > `WithObservabilityOptions` and `WithObservabilityProvider` **replace** the installed provider. They do not merge. To start from a baseline, put `observability.WithDevelopmentDefaults` or `observability.WithProductionDefaults` first in the option chain. > [!TIP] > > See the [`10-observability-otel` example](https://github.com/LerianStudio/midaz-sdk-golang/tree/main/examples/10-observability-otel) in the SDK repo for span attributes, metric names, and exporter setup. ## Idempotency *** The SDK does not generate a random `X-Idempotency` key unless you opt in. Without a key of your own, Midaz treats an identical transaction create inside the idempotency window (300 seconds by default) as a repeat and returns the first transaction. A second intentional transaction with the same request does not post. For how Midaz treats a missing key, see [Retries and idempotency](/en/reference/retries-idempotency). Set a distinct key for each transaction you intend to post. This is typical for saga steps, outbox rows, or UI submissions. ### Set a stable key per request ```go Go theme={null} import "github.com/LerianStudio/midaz-sdk-golang/v6/pkg/sdkctx" ctx := sdkctx.WithIdempotencyKey(context.Background(), "tx-2026-05-06-001") tx, err := c.V2.Transactions.CreateDirect(ctx, orgID, ledgerID, input) ``` A key you set always wins over the client option and over `sdkctx.WithoutAutoIdempotency`. > [!WARNING] > > Midaz uses the key on transaction creates and on holder and instrument creates. Tracer does not use it. If a response is lost, an SDK retry of any other write can run it a second time, even with a key. Turn the SDK retries off for those writes, or read the resource before you retry. ### Enable a random key globally To send a random `X-Idempotency` key on each create, update, and delete, opt in at the client level: ```go Go theme={null} c, err := midaz.New( midaz.WithEnvironment(midaz.EnvironmentLocal), midaz.WithAnonymous(), midaz.WithIdempotency(true), ) ``` You can also set `MIDAZ_IDEMPOTENCY=true` when you use `config.FromEnvironment()`. Each call then carries its own key, so two intentional transactions with the same request post separately. A retry of one call reuses that call's key. ### Stop the random key for one call When the client has the random key on, you can stop it for one call: ```go Go theme={null} ctx := sdkctx.WithoutAutoIdempotency(context.Background()) ``` ## Environment variables *** The SDK reads these variables only when `config.FromEnvironment()` is in your config option chain. | Variable | Description | | :- | :- | | `MIDAZ_ENVIRONMENT` | Target environment (`local`, `development`, `production`). | | `MIDAZ_BASE_URL` | Base URL for the Midaz services, used when the service-specific URLs are not set. Do not add a `/v1` or `/v2` suffix. | | `MIDAZ_LEDGER_URL` | Ledger API URL. It serves the onboarding and transaction endpoints. | | `MIDAZ_TRACER_URL` | Tracer API URL. | | `MIDAZ_TRACER_API_KEY` | Optional API key for Tracer. When you do not set it, Tracer calls use the ledger bearer token. | | `PLUGIN_AUTH_ENABLED` | Enable Access Manager authentication (`true` or `false`). | | `PLUGIN_AUTH_ADDRESS` | Address of the Access Manager service. | | `MIDAZ_CLIENT_ID` | Client ID for Access Manager authentication. | | `MIDAZ_CLIENT_SECRET` | Client secret for Access Manager authentication. | | `MIDAZ_TIMEOUT` | HTTP request timeout in seconds. | | `MIDAZ_DEBUG` | Enable debug logs (`true` or `false`). | | `MIDAZ_MAX_RETRIES` | Maximum retry attempts for failed requests. | | `MIDAZ_IDEMPOTENCY` | Send a random idempotency key on each create, update, and delete (`true` or `false`). Default: `false`. | | `MIDAZ_ERROR_EXPOSE_BODY` | Include the raw response body in `*pkg/errors.Error`. | | `MIDAZ_ACCESS_MANAGER_ALLOW_INSECURE_HTTP` | Allow plain HTTP to the Access Manager. The SDK rejects it when `MIDAZ_ENVIRONMENT=production`. | | `MIDAZ_ALLOW_INSECURE_HTTP` | Allow plain HTTP to the ledger and Tracer URLs on non-loopback hosts. The SDK rejects it when `MIDAZ_ENVIRONMENT=production`. | For the full option matrix across `midaz`, `pkg/config`, and `pkg/sdkctx`, see the [Configuration guide](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/configuration.md) in the SDK repo. ## Example projects *** > [!TIP] > > The SDK has a numbered set of focused tutorials (examples 01–11), plus advanced and reference examples. Each numbered example teaches one concept. Browse them in the [examples directory](https://github.com/LerianStudio/midaz-sdk-golang/tree/main/examples) on GitHub. | Example | What it demonstrates | | :- | :- | | `01-hello-world` | Minimal init plus the first API call. | | `02-auth` | Access Manager authentication (production setup). | | `03-end-to-end` | Creating a transaction on `/v2` with `CreateDirect`. | | `04-listing-cursor` | Cursor-based pagination with `iter.Seq2`. | | `05-listing-pages` | Page-based pagination with `List`, `All`, and `Pages`. | | `06-idempotency` | No key, your own key. | | `07-retries` | Default policy, custom policy, disabled retries. | | `08-logging-slog` | `*slog.Logger` integration. | | `09-testing-with-mocks` | A narrow interface of your own plus a hand-written mock. | | `10-observability-otel` | Full OpenTelemetry surface (tracing + metrics + logs). | | `11-server-version` | Read the server version at start-up and refresh it on a timer. | The repository also includes reference examples: `concurrency`, `configuration`, `context`, `tracing`, `tracing-server`, `pkg-validation-demo`, `mass-demo-generator`, and `workflow-with-entities`. ## Explore the APIs *** For more information about the APIs, refer to the following links: > [card] [External API mapping](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/mapping/external_apis.md) > [card] [Internal API mapping](https://github.com/LerianStudio/midaz-sdk-golang/blob/main/docs/mapping/internal_apis.md) > [card] [Godoc documentation](https://pkg.go.dev/github.com/LerianStudio/midaz-sdk-golang/v6) # Midaz SDK for TypeScript Source: https://docs.lerian.studio/en/products/midaz/midaz-sdk-typescript Lerian no longer maintains the Midaz SDK for TypeScript. Use the Midaz REST API or the Midaz SDK for Go. Lerian no longer maintains the Midaz SDK for TypeScript. To integrate with Midaz, use the [Midaz REST API](/en/reference/products/midaz/quick-start-guide) or the [Midaz SDK for Go](/en/products/midaz/midaz-sdk-go). # Operations Source: https://docs.lerian.studio/en/products/midaz/operations Understand Operations as the smallest units of ledger activity in Midaz: single debit or credit entries on an Account, grouped into balanced Transactions. An operation is the smallest unit of a transaction. A posted transaction has at least one debit and one credit operation. A pending transaction records only its source side until you commit it. * A **Debit operation** records value that moves **out of** an account (the source). * A **Credit operation** records value that moves **into** an account (the destination). The effect on the stored balance depends on the balance `direction`. A normal account (the common case) shrinks on a debit and grows on a credit. A transaction contains operations that must net to zero from the ledger's view. For example, a P2P payment with a fee includes: * a **\$100 debit** from the sender's account. * a **\$98 credit** to the recipient's account. * a **\$2 credit** to the platform's fee account. Midaz makes sure a transaction balances before it commits. Operations also carry metadata such as timestamps and references to the transaction they belong to. You create a transaction through the Midaz JSON API. For each transaction, you specify a set of operations. Each operation has an amount, an asset, and a source or destination account. ## Key characteristics *** * Each operation belongs to a transaction and references a specific account and asset. * Operations include metadata like amount, direction (debit/credit), type, timestamps, references, and more. * Midaz creates operations when you start a transaction and fills them with the data you provide. * Midaz validates all operations against the configured rules before it commits them to the ledger. > [!NOTE] > > Every operation has a **`direction`** (`debit` or `credit`) and a **`type`**. The `direction` is the debit or credit side described above. The `type` classifies the movement. Beyond the standard `CREDIT` and `DEBIT`, the `type` marks special movements: > > * `ON_HOLD` and `RELEASE`: two-phase fund reservations. > * `OVERDRAFT`: system-generated companion operations on the internal overdraft balance. > * `BLOCK` and `UNBLOCK`: the label applied to every operation of a transaction created through the dedicated [block and unblock endpoints](/en/products/midaz/transactions#blocking-and-unblocking-funds). The label overrides only the operation `type`, never its direction or amount. > * `FEE_SETTLEMENT` and `FEE_REFUND`: the settlement of a [fee debt](/en/products/midaz/fees/fee-debt), and its refund on a revert. > > The `direction` always keeps its debit or credit meaning, regardless of `type`. ## Operation Routes *** With Accounting Routes, each operation connects to structured validation logic. That logic lives in [Operation Routes](/en/products/midaz/transaction-routing-entities). ### What is an Operation Route? An **Operation Route** is a validation rule. It defines which account types or specific accounts a transaction component can use. It also sets the accounting direction (source, destination, or bidirectional) and a descriptive annotation. It is a validation layer between transaction input and ledger structure. Each operation you submit must meet the account requirements and business rules. > [!NOTE] > > Transactions contain multiple operations. Operation Routes validate each operation against the configured validation rules. ### Operation > Operation Route relationship When you submit a transaction to Midaz, it contains multiple **Operations**. With **Account Types and Accounting Routes enabled**, Midaz validates each operation against the rules in the Operation Routes. This makes sure that: * The specified account matches the expected account type or specific account requirement. * The operation direction (debit/credit) aligns with the route definition. > [!CAUTION] > > If the operations you submit do not match the configured Operation Route requirements, Midaz fails the validation and rejects the transaction. ## Managing Operations *** Midaz generates operations automatically as part of a transaction flow. You cannot create an operation directly. You can query an operation and update its description and metadata. * [List Operations by Account](/en/reference/products/midaz/v2/get-all-operations-by-account): View all Operations linked to a specific Account. * [Retrieve an Operation by Account](/en/reference/products/midaz/v2/get-operation-by-account): Get details of a specific Operation for that Account. * [Update an Operation](/en/reference/products/midaz/v2/update-operation): Change the description and metadata of an Operation. # Organizations Source: https://docs.lerian.studio/en/products/midaz/organizations Define the top-level Organization that owns your Midaz Ledgers. Represent banks, fintechs, and parent-child hierarchies for subsidiaries. An **Organization** is the top-level entity in Midaz. It represents a financial institution, such as a bank or fintech. An Organization owns and governs the financial data of that institution. It is the primary container for all financial operations. A bank or financial group registers as an Organization in Midaz. > [!NOTE] > > **On Lerian Cloud**: Midaz scopes every Organization to your tenant automatically. When you list Organizations, you see only the ones in your account. You do not filter by tenant or add a tenant identifier to your requests. ### Sub-Organizations Organizations support **parent-child hierarchies**. A bank uses them to represent subsidiaries, regional branches, or separate business units in one framework. This structure fits financial groups that run several legal entities. Each entity owns its own [Ledgers](/en/products/midaz/ledgers) and stays operationally independent. The parent-child link records how the entities relate. ### Organization structure * **Organization > Ledgers:** An Organization can own several Ledgers. Each Ledger holds its financial records, such as accounts and transactions, and belongs to one Organization. ### Key characteristics * Organizations are the highest level in the hierarchy. * Each Organization governs its own Ledgers and sets their operational boundaries. ## Flexible hierarchies *** Midaz supports organizational hierarchies for complex structures. If your company has several locations or divisions, you can create **child organizations** for specific branches, offices, or subdivisions. Each child organization connects to a **parent organization**. Each Organization keeps its own data. > [!NOTE] > > If a single group manages several Organizations, use this hierarchy to set clear boundaries between them. ### Example **Company XPTO** is a Brazilian company with branches in São Paulo and New York. Its structure is as follows: * **Parent Organization**: XPTO Ltda * **Child Organizations**: * XPTO New York * XPTO São Paulo With this structure, the company can: * Set a distinct role for each branch. * Track each branch separately. * Adapt workflows to each branch. ## Benefits of organizational structuring *** * **Scalability**: Add or change branches as the business grows. * **Efficiency**: Manage all levels from one hierarchy. * **Personalization**: Configure each branch on its own. > [!TIP] > > Need help with your Midaz setup? Our consulting service can help you design the structure for your organization, from scratch or from an existing setup. > > [Contact us](https://lerian.studio/contact) to learn more. ## Managing Organizations *** You manage your Organization through the API or Lerian Console. ### Via API * [Create an Organization](/en/reference/products/midaz/v2/create-organization): Register a new Organization. * [List Organizations](/en/reference/products/midaz/v2/list-organizations): View all Organizations in your workspace. * [Retrieve an Organization](/en/reference/products/midaz/v2/get-organization-by-id): Get details of a specific Organization. * [Update an Organization](/en/reference/products/midaz/v2/update-organization): Edit an existing Organization. * [Delete an Organization](/en/reference/products/midaz/v2/delete-organization): Mark an Organization as deleted. > [!NOTE] > > When you delete an Organization, Midaz does not remove it from the system. > > Midaz sets a `deletedAt` timestamp instead. Midaz then excludes the Organization from every read, and you can no longer use it. Midaz leaves its `status.code` unchanged, which preserves historical data for audit trails. Midaz rejects Organization deletion in a production environment. ### Via Lerian Console You view, create, edit, and delete Organizations from the **Organizations** page in the Midaz Module of Lerian Console. [**Learn more in the Managing Organizations guide.**](/en/products/midaz/console/managing-organizations) > [!TIP] > > When you create your **first Organization** in the Console, you do it as part of the onboarding flow. To learn more, see the [Midaz Module onboarding](/en/products/midaz/console/midaz-console-onboarding) guide. # Portfolios Source: https://docs.lerian.studio/en/products/midaz/portfolios Group Midaz Accounts under a single customer or business unit as a Portfolio to view the total client relationship and apply policies at the wallet level. A **Portfolio** is a logical group of Accounts that belong to a single entity, such as a customer or business unit. It groups the related Accounts under one structure and makes them simpler to manage. Think of a Portfolio as a **wallet** that holds multiple asset-specific Accounts for a customer. For example, a retail banking customer might have a Portfolio that includes: * A BRL checking account. * A USD savings account. * A credit card account. With a Portfolio, an institution can view a customer’s total relationship across all accounts. The institution can also apply policies at the Portfolio level. ## Portfolio structure *** * **Portfolio > Accounts**: A Portfolio groups Accounts. These Accounts usually link to one customer or entity. * **Portfolio > Ledger > Organization**: A Portfolio belongs to an Organization through its Ledger. ## Key characteristics *** * Portfolios commonly represent customers in a banking context. * They simplify financial aggregation and give customer-level insights. * You can also create internal Portfolios for operational use cases. ## Managing Portfolios *** You can manage your Portfolios either through the API or through Lerian Console. ### Via API * [List Portfolios](/en/reference/products/midaz/v2/list-portfolios): View all Portfolios in a Ledger. * [Retrieve a Portfolio](/en/reference/products/midaz/v2/get-portfolio-by-id): Get details of a specific Portfolio. * [Create a Portfolio](/en/reference/products/midaz/v2/create-portfolio): Register a new Portfolio. * [Update a Portfolio](/en/reference/products/midaz/v2/update-portfolio): Edit an existing Portfolio. * [Delete a Portfolio](/en/reference/products/midaz/v2/delete-portfolio): Remove a Portfolio. ### Via Lerian Console You can view, create, edit, and delete Portfolios from the Portfolios page in the Midaz Module of Lerian Console. [**Learn more in the Managing Portfolios guide.**](/en/products/midaz/console/managing-portfolios) # Receiving Midaz events Source: https://docs.lerian.studio/en/products/midaz/receiving-midaz-events Consume Midaz events from Kafka, understand the legacy RabbitMQ surface, and check the current Streaming Hub compatibility boundary. Midaz emits CloudEvents for ledger, CRM, Fees, and Tracer business facts. The public integration contract is the **Kafka** surface. Legacy RabbitMQ exchanges remain outside the public catalog. ## Current event surface: Kafka *** Enable publication on each producing service: ```env theme={null} STREAMING_ENABLED=true STREAMING_BROKERS= STREAMING_CLOUDEVENTS_SOURCE=ledger ``` Set `STREAMING_CLOUDEVENTS_SOURCE` when you enable streaming. Use `ledger` for the ledger, CRM, and Fees binary. Use `tracer` for Tracer. Each service rejects any other value at startup. Midaz uses one v3 application fact topic per producing service: * Ledger, CRM, and Fees: `lerian.streaming.ledger` * Tracer: `lerian.streaming.tracer` Examples: * `organization.created` rides `lerian.streaming.ledger` * `transaction.posted` rides `lerian.streaming.ledger` * `fee_charge.applied` rides `lerian.streaming.ledger` * `rule.created` rides `lerian.streaming.tracer` The CloudEvents type is source-qualified as `studio.lerian...`. Headers `ce-resourcetype` and `ce-eventtype` carry the dispatch key separately. The `ce-tenantid` header is always present for Midaz. It carries your tenant ID, or the literal `default` when the event has no tenant. The ledger and Tracer each serve their public JSON business-event catalog and topic mapping at: ```http theme={null} GET /v1/streaming/manifest ``` The manifest route remains available even when you disable publication. Use it as the deployment-time contract instead of guessing topics. The [Midaz event reference](/en/reference/events/midaz) and [Tracer event reference](/en/reference/events/tracer) list every public business event and payload. ### Delivery semantics Midaz publishes these business events directly after the state change. It does not persist them in a streaming outbox. Midaz logs publication failures and does not return them to the business command. Consumers must still be idempotent and deduplicate on `(ce-source, ce-id)` because broker delivery can repeat a published record. Money values use decimal strings. Never parse them as binary floating point. ### Consumer checklist 1. Read the producer manifest. 2. Subscribe to the producer's application topic. 3. Route on `ce-resourcetype` and `ce-eventtype`, not on payload shape. 4. Validate `ce-schemaversion` before decoding. 5. Persist your deduplication key before acknowledging the record. ## Legacy RabbitMQ surface *** Midaz also maintains legacy RabbitMQ exchanges for selected overdraft and audit events. This is not the complete Kafka catalog. If you use these exchanges, you own queue bindings, `ack`/`nack`, dead-lettering, retries, and consumer isolation. The internal async transaction balance-operation pipeline controlled by `RABBITMQ_TRANSACTION_ASYNC` is not a public event feed. Use the Kafka surface for new integrations unless you explicitly depend on a legacy RabbitMQ contract. ## Streaming Hub compatibility *** Streaming Hub follows the v3 Midaz application topics `lerian.streaming.ledger` and `lerian.streaming.tracer`. A subscription can therefore receive Midaz facts when you enable the producer, hub ingest, and destination runtime. Match on the event key from `ce-resourcetype` and `ce-eventtype`. Do not expect a per-event Kafka topic. ## Decision *** | Need | Use | | - | - | | Public Midaz business-event catalog | Direct Kafka consumption or Streaming Hub | | Existing compatibility integration on selected exchanges | Legacy RabbitMQ | | Managed webhook, pull, SQS, RabbitMQ, or EventBridge delivery | Streaming Hub subscription | # Recommended workflow Source: https://docs.lerian.studio/en/products/midaz/recommended-workflow Follow the recommended Midaz onboarding workflow to create your Organization, Ledgers, Assets, Account Types, and Accounts in the correct order, step by step. Follow the steps below in order. They set up your Organization, Ledgers, Assets, Account Types, and Accounts. ## Setting up and managing Ledgers *** When you onboard to Midaz, follow these steps: ![Workflow for setting up and managing ledgers when onboarding to Midaz](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/setup-ledgers.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=b6880cb23b58e3a4c0883d387bf0dffa) Figure 1. Workflow for setting up and managing ledgers. ### Step 1: [Set up the Organization](/en/reference/products/midaz/v2/create-organization) Your organization in Midaz represents your bank or business entity. If you have not created it yet, set it up in the Console or API. Make sure the core details are accurate, such as the legal name and identifiers. ### Step 2: [Create the Ledgers](/en/reference/products/midaz/v2/create-ledger) Create a Ledger under your organization to hold financial records. Most setups start with a primary ledger for all customer-facing operations (for example, "Main Banking Ledger"). At first it contains no accounts. It is the base layer for all financial activity. ### Step 3: [Define Asset types](/en/reference/products/midaz/v2/create-asset) Register the assets your ledger supports. These can include currencies (for example, BRL, USD), points, or crypto tokens. You use these assets across your account and transaction configuration. You can add more assets as your product portfolio grows. ### Step 4: [Create Account Types](/en/reference/products/midaz/v2/create-account-type) To enforce account classification rules, define your **Account Types**. These are categories, for example `user_wallet`, `treasury`, or `revenue`. You reference them later during account creation or transaction validation. > [!NOTE] > > When you enable Account Type validation, each new account must use a registered Account Type. By default, Account Types are optional. This keeps classification consistent across your ledger. Each Account Type has a `keyValue`. The `keyValue` must be unique and alphanumeric, with dashes and underscores allowed. You use these identifiers in validation flows and transaction routes. ### Step 5: Configure Accounting Routes Use **Operation Routes** and the **Transaction Route** (the `transactionRoute` resource in the API) to define and enforce validation for your transactions. * First, [**create the Operation Routes**](/en/reference/products/midaz/v2/create-operation-route). Each Operation Route validates one leg of the transaction. For example, the debit must come from an account of type `user_wallet`, and the credit must go to the alias `@external/BRL`. * Then, [**create the Transaction Route**](/en/reference/products/midaz/v2/create-transaction-route). It combines the individual operation routes into a complete flow. An example is a cashout transaction with specific debit and credit validations. > [!WARNING] > > After you configure routing and enable validation on the ledger, all transactions must match the defined routing structure. Midaz rejects any transaction that does not match. > > The `routeId` field in the transaction payload must include the ID of the **Transaction Route** you created. ### Step 6: Manage your Ledgers Keep your ledgers clean and scalable with the following best practices: * Use Access Manager to assign permissions by resource and action. * Plan separate ledgers when needed, for example "Testing", "Internal", or "Multi-entity". Document their ownership. * Review and reconcile ledger data regularly, especially when you integrate with external settlement systems. * Midaz enforces double-entry logic, so every movement is fully traceable. Do not change balances manually. ## Configuring Accounts, Portfolios, and Segments *** This section shows how to structure customer data and product entitlements in Midaz. ![Workflow for configuring accounts, portfolios, and segments to structure customer data and product entitlements in Midaz](https://mintcdn.com/lerian-49cb71fc/SFzzdxyH5SN7w_fC/images/en/d2/accounts-portfolios-segments.svg?fit=max\&auto=format\&n=SFzzdxyH5SN7w_fC\&q=85\&s=12a217ce289cfa30aa50c40ba9c45b86) Figure 2. Workflow for configuring Accounts, Portfolios, and Segments. ### Step 1: [Create a customer Portfolio](/en/reference/products/midaz/v2/create-portfolio) Create a **Portfolio** for each new customer. Portfolios are the logical containers for accounts. Link each portfolio to your CRM or internal system through its `entityId` field. ### Step 2: [Set up customer Accounts](/en/reference/products/midaz/v2/create-account) Each financial product or asset the customer holds becomes a separate **Account** under their portfolio. * A checking account in BRL and a savings account in USD are separate accounts. * If you enable [Account Types](/en/reference/products/midaz/v2/create-account-type), the `type` field must match one of the pre-registered values. * Use account aliases to simplify downstream operations. > [!TIP] > > Account Types standardize account categorization across your ecosystem. They improve routing, reporting, and integrations. ### Step 3: [Apply segmentation](/en/reference/products/midaz/v2/create-segment) Use Segments to categorize accounts (for example, `standard`, `vip`, `enterprise`). Fee packages can target a segment, so each segment can get its own fees. ### Step 4: Establish sub-accounts (optional) For organizations or special cases, you can configure sub-accounts. Use clear naming conventions to keep traceability (for example, "Acme USD - Payroll"). ### Step 5: [Set the initial balance](/en/reference/products/midaz/v2/create-transaction-direct) Use the **Transactions API** to add the opening balance. This keeps traceability and double-entry compliance: * Debit the funding source. * Credit the new account. * Do not update balances manually. Midaz tracks every value through transactions. ### Step 6: Verify and review Before you run operations, check the following: * Confirm each account has the correct assets and types. * Validate account balances. * Check that you applied segmentation. * Confirm the setup in the API or the Console. ### Step 7: Ongoing Account management Manage lifecycle operations through the API or Console to keep system integrity: * Update account details as needed. * Close accounts only once the balance reaches zero. * Reclassify accounts if segmentation changes. ## Implementing double-entry transaction management *** Midaz guarantees ledger integrity through strict enforcement of double-entry logic. ![Workflow for implementing double-entry transaction management](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/double-entry-transaction-management.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=dec47b42992268288fda31e26bab0337) Figure 3. Workflow for implementing double-entry transaction management ### Step 1: Structure the transaction Structure your **Transaction** object: * After you configure your Transaction Route, insert its ID into the `routeId` field of your transaction payload. * Define the source and destination accounts, with their asset and value details. * Add descriptive metadata to keep traceability and clarity. ### Step 2: Choose your integration method Use the **Transactions API** for programmatic transaction creation. ### Step 3: Enforce double-entry validation Midaz checks that the sum of credits matches the sum of debits. Midaz rejects a transaction that has a mismatch or a structural violation. ### Step 4: Implement idempotency Use idempotency keys to prevent duplicates from network retries. When a retry repeats the key with the same request, Midaz replays the original response instead of processing the request twice. ### Step 5: Track and reconcile transactions Use built-in tools to: * Track submitted and posted transactions. * Audit metadata and timestamps. ### Step 6: Submit corrections via reversals Do not edit or delete transactions. Submit a reversal instead. Midaz links each reversal to its original transaction for full traceability. ### Step 7: Optimize complex workflows Use multi-operation transactions to: * Process interest accruals. * Execute batched payouts. Midaz keeps atomicity across all legs. Either the full transaction posts, or nothing does. # Rest API Source: https://docs.lerian.studio/en/products/midaz/rest-api Integrate with Midaz through a versioned REST API: JSON payloads, explicit versioning, and a predictable, resource-based design. The Midaz REST API gives you programmatic access to the ledger. It uses standard HTTP methods and status codes. ## REST design, JSON format, and versioning *** * **RESTful design**: The API follows REST principles for a predictable structure. * **JSON format**: The documented API uses JSON for requests and responses. * **Versioning**: Explicit version prefixes keep changes backward-compatible. The API exposes the core Midaz resources: organizations, ledgers, accounts, assets, portfolios, transactions, and operations. Each resource has its own endpoints. To move an integration from the v1 API contracts to the v2 contracts, see [Migrate from API v1 to API v2](/en/products/midaz/migrating-to-api-v2). > [!TIP] > > For technical details on the available endpoints, see the [API Reference](/en/reference/introduction). # Scalability strategies Source: https://docs.lerian.studio/en/products/midaz/scalability-strategies Scale Midaz to millions of Accounts and Transactions per day with partitioning by Ledgers, horizontal service scaling, and read replicas. Midaz handles millions of accounts and transactions per day. You start small and scale horizontally as demand grows, with no re-architecture. For a business overview, see [About Midaz](/en/products/midaz/about-midaz). How you deploy and use Midaz affects its performance. To handle large banking operations, use ledgers to segment workloads and scale each service on its own. ## Structuring entities for High Transaction Volumes *** ### Partitioning by Organizations, Ledgers, and Accounts If your bank processes millions of transactions each day, distribute the workload across many accounts, ledgers, or organizations. For example, segment customers by last-name initial, or assign a separate ledger to each region. Each Midaz ledger is an independent book. ### Lock-oriented Operations Midaz applies the balance changes of each transaction in a single Redis Lua script. The script checks every balance against live state before it writes, so a refused transaction changes no balance. The `@external` account skips the balance-floor and overdraft checks. It can go negative without limit, so transactions against it never fail on available funds. Each transaction still commits atomically. All operations apply, or none do. ### Horizontal scaling of services The Midaz ledger runs as one service that holds onboarding, transactions, CRM, and Fees. You scale it by adding instances. Start small and add instances as demand grows. For high loads, deploy several instances of the ledger service behind a load balancer. Use Kubernetes (K8s) pod scaling. ### CQRS and read replicas Midaz uses CQRS (Command Query Responsibility Segregation) to separate write and read operations. You optimize each path on its own. Route heavy reporting and query loads to read replicas. This keeps transaction commits fast. ### Batching and N:N transactions Where possible, batch related operations into a single transaction. This reduces overhead. Use N:N transactions for bulk work such as mass payouts. For example, one batch of 100 debits and 100 credits is often faster than 100 separate transactions. This works when the operations belong to the same logical set. Midaz processes these N:N transactions in one atomic commit. ### Monitoring and iterative scaling Monitor the key metrics: transaction latency, throughput, resource use (CPU and memory), and database performance. Use the Midaz observability tools (OpenTelemetry and Grafana), or send the metrics to your own monitoring stack. Scale out or up before you reach a performance threshold. Midaz is modular, so you deploy the parts you need. ## Handling multi-currency and multi-entity Operations *** ### Multi-currency strategies Midaz supports multiple currencies with a separate account for each currency. Each transaction moves one asset. To scale well: * Configure every currency asset you need. * Handle currency-specific logic (such as rounding and conversion rates) in your integration layer. * For frequent currency conversion, such as forex trading, run the conversion in a separate service. Midaz records the debits and credits, but an external FX-rate service supplies the rates. * You rarely need a separate ledger per currency, unless policy requires it. Instead, use account types and the transaction-routing API to group accounts by currency for clear reporting. * If one currency covers most transactions, keep all currencies in the same ledger. If multi-currency operations grow too complex, split them into a separate ledger per currency group. ### Multiple Entities: Consolidation and separation For a bank that operates across countries or legal entities: * Use the organization hierarchy to segment entities. Give each entity its own base currency, local assets, and ledgers. * Model inter-entity transactions as external movements. One organization credits its external account, and the other debits its own. * You can run several organizations on one Midaz instance. Allocate enough resources: the same ledger instances process the requests of every organization, so total volume matters. * You can deploy a separate Midaz instance per isolated entity, but you lose unified visibility. One cluster with internal organization separation is usually more practical. ## Performance optimization best practices *** ### Indexing and queries Use the Midaz APIs to read data, not direct database queries. These APIs carry predefined indexes for the core identifiers: accounts, portfolios, and transactions. ### Indexing custom metadata fields Create the indexes you need explicitly through the Metadata Index API. By default, Midaz does not index custom metadata fields. Clients fill these fields as flat key-value pairs. Frequent queries or filters on non-indexed fields can trigger full collection scans. These scans slow down as the data volume grows. Create an index when you regularly use a custom metadata field in search filters. With an index, MongoDB finds the documents fast and cuts query response time. **Recommendations:** * Index only the metadata fields you query often. * Do not index rarely-accessed fields, because each extra index adds write overhead. Manage metadata indexes through dedicated APIs: * [Create a Metadata Index](/en/reference/products/midaz/v2/create-metadata-index) * [List Metadata Indexes](/en/reference/products/midaz/v2/get-all-metadata-indexes) * [Delete a Metadata Index](/en/reference/products/midaz/v2/delete-metadata-index) ### Testing at scale Before full deployment, simulate high traffic with load-testing tools. Create millions of accounts, run heavy transaction volumes, and monitor performance. The Midaz architecture targets high-scale operations, but real-world tests help you tune your setup. # Segments Source: https://docs.lerian.studio/en/products/midaz/segments Group Accounts into Segments to deliver tailored benefits: VIP rates, student perks, fee waivers, and personalized rules across Portfolios. A **Segment** is a group of Accounts that share a characteristic, such as a product tier or a customer type. Financial institutions use Segments to apply tailored rules, services, and conditions to each group. Each Segment has a **Segment ID**, a unique identifier. Financial institutions use this ID to track and manage each Segment. #### Examples * **Black or diamond (Cards)**: a premium group of card accounts for customers who want exclusive benefits. * Included benefits: VIP lounge access, insurance coverage, a dedicated concierge, and loyalty rewards. * **Student account (Banking Accounts)**: a group of banking accounts for students. * Included benefits: no account fees, cashback on education purchases, and discounts on cinemas and events. ## Segment structure *** * **Segment > Accounts:** You tag each Account with a `segmentId` (a Segment UUID) to add it to a Segment. * A Segment belongs to one Ledger. Accounts in different Portfolios can share the same Segment. ## Key characteristics *** * Segments give you a scalable way to apply tailored policies to Accounts. * A Segment can include many Accounts. ## Managing Segments *** You manage your Segments through the API or Lerian Console. ### Via API * [List Segments](/en/reference/products/midaz/v2/list-segments): View all Segments in a Ledger. * [Retrieve a Segment](/en/reference/products/midaz/v2/get-segment-by-id): Get the details of a specific Segment. * [Create a Segment](/en/reference/products/midaz/v2/create-segment): Register a new Segment. * [Update a Segment](/en/reference/products/midaz/v2/update-segment): Edit an existing Segment. * [Delete a Segment](/en/reference/products/midaz/v2/delete-segment): Remove a Segment you no longer use. ### Via Lerian Console You view, create, edit, and delete Segments on the Segments page in the Midaz Module of Lerian Console. [**Learn more in the Managing Segments guide.**](/en/products/midaz/console/managing-segments) # Structuring bank operations with Midaz Source: https://docs.lerian.studio/en/products/midaz/structuring-bank-operation Design Organizations, Ledgers, Portfolios, and Segments for retail and corporate banking, with best practices for scalable hierarchies. Midaz supports retail and corporate banking through a clear entity hierarchy. This page gives best practices to structure organizations, ledgers, accounts, portfolios, and segments. A good structure keeps operations simple as you scale. ## Hierarchy of Organizations and Ledgers *** ### Single vs. multiple Organizations A bank that operates as a single legal entity needs one Organization in Midaz. For a banking group with subsidiaries, use a parent organization over several child organizations. This structure matches your corporate governance. It also isolates data per entity. > [!NOTE] > > The organization structure should reflect your corporate structure. ### Using multiple Ledgers Within an organization, choose the number of ledgers from your operational needs. Keep a **primary ledger** for customer transactions. Add ledgers for special purposes, such as treasury operations or regulatory segmentation. > [!NOTE] > > Use multiple ledgers only when necessary to keep complexity low. A transaction can move funds between ledgers only when each ledger enables `crossLedger.enabled`. See [Ledgers](/en/products/midaz/ledgers). ## Account structuring for retail and corporate banking *** ### Retail customers – Portfolio per customer For retail banking, create a Portfolio for each customer. Each portfolio holds the customer's accounts, such as checking, savings, or credit card. This structure makes balances easy to read per customer. > [!TIP] > > Use [CRM](/en/products/midaz/crm/crm-data-security) to manage personal data such as tax IDs, addresses, and banking aliases, all in one place. ### Corporate clients – hierarchical accounts For corporate banking, use **child accounts** within portfolios to reflect internal structure. A company can hold a parent account for its main funds. It can add child accounts for subdivisions, such as payroll or expense tracking. ### Internal accounts Create internal accounts for revenue, expenses, and settlement flows. Named accounts like "Fee Income – USD" or "Interest Expense – USD" keep financial reporting clear. ## Worked example: a typical digital bank *** This example shows how a digital bank can structure its Midaz deployment. The bank offers checking accounts, savings, and Pix transfers. ``` Organization: "Neobank S.A." │ ├── Ledger: "Main Ledger (BRL)" │ │ │ ├── Segments │ │ ├── "Standard" (default tier) │ │ ├── "VIP" (premium customers) │ │ └── "Business" (corporate accounts) │ │ │ ├── Account Types │ │ ├── "checking" → everyday transactions │ │ ├── "savings" → interest-bearing deposits │ │ ├── "settlement" → internal clearing │ │ └── "fee-revenue" → bank fee collection │ │ │ ├── Internal Accounts │ │ ├── Settlement Account (clearing for Pix, TED) │ │ ├── Fee Revenue Account │ │ └── Interest Expense Account │ │ │ └── Customer Portfolios │ ├── Portfolio: "Maria Silva" │ │ ├── Checking Account (BRL) — Segment: VIP │ │ └── Savings Account (BRL) — Segment: VIP │ │ │ └── Portfolio: "Tech Corp Ltda." │ ├── Main Checking (BRL) — Segment: Business │ ├── Payroll Account (BRL) — Segment: Business │ └── Expense Account (BRL) — Segment: Business │ └── Ledger: "Treasury" └── FX and interbank positions ``` ### How a Pix transfer flows through this structure **1. Transaction initiated** Maria sends R\$ 500 via Pix from her checking account. **2. Transaction Route validates** The "Pix Out" Transaction Route applies. It defines a debit from Maria's checking account and a credit to the Settlement Account. It can also add a fee operation. **3. Operations execute** Midaz creates four operations atomically. It debits R\$ 500 from Maria and credits R\$ 500 to Settlement. It also debits a R\$ 0.50 fee from Maria and credits R\$ 0.50 to Fee Revenue. **4. Event published** When streaming is enabled, `STREAMING_BROKERS` and the Ledger CloudEvents source are configured, and the transaction reaches an eligible lifecycle state, Midaz emits a transaction lifecycle CloudEvent. The bank's notification service reads the event and sends Maria a push notification. **5. External settlement** An external integration reconciles the Settlement Account with the central bank's Pix infrastructure. ### Decision guide: when to split ledgers | Scenario | Recommendation | | :- | :- | | Single currency, single business unit | One ledger is enough | | Multiple currencies with occasional FX | One ledger, separate asset accounts per currency | | Separate legal entities or subsidiaries | One ledger per entity, under separate organizations | | Regulatory requirement for data isolation | Separate ledgers, or separate organizations for full isolation | | Treasury and trading operations | Dedicated treasury ledger alongside operational ledger | > [!TIP] > > When in doubt, start with a single ledger. You can split later as operational complexity grows. If you split too early, you add orchestration overhead without clear benefit. # Accounting Routes Source: https://docs.lerian.studio/en/products/midaz/transaction-routing-entities Validate every Transaction with Accounting Routes and Operation Routes. Enforce structure and business rules before recording any movement. Accounting Routes are Midaz's two-layer validation system for financial transactions. **Accounting Routes** define the full transaction pattern. **Operation Routes** validate each operation inside that pattern. Together they keep every transaction structurally correct and compliant with your business rules. > [!NOTE] > > **Naming:** The Lerian Console and product documentation call this concept **Accounting Routes**. In the API and SDKs, the `transactionRoute` resource represents the transaction-level route, with `transaction-route` endpoints. The two terms refer to the same thing. * **Accounting Routes** define the complete structure of a transaction: the required sequence of operations that forms a valid financial event. * **Operation Routes** define the rules for each operation (or "leg") of that transaction. Each rule sets the expected account type or specific account, the accounting annotation, and the debit or credit side. When you enable route validation on a Ledger, Midaz validates each transaction in two layers. The Accounting Routes layer checks that the overall structure matches the predefined pattern. The Operation Routes layer checks that each component meets account requirements and business rules. If any part of the transaction fails these checks, Midaz rejects it before it records the transaction. > [!NOTE] > > You define the validation patterns through Operation Routes and Accounting Routes. ## What are Accounting Routes for? *** Accounting Routes provide structured control over your financial operations by separating transaction logic from business code. Instead of hardcoding validation rules in your application, you configure reusable patterns. These patterns make every financial movement follow your organization's requirements. These entities link Transactions and Operations from the Midaz ledger to higher-level abstractions. These abstractions help you integrate specialized plugins and external systems, especially for accounting and treasury. The structured annotations and classifications create a standardized vocabulary that other components can understand and use. This approach delivers: * **Consistency**: All transactions follow predefined structures regardless of where they originate. * **Flexibility**: Adapt your ledger design to match your business needs without code changes. * **Integrity**: Automatic validation prevents malformed transactions from affecting your ledger. * **Maintainability**: Centralized configuration makes it easier to update financial rules as your business evolves. * **Interoperability**: Business-semantic fields let you integrate accounting plugins and external financial systems. ## Working with Accounting Routes *** To use Accounting Routes, you complete a one-time setup and then execute transactions. ### Initial Setup #### 1. Configure Ledger for transaction route validation To activate transaction route validation for a specific Ledger, enable the validation settings through the [Ledger Settings API](/en/products/midaz/ledgers#ledger-settings). This controls whether transactions in that Ledger must comply with your configured routes. ```json PATCH /v2/organizations/{organization_id}/ledgers/{ledger_id}/settings theme={null} { "accounting": { "validateRoutes": true, "validateAccountType": true } } ``` * **`validateRoutes`**: When enabled, every transaction must reference a valid transaction route. * **`validateAccountType`**: When enabled, Midaz rejects an account whose `type` is not a registered Account Type. This gates **account creation**, not transactions. `validateRoutes` enforces the `account_type` rule on an Operation Route, independent of this flag. #### 2. Create Operation Routes Create Operation Routes that define validation rules and behavior for individual transaction components. **Key fields:** * **title**: Brief label that identifies the operation route. * **code** (deprecated): a legacy external reference kept for backward compatibility. The engine does **not** write it to operations. Instead, it records the resolved rubric's `code` (from `accountingEntries`) as `routeCode` on each operation. * **description**: Optional detailed explanation. * **metadata**: Key-value pairs for business context and custom categorization. * **operationType**: The accounting direction for this route (`source`, `destination`, or `bidirectional`). * `source`: identifies accounts where funds originate (debit side). * `destination`: identifies accounts that receive funds (credit side). * `bidirectional`: applies to both sides of the transaction, as both source and destination. * **account**: Optional validation rules that set a required account type or a specific account. * **ruleType**: Type of account validation rule (`account_type`, `alias`). * **validIf**: The expected value that must match for validation to pass. * **accountingEntries**: Optional accounting entries for each action type. With route validation enabled, a transaction can use the route only for the actions that have an entry. See [Accounting Entries](#4-configure-accounting-entries-actions) below. Configure account rules based on your needs: **Option A: No Account Rule** If you don't need account validation for the operation route, omit the account object: ```json JSON theme={null} { "title": "Fee Collection", "description": "Operation route for collecting service fees from user transactions", "metadata": { "businessUnit": "payments", "category": "revenue" }, "operationType": "source" } ``` **Option B: Account Validation Rule** If you need account validation for the operation, configure account rules based on your ledger setup: * **Target Specific Account** Validate against a specific account using its alias. ```json JSON theme={null} { "title": "Fee Revenue Collection", "description": "Operation route for crediting collected fees to revenue account", "metadata": { "businessUnit": "payments", "category": "revenue" }, "operationType": "destination", "account": { "ruleType": "alias", "validIf": "@external/BRL" }, "accountingEntries": { "direct": { "credit": { "code": "3.1.001", "description": "Fee revenue" } } } } ``` * **Target Account Type** Validate against specific account types. ```json JSON theme={null} { "title": "User Cashout Fee", "description": "Operation route for collecting fees from user cashout transactions", "metadata": { "businessUnit": "payments", "category": "fee" }, "operationType": "source", "account": { "ruleType": "account_type", "validIf": ["user_wallet", "asset"] }, "accountingEntries": { "direct": { "debit": { "code": "1.1.1.001", "description": "User wallet fee" } } } } ``` **Option C: With Accounting Entries** Attach accounting entries directly to the operation route through the `accountingEntries` field. This field maps each transaction-lifecycle stage to the correct double-entry accounting codes. See [Configure Accounting Entries (Actions)](#4-configure-accounting-entries-actions) below for the full action-type model, the debit/credit requirements, and the validation matrix. A route with accounting entries configured: ```json JSON theme={null} { "title": "Pix Cash-out - Current Account", "description": "Operation route for sending Pix payments from current account", "operationType": "source", "accountingEntries": { "direct": { "debit": { "code": "1.1.001", "description": "Cash - Available funds" }, "credit": { "code": "3.1.001", "description": "Service Revenue" } }, "hold": { "debit": { "code": "1.1.002", "description": "Clearing Values" }, "credit": { "code": "2.1.001", "description": "Pending Obligations" } }, "commit": { "debit": { "code": "2.1.001", "description": "Pending Obligations" }, "credit": { "code": "3.1.001", "description": "Service Revenue" } }, "cancel": { "debit": { "code": "2.1.001", "description": "Pending Obligations" }, "credit": { "code": "1.1.002", "description": "Clearing Values" } } }, "account": { "ruleType": "alias", "validIf": "@current_account" }, "metadata": { "channel": "pix" } } ``` > [!NOTE] > > The `operationType` field also supports `bidirectional`. A bidirectional route operates in both directions. Use it for routes that both send and receive, or for operations that you may need to reverse. #### 3. Build Accounting Routes Complete your setup by combining Operation Routes into Accounting Routes (the `transactionRoute` resource in the API). These define your complete transaction patterns. Each pattern maps how operations work together to form balanced financial events that match your business processes. An Accounting Route needs at least one source and one destination Operation Route (errors `0153` and `0154`). A bidirectional route counts as both. On `/v2`, an Accounting Route can also link optional Operation Routes in `optionalOperationRoutes`. A transaction may leave an optional route unused, for example a fee route when no fee applies. Midaz validates a leg that uses it like any other leg. Only the routes in `operationRoutes` count toward the source and destination rule. * A route in both lists returns `0541`. * An optional route with a `crossLedger` entry returns `0256`. * A v2 update applies each list as a JSON merge patch: an absent or `null` list keeps the stored links, and `[]` removes them. * `/v1` refuses `optionalOperationRoutes`. ```json JSON theme={null} { "title": "Fee Transaction", "description": "Complete transaction for collecting fees from user cashout operations", "metadata": { "transactionType": "cashout_fee", "businessFlow": "withdrawal_processing" }, "operationRoutes": [ "0197e6aa-1695-734a-a8c3-8c79e0ad32c2", "0197e675-37cc-71d7-96c2-f58000f33aa0" ] } ``` #### 4. Configure Accounting Entries (Actions) Each Operation Route can include **Accounting Entries**. These structured rubrics define how Midaz records debit and credit entries for each transactional event: `direct`, `hold`, `commit`, `cancel`, and `revert`. Four supplementary keys (`overdraft`, `block`, `unblock`, and `crossLedger`) describe accounting impact but are **not** valid transaction-route actions. The entries determine the `routeCode` and `routeDescription` annotations on each operation. The `accounting.validateRoutes` setting in the [Ledger Settings](/en/products/midaz/ledgers#ledger-settings) controls this behavior. When you enable it, Midaz rejects a transaction whose legs do not match the entries of its Accounting Route. When you disable it, Midaz resolves no rubric, and `routeCode` stays empty. > [!NOTE] > > The **[Accounting Entries](/en/products/midaz/accounting-entries)** page documents the full model in detail. This includes the accounting-entry actions, the debit/credit requirements per operation type, the graceful and strict validation modes, and configuration examples. This section covers only how rubrics attach to Operation Routes. At the route level, you supply accounting entries through the `accountingEntries` block. See **Option C** under [Create Operation Routes](#2-create-operation-routes) above. Each action takes one entry with a `debit` rubric, a `credit` rubric, or both, depending on the route's `operationType`: * **Source** routes require the **debit** rubric. * **Destination** routes require the **credit** rubric. * **Bidirectional** routes require **both** debit and credit rubrics. ##### Accounting entries validation matrix Not every combination of `operationType` and action is valid. Midaz enforces a strict validation matrix when you create or update an Operation Route. If the rules do not match, Midaz rejects the request before it persists the route. An invalid combination returns error `0166` (field required) or `0162`/`0165` (scenario not allowed for the direction). **source** | Action | Debit | Credit | Notes | | :- | :- | :- | :- | | `direct` | Required | Optional | Standard one-step transaction at origin | | `hold` | Required | Required | Reserves funds (moves available → on_hold) | | `commit` | Required | Optional | Finalizes a two-phase transaction | | `cancel` | Required | Required | Releases reserved funds (moves on_hold → available) | | `revert` | — | — | Not allowed (error `0165`). Use `bidirectional` instead | **destination** | Action | Debit | Credit | Notes | | :- | :- | :- | :- | | `direct` | Optional | Required | Standard one-step transaction at destination | | `hold` | — | — | Not allowed (error `0162`) | | `commit` | Optional | Required | Finalizes a two-phase transaction | | `cancel` | — | — | Not allowed (error `0162`) | | `revert` | — | — | Not allowed (error `0165`). Use `bidirectional` instead | **bidirectional** | Action | Debit | Credit | Notes | | :- | :- | :- | :- | | `direct` | Required | Required | Both sides of the double entry | | `hold` | Required | Required | Both sides of the double entry | | `commit` | Required | Required | Both sides of the double entry | | `cancel` | Required | Required | Both sides of the double entry | | `revert` | Required | Required | Only direction that supports revert | > [!CAUTION] > > If an entry has neither `debit` nor `credit`, Midaz rejects it, regardless of operation type or action. **Additional rules:** * **Reserve group atomicity**: On `source` and `bidirectional` routes, if you define `hold`, you must also define `commit` and `cancel` (and vice versa). These three actions form an atomic group there. You can't configure one without the others (error `0163`). On `destination` routes, `hold` and `cancel` are not allowed (error `0162`), so `commit` can be configured without them. It still requires `direct` per the rule below. * **Direct is mandatory**: If you define `hold`, `commit`, `cancel`, `revert`, or `overdraft`, you must also define `direct` (error `0164`). It is the baseline entry for the operation route. * **`overdraft` requires both rubrics** on every `operationType`, including `source` and `destination`. * **`block` and `unblock` mirror `direct`**: debit on a `source` route, credit on a `destination` route, both on `bidirectional`. * **`crossLedger`** classifies the External Account legs that Midaz adds when a transaction spans Ledgers. It requires both rubrics and a `bidirectional` route (error `0162`) with no other entry (error `0256`). An Accounting Route links at most one such route. * Any key outside these nine is rejected with error `0053` (Unexpected Fields). > [!TIP] > > When you design your operation routes, start with the `direct` action. Add `hold`/`commit`/`cancel` only if you need two-phase transaction support. Add `revert` only on `bidirectional` routes. ### Ongoing Operations #### 5. Execute Validated Transactions With your routing configuration in place, you can now submit transactions. In the transaction request, set **`routeId`** to the ID of the Accounting Route you created, and **`operationRouteId`** on each leg. Midaz then validates the transaction against your routing patterns. For the Accounting Route and Operation Routes configured above, Midaz composes the following validation structure: ```bash text theme={null} Transaction Route: "Fee Transaction" (ID: 5656daa5-5b2a-4637-955f-e43bafceaf5d) ├── Operation Route 1: "User Cashout Fee" (ID: 0197e6aa-1695-734a-a8c3-8c79e0ad32c2) │ ├── Type: source │ ├── Account Rule: account_type ["user\_wallet", "asset"] │ └── Validates: source operations in transactions └── Operation Route 2: "Fee Revenue Collection" (ID: 0197e675-37cc-71d7-96c2-f58000f33aa0) ├── Type: destination ├── Account Rule: alias "@external/BRL" └── Validates: destination operations in transactions ``` A matching request to [create a direct transaction](/en/reference/products/midaz/v2/create-transaction-direct): ```json JSON expandable theme={null} { "routeId": "5656daa5-5b2a-4637-955f-e43bafceaf5d", "description": "Cashout fee collection transaction", "asset": "BRL", "amount": "10", "debits": [ { "alias": "@user_wallet_123", "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "ledgerId": "9c858901-8a57-4791-81fe-4a34d4dd8ab5", "amount": "10", "description": "Fee debit from user wallet", "operationRouteId": "0197e6aa-1695-734a-a8c3-8c79e0ad32c2" } ], "credits": [ { "alias": "@external/BRL", "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "ledgerId": "9c858901-8a57-4791-81fe-4a34d4dd8ab5", "amount": "10", "description": "Fee credit to revenue account", "operationRouteId": "0197e675-37cc-71d7-96c2-f58000f33aa0" } ] } ``` When you submit this transaction, Midaz checks that the `@user_wallet_123` account has one of the account types in the `account_type` rule. It also checks that the credited account is `@external/BRL`. ##### Route fields on operations When you enable route validation and configure accounting entries, every processed operation includes two extra fields. Midaz populates these fields from the matched rubric: * **routeCode**: the `code` of the resolved `AccountingRubric` for that operation's action and direction. * **routeDescription**: the description of the resolved accounting rubric. Midaz populates it alongside `routeCode`. These fields link each operation to its accounting classification. Downstream systems such as [Reporter](/en/products/reporter/what-is-reporter) can then produce accurate financial reports without extra lookups. ## Managing Operation and Accounting Routes *** To configure your Operation Routes, use the following endpoints: * [Create an Operation Route](/en/reference/products/midaz/v2/create-operation-route): define a new accounting rule for your operations. * [List Operation Routes](/en/reference/products/midaz/v2/list-operation-routes): view all configured Operation Routes. * [Retrieve an Operation Route](/en/reference/products/midaz/v2/get-operation-route-by-id): get detailed information on a specific Operation Route. * [Update an Operation Route](/en/reference/products/midaz/v2/update-operation-route): modify existing accounting rules. * [Delete an Operation Route](/en/reference/products/midaz/v2/delete-operation-route): remove an outdated or unused Operation Route. To configure your Accounting Routes (the `transactionRoute` resource in the API), use the following endpoints: * [Create a Transaction Route](/en/reference/products/midaz/v2/create-transaction-route): define new routing logic to connect transactions to accounting operations. * [List Transaction Routes](/en/reference/products/midaz/v2/list-transaction-routes): view all configured Transaction Routes. * [Retrieve a Transaction Route](/en/reference/products/midaz/v2/get-transaction-route-by-id): get details of a specific Transaction Route. * [Update a Transaction Route](/en/reference/products/midaz/v2/update-transaction-route): modify existing routing criteria. * [Delete a Transaction Route](/en/reference/products/midaz/v2/delete-transaction-route): remove routes that are no longer applicable. Routes belong to the Organization. A transaction in any Ledger of the Organization can use a route, whatever Ledger you created it under. To create a route without a Ledger, use [Create an organization Operation Route](/en/reference/products/midaz/v2/create-organization-operation-route) and [Create an organization Transaction Route](/en/reference/products/midaz/v2/create-organization-transaction-route). # Transactions Source: https://docs.lerian.studio/en/products/midaz/transactions Record financial events with Midaz double-entry Transactions: multiple Balances, debits, credits, and full traceability across Accounts. A **Transaction** in Midaz records a complete financial event. A transaction often uses multiple accounts and balances. Midaz runs on a double-entry accounting system that keeps every financial movement balanced. With the **multiple balances** feature, each operation specifies the account and the **balance key** to use. You can then debit or credit different logical balances of the same account (for example, `credit`, `operational`, or `collateral`). > [!NOTE] > > If you do not provide a `balanceKey`, the transaction uses the **default balance**. ## Double-entry accounting *** The double-entry system follows one principle. A posted transaction has at least one debit and one credit operation. A pending transaction records only its source side until you commit it. This structure records all financial activity and keeps your accounts balanced. Each transaction uses two kinds of entries: * **Debits** show the value received or the resources consumed. * **Credits** show the value given or the resources provided. Midaz rejects a transaction whose debits and credits do not balance. ### Example In this example, you transfer R\$1000 from one account to another. The transaction has two operations: * One operation to debit R\$1,000.00 from the source account. * One operation to credit R\$1,000.00 to the destination account. Midaz captures both entries automatically. You can view and analyze these movements through the API or Lerian Console. ## N:N Transactions (Many-to-Many) *** Traditional financial systems limit transactions to one-to-one or one-to-many relationships. Midaz supports N:N transactions. A single transaction can use multiple source and destination accounts. ### Examples * **Marketplace payout**: a single escrow account pays multiple sellers, and each seller pays a platform fee. * **Peer-to-peer with fees**: one transaction debits the payer and credits both the payee and a fee account. Midaz processes each case as a single atomic transaction. It debits and credits all parties together. ## Atomicity and integrity *** Transactions are atomic. **Either all operations succeed, or none do.** Partial financial events do not occur. If any part of a transaction fails validation (for example, one account has insufficient funds), Midaz does not apply the transaction. The ledger stays consistent. ## Transaction source *** A transaction in Midaz can start from a single source or from multiple sources. > [!CAUTION] > > The sum of the values in `source` must equal the value after `send`. It must also equal the sum of the values in `distribute`. ### Single source In a single-source transaction, Midaz takes the amount from one source account. You can also name a specific balance. #### Example In this example (*Figure 1*): * Midaz takes BRL 30.00 from `@account1` (balance `credit`). * It sends 100% to `@destinationAccount1` (balance `operational`) ![Single-source transaction moving BRL 30.00 from one source account to a single destination account](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/single-source.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=8867866e614ebd29f2abc801b03ad894) Figure 1. Example of a single source transaction. **Code examples** ```json JSON Example expandable theme={null} { "description": "single source transaction", "send": { "asset": "BRL", "value": "30.00", "source": { "from": [ { "accountAlias": "@account1", "balanceKey": "credit", "amount": { "asset": "BRL", "value": "30.00" } } ] }, "distribute": { "to": [ { "accountAlias": "@destinationAccount1", "balanceKey": "operational", "share": { "percentage": 100 } } ] } } } ``` ### Multi-source In a multi-source transaction, Midaz draws funds from multiple accounts or balances. #### Example In this example (*Figure 2*): * Midaz sends BRL 30.00 to the destination account (`@destinationAccount1`). * BRL 15.00 from `@account1` (balance `default`). * BRL 15.00 from `@account2` (balance `investment`). * The destination account receives 100% of the amount. ![Multi-source transaction where BRL 30.00 is drawn from two source accounts and sent to a single destination account](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/multi-source.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=a662de8e32affc1346da13432daabcd8) Figure 2. Example of a multi-source transaction. **Code examples** ```json JSON Example theme={null} { "description": "multi-source transaction", "send": { "asset": "BRL", "value": "30.00", "source": { "from": [ { "accountAlias": "@account1", "balanceKey": "default", "amount": { "asset": "BRL", "value": "15.00" } }, { "accountAlias": "@account2", "balanceKey": "investment", "amount": { "asset": "BRL", "value": "15.00" } } ] }, "distribute": { "to": [ { "accountAlias": "@destinationAccount1", "share": { "percentage": 100 } } ] } } } ``` ## Transaction destination *** Like sources, destinations can be single or multiple. ### Single destination In a single-destination transaction, Midaz sends the amount to only one destination account. #### Example In this example (*Figure 3*): * Midaz takes BRL 30.00 from an external account (`@external/BRL`). * It sends 100% to the destination account (`@destinationAccount1`). ![Single-destination transaction moving BRL 30.00 from an external account to one destination account](https://mintcdn.com/lerian-49cb71fc/Cb_meREQqa6luqbJ/images/en/d2/single-destination.svg?fit=max\&auto=format\&n=Cb_meREQqa6luqbJ\&q=85\&s=c027a71eaa987cc22a90171bbb326cc2) Figure 3. Example of a single destination transaction. **Code examples** ```json JSON Example theme={null} { "description":"single destination transaction", "send":{ "asset":"BRL", "value":"30.00", "source":{ "from":[ { "accountAlias":"@external/BRL", "amount":{ "asset":"BRL", "value":"30.00" } } ] }, "distribute":{ "to":[ { "accountAlias":"@destinationAccount1", "share":{ "percentage":100 } } ] } } } ``` ### Multi-destination In a multi-destination transaction, Midaz divides the amount among multiple destination accounts. You can distribute values by shares, fixed amounts, or the remaining amount. #### Example In this example (*Figure 4*): * Midaz takes BRL 100 from the source account (`@account1`). * 38% of the amount goes to account 2 (`@account2`). * 50% goes to account 3 (`@account3`). * A fixed BRL 2.00 goes to account 4 (`@account4`). * The remaining amount goes to account 5 (`@account5`). ![Multi-destination transaction splitting BRL 100.00 from one source account across five destination accounts by percentage and fixed amounts](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/multi-destination.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=fc0a0dff5a1a99b2ffda26988f3fed47) Figure 4. Example of a multi-destination transaction. **Code example** ```json JSON Example theme={null} { "description":"multi-destination transaction", "send":{ "asset":"BRL", "value":"100.00", "source":{ "from":[ { "accountAlias":"@account1", "amount":{ "asset":"BRL", "value":"100.00" } } ] }, "distribute":{ "to":[ { "accountAlias":"@account2", "share":{ "percentage":38 } }, { "accountAlias":"@account3", "share":{ "percentage":50 } }, { "accountAlias":"@account4", "amount":{ "asset":"BRL", "value":"2.00" } }, { "accountAlias":"@account5", "remaining":"remaining" } ] } } } ``` ## Multi-source and multi-destination *** These transactions use multiple sources and multiple destinations. They are useful for cases like a crowdfunding campaign. Midaz pools the contributions and distributes them among multiple recipients. #### Example In this example (*Figure 5*): * The donation is BRL 4,000.00. Midaz takes it from four different accounts. * 25% comes from account 1 (`@account1`). * 25% comes from account 2 (`@account2`). * 40% comes from account 3 (`@account3`) * 10% comes from account 4 (`@account4`). * Midaz distributes the donations to four separate accounts. Each account receives a 25% share of the total. ![Multi-source and multi-destination transaction drawing BRL 4,000.00 from four accounts and distributing it evenly across four destination accounts](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/multi-source-destination.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=bc6796fc6414907407362317958eb382) Figure 5. Example of a multi-source and multi-destination transaction. **Code examples** ```json JSON Example theme={null} { "description":"multi-source and multi-destination transaction", "send":{ "asset":"BRL", "value":"4000.00", "source":{ "from":[ { "accountAlias":"@account1", "share":{ "percentage":25 } }, { "accountAlias":"@account2", "share":{ "percentage":25 } }, { "accountAlias":"@account3", "share":{ "percentage":40 } }, { "accountAlias":"@account4", "share":{ "percentage":10 } } ] }, "distribute":{ "to":[ { "accountAlias":"@donation1", "share":{ "percentage":25 } }, { "accountAlias":"@donation2", "share":{ "percentage":25 } }, { "accountAlias":"@donation3", "share":{ "percentage":25 } }, { "accountAlias":"@donation4", "share":{ "percentage":25 } } ] } } } ``` ## Transaction statuses *** Every transaction in Midaz has a status. The status reflects its current stage in the lifecycle. You need these statuses to design transaction flows, configure event consumers, and read ledger data. | Status | What it means | Affects balances? | How it's created | | :- | :- | :- | :- | | `CREATED` | Midaz posted the transaction at once. Only the create response carries this status. Midaz stores the transaction as `APPROVED`. | Yes | Create response of a transaction that is neither pending nor an annotation, reversals included | | `APPROVED` | The transaction completed successfully. Funds have been moved between accounts. | Yes | Stored status of a `CREATED` transaction, or commit of a `PENDING` transaction | | `PENDING` | A two-phase transaction is awaiting confirmation. Funds are reserved in `on_hold` but not yet transferred. | Yes (reservation) | [Create a Transaction](/en/reference/products/midaz/v1/create-transaction-json) with `"pending": true` | | `CANCELED` | A two-phase transaction was canceled. Reserved funds are released back to `available`. | Yes (release) | [Cancel a Pending Transaction](/en/reference/products/midaz/v2/cancel-transaction) | | `NOTED` | An annotation transaction recorded in the ledger without affecting balances. Operations preserve the double-entry structure but all balance fields are zeroed. | No | [Create a Transaction Annotation](/en/reference/products/midaz/v1/create-transaction-annotation) | > [!TIP] > > Use the `NOTED` status to import legacy transactions, record audit trails, and log compliance events. It fits any case where the transaction must exist in the ledger but the balances settled elsewhere already. ### Status transitions Transactions follow predictable paths through these statuses: * **Standard flow:** → `APPROVED` (single step) * **Two-phase flow:** → `PENDING` → `APPROVED` (commit) or `CANCELED` (cancel) * **Annotation flow:** → `NOTED` (terminal, no transitions) > [!NOTE] > > Once a transaction reaches `NOTED` or `CANCELED`, it cannot transition further. Both are terminal statuses. ## Transaction flow *** When a transaction starts, Midaz validates: * The accounts involved. * The specified balances (`balanceKey`, or `default` if not given). * Permissions (`allowSending`, `allowReceiving`). * Sufficient available funds in the selected balance. External accounts skip this check, and a balance that allows overdraft can draw into [overdraft](/en/products/midaz/balance-overdraft). If validation passes and the transaction is neither pending nor an annotation, Midaz transfers the amount **immediately**. It moves the amount from the source account to the destination account, from the available balance. On success, the transaction status becomes `APPROVED`. > [!CAUTION] > > Initiate this type of transaction **only** if you intend to commit it to the ledger immediately. For transactions that need validation or approval first, use the `pending` flag to create a **Two-Phase Transaction**. ## Two-Phase Transaction *** In this flow, Midaz creates the transaction with status `PENDING`. Midaz does not move funds right away. Instead, it reserves the amount in the correct balance (`balanceKey`, or `default` if you do not provide one). * The destination balance does not change until you commit. * You must explicitly `commit` to execute the transfer, or `cancel` to release the funds. * Midaz refuses an external account that you send as a source of a pending transaction (error `0098`). > [!TIP] > > The Two-Phase Transaction feature supports [Flowker](/en/products/flowker/what-is-flowker). You reserve funds at the start of a workflow and run validations later. In *Figure 6*, you can see an example of a two-phase transaction with anti-fraud. ![Two-phase transaction in an anti-fraud workflow, reserving funds first and committing or cancelling them after validation](https://mintcdn.com/lerian-49cb71fc/n1OcqvSm2bbEsplZ/images/en/d2/two-phase-transaction.svg?fit=max\&auto=format\&n=n1OcqvSm2bbEsplZ\&q=85\&s=afc76d6fc49f77f27bce2c19c1e687b8) Figure 6. Anti-fraud workflow example ### Two-Phase Transaction flow #### 1. Create a Two-Phase Transaction * Use the [Create a Transaction using JSON](/en/reference/products/midaz/v1/create-transaction-json) endpoint with `"pending": true`. Midaz validates accounts, the specified balances (`balanceKey`), permissions (`allowSending`, `allowReceiving`), and available funds. If valid: * Midaz reserves funds in the correct balance. * Midaz sets the transaction status to `PENDING`. * Midaz stores the metadata. #### 2. Commit or cancel the pending transaction * **Commit**: finalizes the transaction. Funds move from `on_hold` to the destination balance. * Use the [Commit a Pending Transaction](/en/reference/products/midaz/v2/commit-transaction) endpoint. * Status: `APPROVED`. * **Cancel**: releases the reserved funds back to `available` in the same balance. * Use the [Cancel a Pending Transaction](/en/reference/products/midaz/v2/cancel-transaction) endpoint. * Status: `CANCELED`. If you repeat a commit or cancel after it succeeds, Midaz answers `0486` for up to 300 seconds and `0099` after that. To learn the outcome, read the transaction status. ## Past Transactions *** Midaz also supports past transactions. Institutions can import legacy financial events and keep historical accuracy. * Use the optional `transactionDate` field to set the original date of the transaction. * `transactionDate` does not change balance history. Balance history uses the time when Midaz records the transaction. * Transactions created through the [Create a Transaction Annotation](/en/reference/products/midaz/v1/create-transaction-annotation) endpoint validate structure but do **not** affect balances. They suit audits, compliance, and imports where balances must stay unchanged. ### Example ```json theme={null} { "description": "past transaction example", "transactionDate": "2025-01-01T13:38:31.064Z", "send": { "asset": "BRL", "value": "1000", "source": { "from": [ { "accountAlias": "@external/BRL", "amount": { "asset": "BRL", "value": "1000" } } ] }, "distribute": { "to": [ { "accountAlias": "@account1_BRL", "amount": { "asset": "BRL", "value": "1000" } } ] } } } ``` ## Transactions with no financial impact *** Midaz can create transactions that it records in the ledger but that do not affect account balances. These transactions keep structural integrity and leave balances unchanged. This feature is useful when you need to: * Import legacy transactions but keep balances unchanged. * Record audit or compliance events. * Add business operations that the ledger must track but that do not move funds. ### How does it work? When you create a transaction without financial impact: * Midaz stores the `balance` and `balanceAfter` fields as 0 to preserve double-entry validation. * Each operation has a `balanceAffected` (boolean) field: * true → the operation affects the account balance. * false → Midaz records the operation in the ledger but does not change balances. > [!CAUTION] > > Even when Midaz updates no balances, it enforces double-entry rules. This keeps consistency across all transactions in the ledger. #### Example ```json theme={null} { "description": "annotation example", "transactionDate": "2025-01-01T13:38:31.064Z", "send": { "asset": "BRL", "value": "1000", "source": { "from": [ { "accountAlias": "@external/BRL", "amount": { "asset": "BRL", "value": "1000" } } ] }, "distribute": { "to": [ { "accountAlias": "@account1_BRL", "amount": { "asset": "BRL", "value": "1000" } } ] } } } ``` #### Related endpoint * [Create a Transaction Annotation](/en/reference/products/midaz/v1/create-transaction-annotation): record a transaction without financial impact in the ledger. ## Real-time event publishing *** Midaz publishes transaction lifecycle events through its Kafka-compatible streaming surface. You can track your transactions as they change. After you enable it, Midaz emits `transaction.posted`, `transaction.committed`, `transaction.canceled`, and `transaction.reverted`. A new `PENDING` transaction and a `NOTED` transaction emit no event. A transaction that spans Ledgers also emits group events; see [Event publisher](/en/products/midaz/event-publisher). For more about how to publish and consume transaction events, see the [Event publisher](/en/products/midaz/event-publisher) page. ## Inflows, outflows, and external accounts *** Midaz uses a double-entry ledger. All value that enters or leaves the system must pass through one special account: the **External Account**. Midaz represents this account as `@external/{{assetCode}}`. It is the bridge between Midaz and the external financial world (banks, PSPs, payment rails, and so on). ### Bringing funds into Midaz When you first initialize the ledger, all accounts, including `@external`, start with a zero balance. To reflect real-world balances, such as institutional funds held outside Midaz, you must initiate a transaction that injects funds into Midaz accounts and debits the external account. This is the only way to bring funds into Midaz. ### Inflows – Adding value into the Ledger To credit an internal account from outside the ledger: * **Source**: `@external/{{assetCode}}` (e.g., `@external/BRL`). * **Destination**: One or more internal accounts (e.g., `@organization.main`). **Example: First deposit into the Ledger** Your institution holds R\$10,000 in a real-world bank and wants to bring it into Midaz. You create a transaction: | Source | Destination | Amount | | :- | :- | :- | | @external/BRL | @accountA | BRL 10,000 | This debits the external account and credits your internal account. The external account balance represents the total amount your organization brought into the ledger. ### Outflows – Moving value out of the Ledger To move value from the ledger to an external destination: * **Source**: One or more Midaz accounts. * **Destination**: `@external/{{assetCode}}`. **Example: A Pix transfer from Ledger to an external bank** | Source | Destination | Amount | | :- | :- | :- | | @accountA | @external/BRL | BRL 1,000 | This debits `@accountA` and credits the external account. Your system then transfers the funds to the recipient through SPI or another integration. ### Behavior and balance rules > [!NOTE] > > All value that moves between the outside world and the Midaz ledger must go through the external account. > > Nothing enters or leaves the system without a formal transaction. ## Setting a custom transaction date *** The `transactionDate` field lets you set a custom date for a transaction, independent of when you submit it to the API. * **Optional.** If you omit it, Midaz uses the current timestamp. * **Accepted formats:** * ISO 8601 with timezone: `2026-01-15T10:30:00Z` * ISO 8601 without timezone: `2026-01-15T10:30:00` * Date only: `2026-01-15` * **Constraint:** you cannot use a future date. A future date returns error `0121`. * **Constraint:** you cannot use it on `PENDING` transactions. A `transactionDate` with `"pending": true` returns error `0122`. ### Use cases * Record transactions that occurred in the past (for example, same-day corrections) * Import historical financial data into a new ledger * Reconcile with external systems that use a different posting date ## Transaction Routes *** The **Transaction Routes** API enables structured, validated transaction processing in Midaz. > [!NOTE] > > The Lerian Console and product documentation call this concept **Accounting Routes**. The API resource and endpoints keep the `transactionRoute` / Transaction Routes name. Both refer to the same transaction-level route. The Transactions API runs financial events: debits and credits between accounts. Transaction Routes define templates for **how** to structure and validate these events. This keeps them consistent and correct. The Transaction Routes API is the validation layer. It makes business transactions follow predefined patterns and keep a proper financial structure. For example, a fee, a deposit, or a payout may need different account types, validation rules, and structures. Instead of handling validation separately for each transaction, you configure predefined rules. These rules tell Midaz: "*When the user submits this type of transaction, validate it against these account requirements and structure patterns.*" Each Transaction Route combines multiple **Operation Routes**. An Operation Route defines one component of a transaction. It sets the account requirements, the direction (source, destination, or bidirectional), and the validation rules for each "leg" of the financial event. > [!WARNING] > > Do not use the `route` field in v1 `from` and `to` entries. Use `routeId` instead. `routeId` accepts a UUID that references an Operation Route created through the Operation Routes API. Midaz accepts `route` but does not use it in validation. ### What you do with Transaction Routes With **Transaction Routes**, you: * Keep a consistent transaction structure across your application. * Validate financial events against predefined patterns. * Configure transaction templates without code changes. * Maintain data integrity through structured validation. ## Initiating a transaction *** > [!WARNING] > > When you create transactions through the API, always implement **idempotency** to prevent duplicate processing. Midaz provides built-in idempotency support through the `X-Idempotency` header. Validate the `X-Idempotency-Replayed` response header to tell new transactions from cached replays. See [Retries and idempotency](/en/reference/retries-idempotency) for details. Use the JSON transaction API to initiate a transaction. ### JSON request shape in v2 The v2 [`direct`](/en/reference/products/midaz/v2/create-transaction-direct), [`hold`](/en/reference/products/midaz/v2/create-transaction-hold), [`block`](/en/reference/products/midaz/v2/create-transaction-block), and [`unblock`](/en/reference/products/midaz/v2/create-transaction-unblock) endpoints share one body. The required `debits` and `credits` arrays hold the legs of each side. The legs of each side must sum to the request-level `amount`. Each leg requires `alias`, `organizationId`, `ledgerId`, and exactly one value expression: `amount` or `share`. The `remaining` expression is not accepted in v2. Each array accepts 1 to 500 legs. `share.percentage` is 1–100; `share.percentageOfPercentage` is 0–100, where `0` means no narrowing. V2 create requests have a 1 MiB body limit. The optional `scheme` field names the payment scheme of the transaction, for example `PIX`, `WIRE`, `CARD`, or `CRYPTO`. Midaz accepts up to 50 letters, digits, underscores, or hyphens, and stores the value trimmed and in upper case. V2 responses and transaction events return it, and a v2 revert keeps the scheme of the original transaction. A v1 body cannot send it. ### Using the JSON endpoint * To create a transaction with JSON, use the [Create a Transaction using JSON](/en/reference/products/midaz/v1/create-transaction-json) endpoint. > [!CAUTION] > > If you need to reserve funds **before** you complete the transfer, set the `pending` field to `true` (Two-Phase Transaction flow). ## Reverting a transaction *** Midaz supports transaction reversal. You can undo an approved transaction. Midaz creates a mirror transaction that inverts the original debits and credits. This mechanism keeps full audit trails and cancels the financial impact on account balances. > [!NOTE] > > Reversal creates a **new transaction** that compensates for the original. The original transaction remains in the ledger history for complete traceability. > [!WARNING] > > Revert sends no idempotency key of its own, so Midaz derives one. Read the `X-Idempotency-Replayed` response header: `true` means you received a cached reverse rather than a freshly created one. Treat a replay as a signal to verify the origin's state before retrying. ### How does it work? When you revert a transaction, Midaz automatically: 1. **Inverts operations**: * CREDIT operations become source operations (`from`). * DEBIT operations become destination operations (`to`). 2. **Creates a new transaction** with: * Same amount and asset code. * Same description and your metadata. * Inverted operations (recipients become senders, senders become recipients). * Status: `CREATED` in the create response, stored as `APPROVED`. * `parentTransactionId` that references the original transaction. 3. **Processes the reversal** through the standard transaction flow: validation, balance updates, and history recording. ### Example **Original transaction**: * Account A (debit -100) → Account B (credit +100) **Reversal transaction created**: * Account B (debit -100) → Account A (credit +100) **Result**: * Account A returns to its previous balance (receives back the -100). * Account B returns to its previous balance (loses the +100). * Both transactions remain in the ledger history for audit purposes. * The reversal transaction includes a `parentTransactionId` that points to the original. ### Reversal restrictions Midaz enforces strict rules to keep ledger integrity. A reversal fails in these cases: #### 1. Transaction already has a reversal * Midaz allows only one reversal per transaction. * This prevents multiple reversals of the same transaction. #### 2. Transaction is already a reversal * You cannot revert a transaction that is itself a reversal. * This prevents "reversals of reversals." #### 3. Transaction status is not APPROVED * You can revert only approved transactions. * You cannot revert a transaction with status `PENDING`, `CANCELED`, or `NOTED`. #### 4. Transaction cannot be reverted * This happens when the transaction has no valid operations to invert. * A [fee debt](/en/products/midaz/fees/fee-debt) collection cannot be reverted. * A block or an unblock transaction cannot be reverted (`0539`). To undo a block, create an unblock. To undo an unblock, create a block. #### 5. An operation route on the transaction is not bidirectional * Every operation that carries a `routeId` must reference an Operation Route whose `operationType` is `bidirectional`. * A `source` or `destination` route cannot be reverted: Midaz returns error `0150` (Route Not Bidirectional). * Plan for this when you design routes. See [Accounting Routes](/en/products/midaz/transaction-routing-entities). #### 6. The fee-debt record is not complete * Midaz refuses the revert of a transaction that opened a fee debt while the record of that debt is not complete. * Midaz returns error `0529` (HTTP 409) and moves nothing. Try again later. > [!CAUTION] > > It does not reverse ON_HOLD or RELEASE operations. ### Use cases Transaction reversal helps in several operational scenarios: #### 1. Incorrect payment reversal A customer paid BRL 500 to the wrong supplier. * Revert the transaction. * Funds return to the customer's account. * The customer can start a new payment to the correct supplier. #### 2. Purchase cancellation A store processed a BRL 1,000 sale, but the customer cancels the purchase. * Revert the sale transaction. * Funds return to the customer's account. #### 3. Operational error correction An operator created a transaction with the wrong amount. * Revert the incorrect transaction. * Create a new transaction with the correct amount. #### 4. Product return A customer purchased and paid BRL 200, but returned the product. * Revert the payment transaction. * The customer receives a refund. #### 5. Integration failure compensation A transaction is approved but fails in an external system. * Revert to undo the accounting operation. * Balances return to their previous state. ## Blocking and unblocking funds *** Some scenarios require you to flag funds as **blocked** (a compliance hold, a court order, a fraud investigation) and later **release** them. Midaz supports this with two dedicated endpoints. These endpoints create transactions whose operations are typed `BLOCK` and `UNBLOCK`. These transactions accept the same body as the [Create a Transaction using JSON](/en/reference/products/midaz/v1/create-transaction-json) endpoint, with two key differences: * **Always posted immediately.** Midaz ignores the `pending` field in the request body and overrides it to `false`. Block and unblock transactions are never two-phase. They go straight to `APPROVED`. * **Operations are typed `BLOCK` or `UNBLOCK`.** This classification distinguishes them in the ledger and in operation queries. You can audit blocked-fund movements without a look at the metadata. * **No overdraft draw.** A block never draws overdraft. A block of more than the available amount returns `0018`, even when the balance allows overdraft. An unblock repays outstanding overdraft first and records that repayment as an `OVERDRAFT` operation. Midaz is agnostic about the business reason to block or unblock funds. Record the reason in the `metadata` field. > [!NOTE] > > A Block transaction records a **ledger movement** with `BLOCK`-typed operations. This differs from the balance-level controls in [Balances](/en/products/midaz/balances): permission flags (`allowSending` / `allowReceiving`) and collateral balances. Those controls restrict movement but record no transaction. Use a collateral balance for a standing operational restriction. Use a Block transaction when you need an auditable ledger entry. * Use the [Create a Block Transaction](/en/reference/products/midaz/v1/create-transaction-block) endpoint to block funds. * Use the [Create an Unblock Transaction](/en/reference/products/midaz/v1/create-transaction-unblock) endpoint to release previously blocked funds. ## Managing transactions *** You can manage your Transactions through the API or Lerian Console. ### Via API * [Create a Transaction using JSON](/en/reference/products/midaz/v1/create-transaction-json): submit a transaction directly using a JSON payload. * [Commit a pending transaction](/en/reference/products/midaz/v2/commit-transaction): finalize a reserved transaction. * [Cancel a pending transaction](/en/reference/products/midaz/v2/cancel-transaction): release reserved funds without executing. * [Revert a Transaction](/en/reference/products/midaz/v2/revert-transaction): create a reversal transaction to undo an approved transaction. * [Create an Inflow Transaction](/en/reference/products/midaz/v1/create-transaction-inflow): register incoming funds from external sources into the Ledger. * [Create an Outflow Transaction](/en/reference/products/midaz/v1/create-transaction-outflow): move funds from internal accounts to the external world. * [Create a Block Transaction](/en/reference/products/midaz/v1/create-transaction-block): flag funds as blocked with `BLOCK`-typed operations. * [Create an Unblock Transaction](/en/reference/products/midaz/v1/create-transaction-unblock): release previously blocked funds with `UNBLOCK`-typed operations. * [List Transactions](/en/reference/products/midaz/v2/get-all-transactions): view all Transactions in your workspace. * [Retrieve a Transaction](/en/reference/products/midaz/v2/get-transaction): get details of a specific Transaction. * [Update a Transaction](/en/reference/products/midaz/v2/update-transaction): edit the metadata of an existing Transaction. * [Create a Transaction Annotation](/en/reference/products/midaz/v1/create-transaction-annotation): record a transaction without financial impact in the ledger. ### Via Lerian Console You can view and create Transactions through Lerian Console. Learn more in the [Managing Transactions](/en/products/midaz/console/managing-transactions) guide. # Transactions Source: https://docs.lerian.studio/en/products/midaz/transactions-overview Overview of Transactions in Midaz: balances, overdraft, events, async processing, bulk recording, and operations that keep financial value moving safely. Transactions are where financial value moves. This section covers balances, transaction processing, events, and operations. ## Content *** * [**Balances**](/en/products/midaz/balances): The value an account holds. Balances reflect every operation over time and support multiple balance keys to segment funds within one account. * [**Balance Overdraft**](/en/products/midaz/balance-overdraft): Controlled negative balances. * [**Transactions**](/en/products/midaz/transactions): Complete financial events built on Midaz's double-entry accounting. Every transaction pairs debits and credits, and they must balance before Midaz commits it. * [**Transaction amount**](/en/products/midaz/amount): Which amount field each transaction endpoint version uses, and in which format. * [**Event publisher**](/en/products/midaz/event-publisher): Publish eligible transaction lifecycle CloudEvents through the Kafka-compatible streaming surface. * [**Receiving events from Midaz**](/en/products/midaz/receiving-midaz-events): Consume ledger events from the Kafka-compatible streaming surface or through Streaming Hub. * [**Async transaction processing**](/en/products/midaz/async-transaction-processing): How Midaz decouples transaction writes with RabbitMQ for higher throughput and lower latency. It covers sync and async modes, built-in resilience, and balance synchronization. * [**Bulk Recorder**](/en/products/midaz/bulk-recorder): Batch transaction processing that groups multiple writes into one bulk operation. It reduces database round trips and increases throughput for high-volume workloads. * [**Operations**](/en/products/midaz/operations): The smallest unit of financial activity. It is a single ledger entry, either a debit or a credit on a specific account. Operations form the building blocks of every transaction. # Midaz use cases Source: https://docs.lerian.studio/en/products/midaz/use-cases Explore Midaz use cases across banking, multi-account customers, account closure, global portfolios, academic records, and supply chain traceability scenarios. See how organizations across industries use Midaz to solve operational problems, from banking and payments to supply chain traceability and academic records. Each use case shows what changes with Midaz. It maps the platform's entities to the domain and gives step-by-step transaction examples. ### Content * [**Banking**](/en/products/midaz/midaz-in-banking): Understand how Midaz supports banking operations. * [**Midaz for multi-account customers**](/en/products/midaz/midaz-for-multi-account-customers): Model multiple accounts under a single customer, with segregated balances, rules, and statements. * [**Closing a customer account**](/en/products/midaz/closing-a-customer-account): How to close a customer account in line with BACEN account-closure rules. * [**Global portfolio**](/en/products/midaz/midaz-in-a-global-portfolio): Configure a global account structure similar to those at major banks. * [**Academic records**](/en/products/midaz/midaz-for-academic-record-management): Manage academic records for an educational institution. * [**Supply chain**](/en/products/midaz/midaz-for-supply-chain-management): Manage the supply chain for a manufacturing company. > [!TIP] > > See [Pix use cases](/en/interfaces/pix/pix-use-cases) for scenarios that combine Midaz with Pix. # Midaz in Lerian Console Source: https://docs.lerian.studio/en/products/midaz/using-midaz-in-lerian-console Manage Midaz visually inside the Lerian Console: Organizations, Ledgers, Accounts, Transactions, and plugins from a single web interface. Midaz is a product module in the [Lerian Console](/en/platform/console/about-lerian-console), the web interface for all Lerian products. Through the Console, you manage your full ledger infrastructure, from organizations and assets to transactions and plugins. > [card] [Midaz in Lerian Console](/en/products/midaz/console/midaz-module) > > Access the full documentation for using Midaz in the Lerian Console. ## Available actions *** From the Lerian Console, you can: * **Foundation**: Manage [organizations](/en/products/midaz/console/managing-organizations), [ledgers](/en/products/midaz/console/managing-ledgers-via-console), [assets](/en/products/midaz/console/managing-assets), and [account types](/en/products/midaz/console/managing-account-types) * **Accounting**: Configure [routes](/en/products/midaz/console/managing-accounting-routes) * **Accounts**: Manage [accounts](/en/products/midaz/console/managing-accounts), [holders](/en/products/midaz/console/managing-crm-holders), [aliases](/en/products/midaz/console/managing-crm-alias-accounts), [segments](/en/products/midaz/console/managing-segments), and [portfolios](/en/products/midaz/console/managing-portfolios) * **Transactions**: [View and create transactions](/en/products/midaz/console/managing-transactions) * **Fees**: Manage [fee packages](/en/products/midaz/fees/using-fee-engine-with-midaz-console) # What is Midaz? Source: https://docs.lerian.studio/en/products/midaz/what-is-midaz Learn what Midaz is: Lerian's core ledger for double-entry accounting, multi-currency operations, and audit trails. **Midaz** is Lerian's core ledger (The core financial book that records all transactions, balances, and operations for an organization. It is the single source of truth for a business unit's finances.) for financial infrastructure. It covers account management, transaction processing, and multi-currency operations. You configure your financial structure once (organizations, ledgers, accounts, and transaction rules). Midaz handles the rest: double-entry accounting (Every financial movement is recorded as at least two operations: a debit from one account and a credit to another, so the system always balances.), balance tracking, audit trails (A chronological, immutable record of every action and transaction in the system, essential for regulatory compliance and dispute resolution.), and event-driven integrations. ## Why use Midaz *** A legacy core means rigid schemas, vendor lock-in, and slow release cycles. Every new product or regulation requires months of integration work. Midaz solves this: * **Move fast**: Modular architecture lets you add products and integrations without re-architecting * **Stay compliant**: Immutable audit trails (A chronological, immutable record of every action and transaction in the system, essential for regulatory compliance and dispute resolution.) and double-entry enforcement * **Scale confidently**: Handle thousands to millions of transactions per day with horizontal scaling ## What Midaz does *** * **Central ledger**: Real-time account and transaction management with double-entry guarantees * **Multi-currency support**: Manage traditional currencies, digital assets, and loyalty points in the same ledger * **Accounting Routes**: Define reusable transaction templates (A complete transaction blueprint composed of multiple Operation Routes. It defines all the debits and credits involved in a transaction type, so each transaction of that type complies with double-entry rules. Exposed as transactionRoute in the API.) that enforce business rules automatically * **Automated triggers**: Respond to transactions in real time. Trigger notifications, compliance workflows, or analytics feeds * **Plugin ecosystem**: Extend with Pix, TED, and more, or build your own ### Built for every financial player * **Fintechs**: Run digital wallets, credit platforms, and embedded finance products * **Banks**: Modernize legacy systems incrementally without full migration risk * **Enterprises**: Simplify payments and collections ## Common use cases *** > [accordion] Digital banking > > Launch checking accounts, savings products, and instant transfers. Structure your accounts with portfolios per customer and enforce business rules through transaction routes. > [accordion] Global portfolios > > Manage multi-currency accounts for international customers. Each currency gets its own asset (A unit of value tracked in the ledger: traditional currencies (BRL, USD), digital currencies (BTC), or custom units like loyalty points. Every account is linked to exactly one asset.) accounts while portfolios (A grouping of accounts belonging to the same account holder, business unit, or purpose. It ties together checking, savings, and investment accounts for a unified view.) tie everything together for a unified customer view. > [accordion] Pix and instant payments > > Offer Pix (Brazil's instant payment system operated by the Central Bank (BACEN), for real-time transfers 24/7 between individuals, businesses, and government entities.) connectivity with automated fee management. Combine Midaz's ledger and Fees Engine with the Pix plugin to process instant payments, calculate fees, and maintain settlement accounts, all in real time. > [accordion] Marketplace payouts > > Handle complex multi-party settlements (The process of finalizing a financial transaction by transferring actual funds between institutions. Settlement accounts act as clearing points where money is held temporarily before reaching its final destination.) where a single payment splits into seller payouts, platform fees, and tax withholdings, all processed atomically as one transaction. > [accordion] Non-financial ledgers > > Use Midaz beyond finance: track academic credits, supply chain materials, loyalty points, or carbon credits. Midaz fits any domain that needs immutable, auditable tracking of units of value. ## How Midaz works *** **1. Structure** Create your Organization, Ledgers, Assets, and Account Types (A classification defining the nature and purpose of an account, such as checking, savings, escrow, or settlement. Account types enable proper transaction routing.) to reflect your business model. **2. Onboard** Set up customer Portfolios (A grouping of accounts belonging to the same account holder, business unit, or purpose. It ties together checking, savings, and investment accounts for a unified view.) and Accounts. Group them into Segments (A classification applied to accounts that share characteristics, like account holder tiers (VIP, Student) or regional divisions. Rules and pricing can differ by segment.) for differentiated rules and pricing. **3. Define rules** Configure Accounting Routes and Operation Routes to define how money moves. Midaz validates transactions against these routes only when `accounting.validateRoutes` is enabled in the Ledger settings. (Accounting Routes are exposed as `transactionRoute` in the API.) **4. Transact** Process transactions through the API. Midaz validates and updates the balances of each transaction in one atomic step, then records its operations. **5. React** Enable event publishing to trigger downstream systems (notifications, analytics, compliance workflows) the moment a transaction completes. **6. Report** Use Reporter to generate regulatory and business reports from your ledger data, or query balances and transactions directly via the API. ## Integrations with the Lerian ecosystem *** Midaz is a stand-alone product that can optionally integrate with other components of the Lerian ecosystem. | Product | Integration | | - | - | | [Matcher](/en/products/matcher/what-is-matcher) | Optional: Reconcile (The process of comparing two sets of records (for example, your internal ledger against bank statements) to verify they match and flag discrepancies.) ledger transactions against external data sources | | [Reporter](/en/products/reporter/what-is-reporter) | Optional: Generate regulatory and business reports from ledger data | | [Flowker](/en/products/flowker/what-is-flowker) | Optional: Orchestrate pre-ledger validation workflows (anti-fraud, approvals) | | [Tracer](/en/products/tracer/what-is-tracer) | Optional: Real-time transaction validation and spending controls | > [!NOTE] > > Midaz works independently or as part of the Lerian ecosystem. ## Next steps *** > [card] [About Midaz](/en/products/midaz/about-midaz) > > Understand Midaz's domains, entities, and how they relate to each other. > [card] [Quick start](/en/products/midaz/midaz-setup) > > Install and configure Midaz to start building your financial infrastructure. > [card] [Use cases](/en/products/midaz/use-cases) > > Explore detailed use cases for banking, global portfolios, Pix, and more. > [card] [Explore the Midaz API](/en/reference/products/midaz/quick-start-guide) > > Browse endpoints, request/response schemas, and try the API directly. # Products, platform, and plans Source: https://docs.lerian.studio/en/products/products-and-plugins How Lerian's offering is structured: products, platform services, Brazil Rails, Interfaces, and their licensing. Lerian is a complete, modular core banking platform. You choose what you adopt, and when. ## The catalog *** Lerian has six products: Midaz, Tracer, Matcher, Flowker, Lender, and Reporter. Each product covers one financial domain end to end. Each product also deploys and evolves on its own. Console, Access Manager, Streaming Hub, Multi-tenancy, and Observability are platform services. They serve every product and are not products themselves. [Explore the products →](/en/products/about-products) · [Explore the platform →](/en/platform/platform-introduction) ## Licensing *** Lerian licenses every product to institutions. Midaz versions released under the Elastic License 2.0 (ELv2), including Tracer, keep that license. Tracer ships with Midaz, and it stays a separate runtime and deployment. Reporter, Matcher, and Flowker work with a ledger, either Midaz or another one, and they do not depend on one. Lender runs its credit journeys on the Midaz ledger. After you license a product, you can also operate it from the Console. ## Plans *** > [!NOTE] > > Pricing depends on your setup and scale. [Talk to our team](https://lerian.studio/contact) to find the right plan for your use case. ## Brazil Rails and Interfaces *** A Brazil rail is Lerian-owned messaging software that connects your institution to BACEN or to a market infrastructure, with no intermediary. An interface is the product surface over a rail. Pix Lerian is the interface over Lerian SPI, and TED Lerian is the interface over Lerian SPB. Pix JD, Pix BTG, TED JD, and Payments BTG are partner interfaces that ship as separately deployed Midaz plugins. JD Courier lets two or more core banking engines share one JD channel and one ISPB. Plugin SISBAJUD runs SISBAJUD court orders on Midaz. [Explore Brazil Rails →](/en/rails/what-are-brazil-rails) · [Explore Interfaces →](/en/interfaces/introduction) · [Explore the plugins →](/en/products/about-plugins) # Core Banking vision Source: https://docs.lerian.studio/en/start-here/about-lerian/core-banking-vision Understand Lerian's vision for modern core banking, structured around four pillars: Ledger, transactional services, governance, and connectivity. Core banking should be a programmable platform. Four pillars work together to give you control, scalability, and long-term architectural flexibility. ## The four pillars of modern Core Banking *** ### 1. Ledger The ledger is the foundation of any financial system. It manages accounts, balances, and transactions with precision and consistency. Powered by Midaz, our ledger is designed for high throughput, reliability, and operational clarity. **Key capabilities:** * Real-time transaction processing * Multi-currency support * Immutable audit trails * High-performance architecture that scales as transaction volume grows ### 2. Transactional services Transactional services orchestrate how money moves. From instant payments to interbank transfers and card settlement, this layer ensures consistent, secure debit and credit execution across channels and networks. **Transaction types documented today:** * Instant payments: [Pix](/en/interfaces/pix/pix-overview), including scheduled (Pix Agendado) and agreement-based automatic debits (Pix Automático) * Interbank wire transfers: [TED](/en/interfaces/ted/ted-overview), settled through BACEN's STR * Boletos and bill payments: [issuing and paying](/en/interfaces/payments-btg/boleto-and-bill-payment) boletos, DARF taxes, and utility invoices * Card-settlement messaging: [Lerian SLC](/en/rails/slc/what-is-lerian-slc) operates Núclea's ASLC messaging, while [Lerian SILOC](/en/rails/siloc/what-is-lerian-siloc) provides the participant-side gateway and card-domain relay ### 3. Governance Governance ensures that growth does not compromise control. This layer integrates compliance, risk management, accounting, and reporting into the operational flow as structural components. **Governance capabilities:** * KYC/AML integrations through Flowker and third-party providers * Fraud detection and prevention * Regulatory reporting * Accounting integration * Audit and compliance tooling ### 4. Connectivity infrastructure Our connectivity infrastructure supports integration with external networks, partners, and internal systems. **Integration capabilities:** * Built for integration: every capability is accessible through standard interfaces * Runs on modern cloud infrastructure with automated scaling and recovery * Supports multiple communication protocols * Real-time data synchronization * Secure communication channels ## What the modular architecture allows *** Traditional core banking platforms are monolithic and difficult to evolve. Lerian’s modular architecture allows institutions to: * Adopt components incrementally * Integrate with existing systems * Scale based on operational demand * Avoid vendor lock-in You stay in control of your architecture and your roadmap. # Our values Source: https://docs.lerian.studio/en/start-here/about-lerian/our-values Learn Lerian's mission and the values that guide our work: strength, courage, integrity, audacity, and leadership in financial infrastructure. At Lerian, we combine technology and financial expertise to help institutions manage their operations through a modular platform. We help institutions build systems they can control as their needs evolve. ## Our Mission *** We help financial institutions adopt a modular platform that supports independent operations and evolution. We design adaptable financial software anchored by Midaz, our core ledger. Institutions assemble the products and platform services they need. ## Our Commitment *** We design for scale, so our software grows with our clients' needs. We believe in building technology that adapts to your needs. ## Our Values *** ### Be Your Own Strength Pursue excellence, face challenges with resilience, and embrace growth. True strength comes from the ability to adapt, learn, and overcome obstacles. ### Be Your Own Courage Navigate uncertainty boldly and embrace risk with confidence. Courage means taking calculated risks and pushing boundaries. ### Be Your Own Integrity Uphold transparency, ethics, and trust in every decision. Integrity is not negotiable. It underpins everything we build and every relationship we nurture. ### Be Your Own Audacity Innovate fearlessly, push boundaries, and take initiative. Audacity drives us to challenge conventions and create solutions that others might consider impossible. ### Be Your Own Leader Forge your own path with vision, self-development, and confidence. Leadership means you take ownership, inspire others, and create lasting impact. # Our release cycle Source: https://docs.lerian.studio/en/start-here/about-lerian/release-cycle Understand how Lerian plans, builds, tests, and releases, from continuous weekly delivery to production releases, so teams know what to expect. Lerian plans and reviews work on a weekly rhythm, delivering improvements continuously. Production releases follow a separate, more deliberate cadence to keep environments stable. We evolve all our products, improving existing capabilities and, when applicable, developing new products. We validate every change before it reaches production. ## How it works *** * **Planning**: We align scope, priorities, and technical direction. We define requirements and shape the roadmap. * **Development**: The team builds and iterates on new features, enhancements, and platform improvements based on the planned scope. * **Testing and validation**: We test and validate changes for reliability, performance, and consistency across the platform. * **Release**: We consolidate changes into a production release. We publish documentation and release notes with the rollout. # 2025 release schedule Source: https://docs.lerian.studio/en/start-here/about-lerian/release-cycle-2025 Track Lerian's 2025 release cycles with the planned start and end dates for each stage so you can align your delivery and rollouts. In 2025, our release cycles were: ## First cycle *** | Stage | Start Date | End Date | | :- | :- | :- | | **Weeks 1–6** | April 7 | May 16 | | **Weeks 7–8** | May 19 | May 30 | ## Second cycle *** | Stage | Start Date | End Date | | :- | :- | :- | | **Weeks 1–6** | June 2 | July 11 | | **Weeks 7–8** | July 14 | July 25 | ## Third cycle *** | Stage | Start Date | End Date | | :- | :- | :- | | **Weeks 1–6** | July 28 | September 5 | | **Weeks 7–8** | September 8 | September 19 | ## Fourth cycle *** | Stage | Start Date | End Date | | :- | :- | :- | | **Weeks 1–6** | September 22 | October 31 | | **Weeks 7–8** | November 3 | November 14 | ## Fifth cycle *** | Stage | Start Date | End Date | | :- | :- | :- | | **Weeks 1–6** | November 17 | December 26 | | **Weeks 7–8** | December 29 | January 9, 2026 | # Our release schedule Source: https://docs.lerian.studio/en/start-here/about-lerian/release-schedule Track Lerian's release schedules, organized by year. This page links Lerian's release schedules by year. To understand how our release cycle works, see the [Our release cycle](/en/start-here/about-lerian/release-cycle) page. > [card] [2025 schedule](/en/start-here/about-lerian/release-cycle-2025) > > Cycles completed in 2025 with dates for each stage. # Version governance Source: https://docs.lerian.studio/en/start-here/about-lerian/versioning-governance Understand Lerian's versioning governance: how changes are communicated, how dependencies stay compatible, and our backward-compatibility promise. This page covers how we communicate changes, how we manage dependencies, and our long-term commitment to backward compatibility. ## Communication of changes *** We communicate every change so teams can prepare. * **Release notes** include new features, improvements, bug fixes, and breaking changes with migration paths. * **Documentation updates** reflect API changes, new configurations, and updated behaviors. * We announce major versions in advance. ## Versioning of dependencies *** We version dependencies with the same principles to ensure stability and compatibility. * **Internal dependencies** follow the same versioning scheme as Midaz. * We manage **external dependencies** to stay compatible throughout a major version lifecycle. ## Backward compatibility commitment *** This versioning policy applies to every new release. We commit to maintaining the defined support windows for all future versions. By preserving backward compatibility, we reduce the risk of breaking changes and let you plan upgrades on your own schedule. > [!TIP] > > For details about timelines and schedules, see the [Release cycle](/en/start-here/about-lerian/release-cycle) page. # Versioning process Source: https://docs.lerian.studio/en/start-here/about-lerian/versioning-process Understand how versioning works in Lerian: what to expect between releases, how semantic versioning is automated, and how to plan upgrades across majors. Versioning follows an automated process that ensures consistency across releases. This section explains how automation drives version generation, how support timelines are defined, and what to expect when moving between versions. ## Versioning automation *** To ensure an automated and predictable versioning process, we follow **semantic versioning** principles. ### How it works *** **Step 1** Identifies commits made since the last version. **Step 2** Determines the new version based on predefined rules. **Step 3** Automatically generates and publishes the new version. ## Version support timeline *** Midaz follows a support policy that defines what you can expect from each version throughout its lifecycle. * **Active support (current major version):** includes feature enhancements, bug fixes, and security patches. * **Security support (post-active support):** limited to critical security patches only. > [!CAUTION] > > Older versions do not receive further updates or support. ## Upgrade path recommendations *** Follow these recommendations when you upgrade Midaz versions. * **Minor version upgrades** (`1.0.0 → 1.1.0`) require little effort. * **Major version upgrades** (`1.2.0 → 2.0.0`) may involve planning and testing. * Every major version comes with an **upgrade guide**. # Versioning scheme Source: https://docs.lerian.studio/en/start-here/about-lerian/versioning-scheme Learn how Lerian applies semantic versioning, and how we manage breaking changes. The versioning scheme describes how we assign and increment version numbers. It clarifies the meaning of major, minor, and patch releases, and how we handle breaking changes. ## Semantic versioning *** We follow a **modified semantic versioning** scheme in the format **X.Y.Z**, where: | Version type | Increment frequency | Characteristics | Example | | - | - | - | - | | **X (Major Version)** | Evaluated every two development cycles, but **only released if there are significant changes**. | **May introduce breaking changes**. Requires explicit upgrade steps. | *1.0.0 → 2.0.0* | | **Y (Minor Version)** | Every development cycle | **Maintains backward compatibility**. Introduces new features and functionality. | *1.0.0 → 1.1.0* | | **Z (Patch Version)** | As needed, outside the regular cycle | **For hotfixes, security patches, and critical updates**. Maintains backward compatibility. | *1.1.0 → 1.1.1* | ## Breaking changes *** A breaking change happens when an update alters or removes behavior in a way that is not fully compatible with previous versions. To keep this process predictable, we follow strict rules and communicate early. * We introduce breaking changes **only in a major version**. * They are **announced in advance**, always with migration guides and examples. * Deprecated features **emit warnings** before removal, so teams have time to adjust. * We aim to **minimize disruption** by grouping breaking changes together and providing alternative solutions whenever possible. ### Examples * **Field replacement**: `routeId` (UUID) superseded the free-text `route` field in transaction payloads. v1 still accepts `route` when `routeId` is absent. v2 accepts only `routeId`. * **Validation rules**: The Ledger Settings API replaced the `ACCOUNT_TYPE_VALIDATION` and `TRANSACTION_ROUTE_VALIDATION` environment variables. The API controls accounting validation per ledger without redeployment. * **Deprecation cycle**: We removed the `scale` field from transaction amounts in v3, when amount handling moved to a numeric system. # Our versioning strategy Source: https://docs.lerian.studio/en/start-here/about-lerian/versions Understand Lerian's versioning strategy: increments, automation, upgrade paths, and how changes are communicated. Our versioning strategy defines how we increment versions and how automation keeps everything consistent across the system. Each release follows a [clear cycle](/en/start-here/about-lerian/release-cycle). Alongside the technical rules, we provide guidance on upgrade paths, outline our support policy, and communicate changes. # Who we are Source: https://docs.lerian.studio/en/start-here/about-lerian/who-we-are Learn about Lerian's mission, identity, and the principles that guide our approach to modern, modular financial infrastructure and core banking software. At Lerian, we build financial infrastructure that gives institutions control. We combine deep financial expertise with modern, modular technology to help organizations operate independently, scale confidently, and adapt without friction. We believe in clarity, ownership, and long-term autonomy. ## What we do *** We help financial institutions design and operate modern core banking ecosystems. By providing a programmable, modular foundation, we enable teams to move faster without compromising control over their operations or their architecture. We built our platform for institutions that demand more than off-the-shelf solutions: * **Digital banks** launching new financial products * **Traditional banks** modernizing legacy cores incrementally * **Fintechs** building embedded finance and payment platforms * **Enterprises** consolidating payments, collections, and reconciliation across business units ## Our principles *** Three principles guide how we build financial software: #### Independence over vendor lock-in We build systems that you control. We use standard interfaces and open formats, so no single vendor dictates your roadmap. #### Transparency over opacity Financial systems require absolute clarity. We design our infrastructure to be inspectable and auditable, so it has no hidden logic or opaque behaviors that introduce systemic risk. #### Architecture over shortcuts We prioritize scalable design over quick fixes. Our solutions handle real-world complexity, so your infrastructure grows with your business without constant re-platforming. ## Explore further *** > [card] [Why Lerian](/en/start-here/about-lerian/why-lerian) > > Understand the problems we solve and how our platform helps financial institutions regain control. > [card] [Our values](/en/start-here/about-lerian/our-values) > > Discover the core values and commitments that drive our team and shape our culture. ## Get in touch *** Talk to us about your questions, a partnership, or your architecture. > [card] [Contact us](https://lerian.studio/en/contact) > > Reach out to our team to discuss how Lerian can support your infrastructure needs. # Why Lerian Source: https://docs.lerian.studio/en/start-here/about-lerian/why-lerian Understand how Lerian helps financial institutions modernize core banking without vendor lock-in: modular products and flexible deployment. Modern financial institutions face a common set of challenges. Legacy systems cost too much to maintain, and they adapt too slowly. They also lock you into vendors who dictate the roadmap. Lerian gives you back control. > [!NOTE] > > **New to core banking?** If terms like *Ledger*, *debit and credit*, or *chart of accounts* are new to you, start with the fundamentals first. They make everything here easier to follow. > > **[Begin with Core Banking Fundamentals](/en/start-here/fundamentals/core-banking/what-is-core-banking)** ## The problems we solve *** | Challenge | How Lerian helps | | :- | :- | | **Slow time-to-market** | Modular platform lets you launch new products in weeks, not months | | **Compliance burden** | Built-in audit trails, regulatory reporting, and immutable records reduce manual compliance work | | **Reconciliation errors** | Automated reconciliation replaces manual spreadsheet matching and catches discrepancies | | **Operational cost** | Replace multiple disconnected systems with one composable platform | | **Scaling limitations** | Handle millions of transactions per day without re-platforming | ## What the platform includes *** | Business need | Lerian product | What it does | | :- | :- | :- | | Central financial record-keeping | **Midaz** | Manages accounts, balances, and transactions with full audit trails | | Regulatory and business reporting | **Reporter** | Generates compliance reports (BACEN) and business analytics automatically | | Transaction reconciliation | **Matcher** | Compares internal records against bank statements and payment processors, and flags discrepancies | | Real-time transaction controls | **Tracer** | Validates transactions against spending limits and business rules before they execute | | Workflow automation | **Flowker** | Automates approval flows, anti-fraud checks, and payment orchestration | | Credit products and loan management | **Lender** | Defines loan products and manages the loan lifecycle: applications, disbursement, and interest accrual | Console, Access Manager, Streaming Hub, Multi-tenancy, and Observability are platform services. They are not products themselves. | Platform service | What it does | | :- | :- | | **Console** | Operates Lerian products from one web interface, with one login | | **Access Manager** | Controls human and machine access, and issues access tokens | | **Streaming Hub** | Delivers platform events to your webhooks, cloud queues, or pull consumers | | **Multi-tenancy** | Serves independent institution contexts from one deployment | | **Observability** | Collects metrics, traces, and logs from Lerian workloads through OpenTelemetry | ## Deployment flexibility *** You choose how to run the platform: * **Fully managed (SaaS)**: Lerian handles everything. Your team focuses on configuration and business logic. Fastest path to production. * **Your infrastructure (BYOC)**: Deploy in your own cloud or on-premises. Full control over data residency, security, and compliance boundaries. Choose based on your regulatory requirements and operational maturity. [Compare deployment models in detail →](/en/start-here/evaluate-and-deploy/deployment-models) ## Built for trust and independence *** * **No vendor lock-in**: Standard interfaces and open formats across the platform. You can always move * **Compliance-ready**: Immutable audit trails, double-entry enforcement, and regulatory reporting ship built in * **Incremental adoption**: Start with one product and expand as needed. No big-bang migration required ## Who uses Lerian *** * **Digital banks** launching new financial products * **Traditional banks** modernizing legacy cores incrementally * **Fintechs** building embedded finance and payment platforms * **Enterprises** consolidating payments, collections, and reconciliation across business units ## Next steps *** > [card] [Our Core Banking vision](/en/start-here/about-lerian/core-banking-vision) > > Understand the four pillars that form our architectural philosophy. > [card] [Getting started](/en/start-here/getting-started) > > Choose your path: evaluate the platform or start building. > [card] [Deployment models](/en/start-here/evaluate-and-deploy/deployment-models) > > Understand the differences between fully managed and self-hosted deployment. > [card] [Talk to us](https://lerian.studio/en/contact) > > Talk to us about your questions or a partnership. # Lerian Cloud (SaaS) and BYOC Source: https://docs.lerian.studio/en/start-here/evaluate-and-deploy/deployment-models Understand how Lerian can be deployed, in Lerian Cloud (SaaS) or through BYOC in your own infrastructure, and choose the model that fits your compliance and scale needs. Lerian supports two deployment models for its complete, modular platform: **Lerian Cloud (SaaS)** and **BYOC** (Bring Your Own Cloud). The deployment model defines who operates the infrastructure. Your license and commercial agreement define which modules are available. Choose the model that fits your operational maturity, compliance requirements, and team structure. Availability depends on the permitted license and commercial arrangement. ## Lerian Cloud (SaaS): Fully managed by Lerian *** In Lerian Cloud, Lerian hosts and operates the platform for you. Your team focuses on building financial products. We handle everything underneath. **What Lerian manages:** * Cloud infrastructure (compute, storage, networking) * Database provisioning, backups, and scaling * Security patches and OS-level updates * Application upgrades and version management * Monitoring, alerting, and incident response * High availability and disaster recovery **What you manage:** * Business configuration (organizations, ledgers, accounts, rules) * API integrations with your systems * User access and permissions within the platform * Compliance obligations specific to your institution > [!TIP] > > Lerian Cloud is ideal if you want the fastest path to production without building or maintaining infrastructure. Lerian operates the platform for you from day one. ## BYOC (Bring Your Own Cloud) *** In the BYOC model, you deploy and operate Lerian in your own infrastructure. That can be a public cloud (AWS, GCP, Azure), a private cloud, or on-premises. Flowker runs only in Lerian Cloud. You have full control over the environment. Lerian provides the software, Helm Charts (A pre-configured package for deploying software on Kubernetes. Think of it as a ready-to-use installation template that automates setup and configuration.), Terraform templates (An infrastructure automation tool that provisions and manages cloud resources (servers, databases, networks) through configuration files instead of manual setup.), and tooling to make deployment and lifecycle management straightforward. **What Lerian provides:** * Application software (container images, Helm Charts) * [Terraform templates](/en/products/midaz/midaz-terraform-foundation) for infrastructure provisioning * [Lifecycle Management](/en/platform/lifecycle-management): an agent in your cluster, through which Lerian installs and upgrades products * Lerian installs and upgrades Matcher and Streaming Hub through Lifecycle Management. * Security patches and application updates (delivered by Lerian, and applied by you or by Lerian through Lifecycle Management) **What you manage:** * Cloud infrastructure and Kubernetes (A platform for running and managing software applications at scale. It automatically handles deployment, scaling, and recovery across multiple servers.) clusters * Database administration, backups, and scaling * Network security (firewall rules, network isolation, and traffic routing) * OS and container-level patching * Monitoring and observability pipelines * Encryption, secrets management, and access control > [!TIP] > > BYOC is ideal if your organization requires full data sovereignty, has strict regulatory constraints on where data lives, or has an established platform engineering team. Lerian publishes official Helm charts (A pre-configured package for deploying software on Kubernetes. Think of it as a ready-to-use installation template that automates setup and configuration.) for the products and platform components supported through its Helm repository. Helm is the recommended way to deploy, configure, and manage the platform in your infrastructure. For step-by-step installation instructions, see the [Midaz chart README](https://github.com/LerianStudio/helm/blob/main/charts/midaz/README.md#install-midaz-helm-chart). > [!NOTE] > > Lerian Cloud is operated as a multi-tenant environment managed by Lerian. If you need dedicated, isolated infrastructure, choose BYOC. ## How your deployment model affects Midaz API integration *** The Midaz API surface is identical across deployment models: same endpoints, same payloads, same responses. The difference is in how authentication and tenant scoping work. **Lerian Cloud (Midaz)** Your tenant context is established automatically through your authentication token. There is no tenant header to pass and no tenant ID to manage manually. * You authenticate via [Access Manager](/en/platform/access-manager) and receive a JWT. * That token includes your tenant context. * Every API call is automatically scoped to your tenant: organizations, ledgers, accounts, and transactions are all isolated. * You never interact with data from other tenants, and they never interact with yours. **BYOC (Midaz)** Configure authentication with `PLUGIN_AUTH_ENABLED`. It defaults to `false`. Set it to `true` in production. With authentication disabled, API calls do not require a token. > [!TIP] > > For a deeper look at how tenant isolation works, see [Multi-tenancy](/en/platform/multi-tenancy). ## At a glance *** | | **Lerian Cloud (SaaS)** | **BYOC** | | :- | :- | :- | | **Who manages infrastructure?** | Lerian | Your team | | **Where does data live?** | Lerian-managed cloud | Your cloud or on-premises | | **Time to production** | Weeks | Depends on your provisioning timeline | | **Operational effort** | Low: Lerian handles operations | Higher: your team operates the platform | | **Best for** | Teams that want to focus on product, not infrastructure | Organizations with strict data residency or compliance requirements | > [!TIP] > > Not sure which model fits? Jump to ["Which model is right for you?"](#which-model-is-right-for-you) below. ## Comparing the models *** | | **Lerian Cloud (SaaS)** | **BYOC** | | :- | :- | :- | | **Infrastructure** | Managed by Lerian | Managed by you | | **Data location** | Lerian-managed cloud | Your cloud or on-premises | | **Data sovereignty** | Data hosted in Lerian-managed cloud infrastructure | Data is hosted in your environment; you control residency and egress according to your architecture and contracted services. | | **Security responsibility** | Shared (Lerian manages infra + app) | Shared (you manage infra, Lerian manages app) | | **Time to production** | Weeks: no infrastructure setup required | Depends on your team's provisioning timeline | | **Operational overhead** | Low: Lerian handles operations | Higher: your team operates the platform | | **Customization** | Standard configuration | Full control over infrastructure and networking | | **Compliance** | Lerian's environment meets security standards | You ensure your environment meets your regulatory requirements | | **Updates** | Applied by Lerian | Applied by you with Helm, or by Lerian through Lifecycle Management (Matcher and Streaming Hub: by Lerian only) | | **Scalability** | Managed by Lerian | Managed by you | ## Which model is right for you? *** **Choose Lerian Cloud if:** * You want to go live quickly without provisioning infrastructure * Your team prefers to focus on product and integration, not operations * You don't have strict requirements for data to remain in your own environment **Choose BYOC if:** * Regulatory or compliance rules require data to stay in your infrastructure * You need full control over networking, encryption, and access policies * Your organization has a platform or DevOps team ready to operate Kubernetes workloads * You want to integrate Lerian into an existing cloud environment with specific architectural constraints ## What's next *** > [card] [Getting started](/en/start-here/getting-started) > > Follow the step-by-step guide to set up your first Ledger and run transactions. > [card] [Security](/en/products/midaz/security) > > Learn how the shared responsibility model works for each deployment option. > [card] [Deployment strategies](/en/products/midaz/deployment) > > Explore Kubernetes, Helm, and Terraform options for BYOC deployments. # Before you begin Source: https://docs.lerian.studio/en/start-here/evaluate-and-deploy/getting-started Review the sandbox, Try It, and licensing pages before integrating with Lerian APIs so you know how to authenticate, test, and access each product. This section covers the tools and policies you should know before integrating with Lerian's APIs. Use the sandbox to test your requests safely, and read the license page to get and configure your license key. ## Available pages *** > [card] [Using our Sandbox](/en/start-here/evaluate-and-deploy/using-our-sandbox) > > Test your integrations in a secure, isolated environment with simulated data. > [card] [Using the Try It feature](/en/start-here/evaluate-and-deploy/using-try-it) > > Interact with our APIs directly from the documentation. > [card] [Lerian's License](/en/start-here/evaluate-and-deploy/lerians-license) > > Get your product's license key and configure it in your deployment. # Setup order for Midaz and Access Manager Source: https://docs.lerian.studio/en/start-here/evaluate-and-deploy/initiating-with-enterprise-model Set up Midaz, Access Manager, and Reporter in the right order to onboard product, engineering, and ops teams. > [!NOTE] > > This guide is for users with access to **Midaz** and **Access Manager**. It also shows how to configure the **Fees Engine** and **CRM** capabilities that ship inside Midaz, and how to add **Reporter**. ## Getting started: Setup order *** Follow this setup order: ![Recommended setup order, sequencing Midaz, Access Manager, and the optional Fees, CRM, and Reporter capabilities](https://mintcdn.com/lerian-49cb71fc/svQbQMf9Iz90q0Cc/images/en/d2/enterprise-model.svg?fit=max\&auto=format\&n=svQbQMf9Iz90q0Cc\&q=85\&s=0a4b51b9c2763c1a87cb07f849de8eb2) Figure 1. Setup order. Get an Access Manager token first. Midaz needs one for every call in Lerian Cloud, and in any BYOC deployment that enables authentication. ### Step 1: Configure Midaz Core Start with the [Midaz recommended workflow](/en/products/midaz/recommended-workflow). It covers these tasks: * Create your Organization and Ledger(s). * Define assets and account types. * Set up portfolios, accounts, and segments. * Configure Accounting Routes for validation. * Build double-entry transaction workflows. ### Step 2: Activate Access Manager **Access Manager** centralizes authentication and role-based access control (RBAC) for Midaz and its plugins. * Define roles and their permissions. * Assign permissions to roles or users. * Control access to operations by role. > [!TIP] > > Start with the [Access Manager Setup](/en/platform/access-manager) page. ### Step 3: Configure CRM **CRM** ships inside the Midaz ledger process and manages `Holder` and `Instrument` records. Instruments add CRM context to an account's Holder, and accounts can optionally belong to portfolios. * Register customers as `Holder` objects. * Create Instruments to link Holders to ledger accounts, or use `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/holders/{holder_id}/accounts` to open a holder-owned account in one call. * Add metadata for compliance, segmentation, and insights. This links each customer to the right ledger accounts. > [!TIP] > > Start with the [CRM Setup](/en/products/midaz/crm/crm-overview) page. ### Step 4: Configure Fees Engine Use the **Fees Engine** to automate pricing and monetization rules across your operations. * Define fee packages with flat or percentage calculations. * Attach fees to operations like transfers or withdrawals. * Control when and how the Fees Engine calculates and charges each fee. > [!TIP] > > Start with the [Fees Engine Setup](/en/products/midaz/fees/fees-engine-overview) page. ### Step 5: Design with Reporter templates Use **Reporter** and its template engine to generate content such as: * Transaction summaries * Regulatory documents * Customer notifications Use it to standardize documents and messages with context data from Midaz and CRM. > [!TIP] > > Start with the [Reporter quick start](/en/products/reporter/reporter-quick-start) page. ## Final recommendations *** After you set up all systems: * Review the integration points between Midaz and each capability. * Create automated workflows that combine ledger events, customer data, and fee logic. * Apply permission rules with Access Manager to control access at scale. > [!TIP] > > Lerian capabilities are modular. Activate and expand them progressively. # Lerian's License Source: https://docs.lerian.studio/en/start-here/evaluate-and-deploy/lerians-license A Lerian license key covers one product for the whole deployment: how you get the key and how you configure it. A **license key** authorizes one Lerian product in your deployment. Each licensed product validates its key when it starts, and again at a fixed interval. ## Get and configure the key *** **1. Request the key** Ask Lerian for a license key for the product. One key covers the whole deployment, so you do not give organization IDs. **2. Receive the key** Lerian sends you the key. Store it as a secret. **3. Configure the environment** Set the key and the global scope in the product environment. ```bash Bash theme={null} LICENSE_KEY=your-license-key ORGANIZATION_IDS=global ``` * **LICENSE_KEY**: The key that Lerian issued for the product. * **ORGANIZATION_IDS**: Set it to `global`. > [!WARNING] > > Incorrect or missing values make license validation fail. To replace a key that was issued with a list of organizations, see [License Manager](/en/platform/licensing/license-manager). ## License-related errors *** For the error codes a product returns when license validation fails, see [License Manager error list](/en/platform/licensing/license-manager-error-list). > [!TIP] > > For more information about your license, open a request on Lerian Clients at [clients.lerian.studio](https://clients.lerian.studio). # Using our Sandbox Source: https://docs.lerian.studio/en/start-here/evaluate-and-deploy/using-our-sandbox An isolated Lerian environment that powers the Try It experience inside the documentation for safe hands-on API testing. The sandbox helps you explore Lerian’s APIs in a safe and predictable environment. The sandbox powers the Try It experience. If you haven't seen how the Try It feature works yet, check out the [Using the Try It feature](/en/start-here/evaluate-and-deploy/using-try-it) page. ## Base URLs *** | Service | Sandbox Base URL | | - | - | | Midaz | `https://ledger.sandbox.lerian.net` | | Access Manager | `https://auth.sandbox.lerian.net` (Auth APIs) `https://identity.sandbox.lerian.net` (Identity APIs) | | Reporter | `https://reporter.sandbox.lerian.net` | | Tracer | `https://tracer.sandbox.lerian.net` | | Matcher | `https://matcher.sandbox.lerian.net` | | Flowker | `https://flowker.sandbox.lerian.net` | | Lender | `https://lender.sandbox.lerian.net` | | Streaming Hub | `https://streaming-hub.sandbox.lerian.net` | | Consignado CLT (Dataprev) | `https://br-consignado-gw.sandbox.lerian.net` | ## What you can do *** The sandbox lets you: * Run live requests from the documentation * Inspect request and response structures * Understand authentication headers and data formats * Learn how each API behaves without setting up your own environment > [!TIP] > > Click **Try It** on an endpoint to run a live request and check how the API responds. ## Limitations *** The sandbox is designed for exploration. Some restrictions are intentional: * Data resets frequently * Some APIs can use simpler authentication rules For full integration tests, use your own environment or reach out to our team to request a dedicated development space. # Using the Try It feature Source: https://docs.lerian.studio/en/start-here/evaluate-and-deploy/using-try-it Send live requests directly from the documentation with real API responses in a controlled environment, with no local setup required. The **Try It** feature lets you interact with our APIs directly from the documentation. It gives you an embedded playground where you can test real requests and responses in a controlled environment. If you want to understand how the sandbox works under the hood, check the page [Using our Sandbox](/en/start-here/evaluate-and-deploy/using-our-sandbox). ## What you can do *** With **Try It**, you can: * Send live requests * Inspect full HTTP request and response details * Adjust headers, parameters, and body payloads * Test different authentication tokens or organization IDs * Explore error handling and validation scenarios with mock data ## Before you start *** You will need the required headers for each API. Examples include `Authorization` or `X-Organization-Id`. Each endpoint specifies exactly which headers you must use. > [!CAUTION] > > The sandbox resets automatically every day. > > The Organizations, Ledgers, and Portfolios you create are deleted within 24 hours. > > When testing dependent endpoints, create the required entities again before sending new requests. > > For example, you must create an Organization before creating a Ledger. Use the returned `id` as the `organization_id` in the Ledger path. ## How to use it *** > [!WARNING] > > The **Try It** feature is available on endpoint pages in the **API Reference**. > > If the Try It button does not appear, reload the page or check that you are in the API Reference section. **Step 1** Open any endpoint in the **API Reference**. **Step 2** Click the **Try It** button next to the endpoint path. **Step 3** Fill in the input fields such as query parameters, body content, or headers. **Step 4** Click **Send Request** to run the call. **Step 5** Review the response body, status code, and headers shown below the request. > [!TIP] > > You can copy your request as `curl` or `fetch` using the code tabs. It is a simple way to move from testing in the docs to running calls in your local environment. # The accounting cycle Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/accounting-cycle How transactions, journal entries, the ledger, trial balance, and financial statements fit together as one repeating cycle that keeps the books trustworthy. You've met the pieces one at a time: [debits and credits](/en/start-here/fundamentals/accounting/debits-and-credits), [journal entries](/en/start-here/fundamentals/accounting/journal-entries), the [chart of accounts](/en/start-here/fundamentals/accounting/chart-of-accounts), the [financial statements](/en/start-here/fundamentals/accounting/financial-statements). The **accounting cycle** puts them in a line. It is a routine that repeats. It turns a single real-world event into a report you can trust, then starts over. ## One event, all the way through *** Every figure on a financial statement started life as something tiny and concrete: a sale, a payment, a bill. The cycle is the path that event travels, step by step, until it shows up in a report. * **Transaction**: something happens. A customer pays, you cover the rent, a bill arrives. * **Journal entry**: you write it down as matching debits and credits, so you record both sides of the movement. * **Ledger**: you sort each entry into the right account, so every account gathers its own running history. * **Trial balance**: you add up all the accounts and check that total debits still equal total credits. * **Financial statements**: the balanced totals form the Balance Sheet, Income Statement, and Cash Flow Statement. Then the cycle repeats for the next transaction, the next day, the next period. ```mermaid theme={null} flowchart LR T["Transaction
something happens"] --> J["Journal entry
debits = credits"] J --> L["Ledger
sorted by account"] L --> TB["Trial balance
check it still balances"] TB --> FS["Financial statements
the reports"] FS -.->|"next transaction · next period"| T classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class TB,FS bal; ``` ## Walking one transaction around the loop *** Say a customer pays you \$2,000 for a sale you make right then, so you earn the revenue at that moment. Follow it through: 1. **Transaction.** The sale happens and the customer pays. 2. **Journal entry.** You record it: **Cash** debited \$2,000, **Revenue** credited \$2,000. Debits equal credits, so the entry balances. 3. **Ledger.** That \$2,000 debit joins the running history of the Cash account. The \$2,000 credit joins the Revenue account. Do this for every entry and each account always knows its own total. 4. **Trial balance.** Add every account's debits and credits across the whole book. If the two grand totals match, the records are internally consistent, a quick health check before you report anything. 5. **Financial statements.** The Cash balance feeds the Balance Sheet. The Revenue feeds the Income Statement. It is the same \$2,000, now part of the big picture. The cycle invents nothing new along the way. Each step reorganizes the same balanced movement into a more useful shape. It goes from a single event, to a record, to a sorted history, to a verified total, to a readable report. ## Why the order matters *** Each step depends on the one before it, so the sequence never changes: * You can't sort an entry into the **ledger** until you've written the **journal entry**. * The **trial balance** is only meaningful once every entry has landed in the ledger. * The **financial statements** are only trustworthy once the trial balance confirms debits equal credits. The balancing rule from [double-entry](/en/start-here/fundamentals/accounting/double-entry-bookkeeping) rides along at every stage. > [!NOTE] > > **See also in Core Banking** > > See how this whole flow lands in a real ledger system in [Designing your ledger plan](/en/start-here/fundamentals/core-banking/designing-your-ledger-plan) and [Where to go next](/en/start-here/fundamentals/core-banking/where-to-go-next). ## Next steps *** > [!NOTE] > > **Next up** > > See how these ideas map onto a real ledger system in [Accounting in Lerian](/en/start-here/fundamentals/accounting/accounting-in-lerian). # Accounting in Lerian Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/accounting-in-lerian How core accounting ideas map onto real Lerian and Midaz entities (accounts, transactions, operations, and routes) so the concepts and the product line up. Everything in this guide covers accounting in general. Midaz implements that same accounting. The terms you've already learned have direct counterparts in the product. ## The same ideas, renamed for a ledger *** From here on, the words get more product-specific. The accounting ideas stay the same and only the names change. In the table below, each accounting idea on the left maps to something concrete in Midaz on the right. | Accounting idea | In Lerian / Midaz | | - | - | | [Chart of accounts](/en/start-here/fundamentals/accounting/chart-of-accounts) | The **account hierarchy** inside a Ledger | | The five account families (assets, liabilities, equity, revenue, expense) | How you **structure and group** accounts in that hierarchy | | [Journal entry](/en/start-here/fundamentals/accounting/journal-entries) | A **transaction** made of **operations** | | A single debit or credit line | One **operation** | | Which accounts a kind of entry may touch | An **accounting route** | ```mermaid theme={null} flowchart LR subgraph ACC["Accounting"] direction TB CA["Chart of Accounts"]:::a JE["Journal Entry"]:::a DC["Debit / Credit rule"]:::a end subgraph MID["Lerian / Midaz"] direction TB AH["Account Hierarchy"]:::m TO["Transaction + Operations"]:::m AB["Always Balanced"]:::m end CA --> AH JE --> TO DC --> AB classDef a fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef m fill:#dcfce7,stroke:#16a34a,color:#14532d ``` ## Chart of accounts → the account hierarchy *** A [chart of accounts](/en/start-here/fundamentals/accounting/chart-of-accounts) organizes the buckets a business sorts its money into. In Midaz, an [account](/en/start-here/fundamentals/core-banking/building-blocks) belongs to one asset code and can have one or more keyed [balance](/en/start-here/fundamentals/core-banking/building-blocks) records. Accounts form a hierarchy, not a flat list. You can nest and group them to mirror the structure of a real business. The five accounting families (assets, liabilities, equity, revenue, expenses) are the kind of grouping that hierarchy expresses. A [Ledger](/en/start-here/fundamentals/core-banking/building-blocks) is one self-contained book of records, and an Organization can hold several. So your chart of accounts lives as the structured set of accounts inside a Ledger. It is the same map of "where value lives," given room to scale. ## Journal entry → transaction + operations *** A [journal entry](/en/start-here/fundamentals/accounting/journal-entries) records one event as matching debits and credits. Midaz splits that single idea into two precise words you'll see everywhere in [how money moves](/en/start-here/fundamentals/core-banking/how-money-moves): * A **transaction** is one complete movement of value: the whole event, start to finish. That's the journal entry. * An **operation** is one part of that movement: the smallest Midaz record of a balance effect. Non-pending transfers can produce debit and credit operations. Pending or canceled flows can also include `ON_HOLD` or `RELEASE`. So when you recorded "Cash debited \$2,000, Revenue credited \$2,000" as a journal entry, the Midaz version is one transaction made of two operations. It is the same event and the same two sides, in the product's vocabulary. ```mermaid theme={null} flowchart TD A["Journal entry
accounting"]:::acc --> B["Transaction
the whole movement"]:::mid B --> C["Operation
debit"]:::mid B --> D["Operation
credit"]:::mid C --> E["Debits total"]:::tot D --> F["Credits total"]:::tot E --> G["Transaction balances"]:::bal F --> G classDef acc fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef mid fill:#dcfce7,stroke:#16a34a,color:#14532d classDef tot fill:#f3f4f6,stroke:#6b7280,color:#111827 classDef bal fill:#fde68a,stroke:#d97706,color:#78350f ``` ## Double-entry → transactions always balance *** Midaz builds the iron rule of accounting, [debits must equal credits](/en/start-here/fundamentals/accounting/debits-and-credits), into its processing. Midaz validates resolved source, destination, and transaction totals before processing. If they differ, the movement will not go through. Midaz validates every accepted movement with a clear source and a clear destination. The system enforces this instead of a person. The [core-banking explanation of how the ledger records money](/en/start-here/fundamentals/core-banking/double-entry-explained) covers this from the ledger's side. ## Accounting routes → which accounts may take part *** In plain accounting you decide by judgment which accounts a given kind of entry should touch. Midaz captures that judgment once as an [accounting route](/en/start-here/fundamentals/core-banking/routes-and-fees). The route is a reusable rule for who can send, who can receive, and which debits and credits a movement should record. With route validation enabled for the Ledger, Midaz checks transactions against that rule. A **fee** means more balanced operations on the same transaction. For example, a wallet transfer's route defines which customer account may be debited, which customer account may be credited, and which fee accounts join in when a fee applies. With route validation enabled, Midaz checks those rules. The [core-banking guide to routes and fees](/en/start-here/fundamentals/core-banking/routes-and-fees) walks through it in full. ## A note on holders and accounts *** In Midaz the [account](/en/start-here/fundamentals/core-banking/holders-accounts-aliases) is the balance container. The real-world owner is a separate **holder** record and friendly nicknames are **aliases**, kept separate so the Ledger's record of value stays clean. If that distinction matters for your work, [who owns what](/en/start-here/fundamentals/core-banking/holders-accounts-aliases) untangles it. ## Next steps *** > [!NOTE] > > **Go deeper** > > To see these entities in full, continue into the [Core banking fundamentals](/en/start-here/fundamentals/core-banking/what-is-core-banking), or revisit any idea from the [Accounting overview](/en/start-here/fundamentals/accounting/what-is-accounting). # Accrual vs. cash accounting Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/accrual-vs-cash Why revenue isn't always money in the bank and profit isn't the same as cash: the difference between accrual and cash accounting, explained in plain language. When does a sale count? The moment you agree to it and send the bill, or the moment the money lands in your account? Your answer decides whether you're doing **accrual** or **cash** accounting, and it changes how every report reads. ## Two moments, not one *** Every sale has *two* moments: ```mermaid theme={null} flowchart LR M1["📋 Moment 1
Work done · Invoice sent
March"]:::moment M2["💵 Moment 2
Cash received
May"]:::moment M1 -->|"time passes"| M2 ACC(["Accrual records the sale here"]):::accrual CASH(["Cash records the sale here"]):::cash ACC -.-> M1 CASH -.-> M2 classDef moment fill:#eef2ff,stroke:#4f46e5,color:#312e81 classDef accrual fill:#dcfce7,stroke:#16a34a,color:#14532d classDef cash fill:#fef3c7,stroke:#d97706,color:#78350f ``` * The moment you **earn** it: you deliver the goods, finish the work, send the invoice. * The moment you **get paid**: the cash arrives. Sometimes these happen together (you buy coffee, you pay at the counter). Often they don't: you finish a job in March but the customer pays in May. The two methods disagree about which moment to record. ## Cash accounting: record when money moves *** **Cash accounting** is the simple one: you record a transaction **only when the cash changes hands**. You write down money in and money out, and you record nothing until money moves. It works like your personal bank statement. You don't note that a friend *promised* to pay you back. You note it when they actually do. Small businesses like it because it's easy and it mirrors the bank balance you can see. It can mislead you about timing. Do \$50,000 of work in December but get paid in January, and cash accounting says December earned **nothing**. That's tidy for taxes but a poor picture of what the business did. ## Accrual accounting: record when it's earned *** **Accrual accounting** records a transaction **when it's earned or incurred, not when the cash moves**. Finish the work and send the invoice, and that's revenue *now*, even if payment is weeks away. Receive a bill for electricity you've already used, and that's an expense *now*, even if you pay it later. It captures *promises* as well as cash: * Accrual records money customers owe you (but haven't paid) as revenue and as an asset called **accounts receivable**. * It also records bills you owe (but haven't paid) as expenses and as a liability called **accounts payable**. This gives a truer picture of how the business is *really* doing in a period. That is because it matches the income to the work that earned it. That's why larger businesses (and the rules they answer to) use it. | | **Cash accounting** | **Accrual accounting** | | - | - | - | | **Records revenue when** | Cash arrives | Work is done / invoice sent | | **Records expenses when** | Cash is paid | Bill is incurred | | **Shows you** | What's in the bank | What you've really earned and owe | | **Best for** | Simplicity, small operations | An accurate picture over time | This is the same job, **\$50,000 of work done in December, paid in January**, booked under each method: | The \$50,000 job | December *(work done)* | January *(customer pays)* | | - | - | - | | **Cash accounting** records revenue | \$0 | \$50,000 | | **Accrual accounting** records revenue | \$50,000 | None *(cash just arrives)* | The sale and the \$50,000 are the same, but the methods book them in different months. Accrual ties the revenue to the **work** in December. Cash waits for the **money** in January. ## Why revenue isn't "money in the bank" *** Under accrual accounting, **revenue means money earned, not money received**. You can book \$10,000 of revenue this month and have **none of it** in your account yet, because the customers haven't paid. So when you read an [Income Statement](/en/start-here/fundamentals/accounting/financial-statements) and see revenue, don't picture a full bank account. Picture *work that has been done and billed*. The cash may already be here, may arrive next month, or may never arrive at all if someone fails to pay. ## Why profit isn't cash *** The same gap explains why **a profitable business can still run out of cash.** Profit is revenue minus expenses. Under accrual, both can include things where no cash has moved yet. So your Income Statement can show a healthy profit while your bank account runs dry, because customers are slow to pay. The reverse happens too: you can have plenty of cash (a big upfront payment) yet little profit. That's why there are two different reports. The Income Statement shows **profit**. The [Cash Flow Statement](/en/start-here/fundamentals/accounting/financial-statements) shows the **actual cash**. You need both to understand a business. ## Next steps *** > [!NOTE] > > **Next up** > > See how these pieces run together, period after period, in [The accounting cycle](/en/start-here/fundamentals/accounting/accounting-cycle). # Assets, liabilities & equity Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/assets-liabilities-equity The accounting equation explained with everyday analogies: what you own, what you owe, what's yours, and why Assets = Liabilities + Equity always balances. Every business (and honestly, every person) can describe its financial life with three words: **assets**, **liabilities**, and **equity**. Get these three and the accounting equation falls into place. Let's use a house. ## The three words, in plain terms *** * **Assets**: everything you **own** that has value. Your house, your car, the cash in your account, the money customers still owe you. * **Liabilities**: everything you **owe** to someone else. Your mortgage, your car loan, an unpaid bill. * **Equity**: what's **yours** after you pay off the debts. It's the leftover. Say your house is worth \$300,000 (an asset). You still owe \$200,000 on the mortgage (a liability). The part that's truly yours (your **equity**) is \$100,000. What you own, minus what you owe, is what's yours: $$ Assets - Liabilities = Equity $$ | Term | Plain meaning | House example | | - | - | - | | **Asset** | What you own | The \$300,000 house | | **Liability** | What you owe | The \$200,000 mortgage | | **Equity** | What's left over for you | The \$100,000 that's yours | ## The equation that ties them together *** You just saw the equation one way. Move Liabilities to the other side and you see the same idea in reverse. This is the form accountants use, called the **accounting equation**: $$ \underset{\$300{,}000\ \text{house}}{\text{Assets}} \:=\: \underset{\$200{,}000\ \text{mortgage}}{\text{Liabilities}} \:+\: \underset{\$100{,}000\ \text{yours}}{\text{Equity}} $$ It's the same sentence written two ways. The first asks *what's truly mine?* The second asks *how did I fund everything I own?* Nothing changes but the order. The business paid for everything it **owns** in one of two ways: with **money it borrowed** (liabilities) or with **money that's its own** (equity). So the total value of what you own always equals the sum of those two sources. ## Why it always balances *** The equation can **never** be out of balance, by design. If something changes on one side, something else has to change to keep it even. * **You buy a \$20,000 car with a loan.** Assets go up by \$20,000 (the car). Liabilities go up by \$20,000 (the loan). Still balanced. * **You pay off \$5,000 of that loan with cash.** Assets drop by \$5,000 (cash leaves). Liabilities drop by \$5,000 (debt shrinks). Still balanced. * **The business earns \$10,000 in profit.** Assets go up by \$10,000. Equity goes up by \$10,000 (it's yours to keep). Still balanced. Every real-world event touches the equation in a way that keeps both sides equal. That is the rule that makes accounting trustworthy. If your books *don't* balance, you know immediately that something in the records is wrong. ## Next steps *** > [!NOTE] > > **Next up** > > You've got what a business owns, owes, and keeps. The other half of the picture is what it earns and spends. See [Revenue, expenses & costs](/en/start-here/fundamentals/accounting/revenue-and-expenses), and how profit feeds back into equity. # Chart of accounts Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/chart-of-accounts What a chart of accounts is, why it keeps financial data organized, how it ties accounting together, and how it maps to the account hierarchy in Midaz. Think of accounting as a giant filing cabinet of money movements. The **chart of accounts** is the labels on the drawers. It's the organized list of every "bucket" a business uses to sort its transactions. Without it, the records would be an unsearchable pile. ## What a chart of accounts is *** A **chart of accounts** lists, in a defined structure, all the accounts a business uses to record its financial activity. Each account is a category: a place to put a certain kind of transaction. Think of how you might organize your own money into labeled envelopes: *Rent*, *Groceries*, *Salary*, *Savings*. A chart of accounts is the same idea, more complete and consistent. You file every transaction into one of these named buckets, so you always know what it was for. ## How it's organized *** The chart groups accounts to match the concepts you've already met. Most charts follow the same five families: | Group | What goes here | Examples | | - | - | - | | **Assets** | What the business owns | Cash, equipment, money owed to you | | **Liabilities** | What the business owes | Loans, unpaid bills | | **Equity** | What's left for the owners | Owner's stake, retained profit | | **Revenue** | Money earned | Sales, service income | | **Expenses** | Money spent | Rent, salaries, supplies | The first three feed the [Balance Sheet](/en/start-here/fundamentals/accounting/financial-statements). The last two feed the Income Statement. So the chart of accounts is the bridge between raw transactions and the reports everyone reads. In practice, a simple one looks like this. Each family gets its own range of numbers, with individual accounts slotted inside: ``` 1000 Assets 1010 Cash 1020 Accounts receivable 1030 Equipment 2000 Liabilities 2010 Loans payable 2020 Taxes payable 3000 Equity 3010 Owner's equity 3020 Retained earnings 4000 Revenue 4010 Product sales 4020 Service income 5000 Expenses 5010 Rent 5020 Salaries 5030 Supplies ``` The numbers keep accounts in a fixed order and leave room to add new ones (a `1040` for inventory, say) without disturbing the rest. ## How it makes financial data usable *** A good chart of accounts is what makes financial data **usable**: * **Consistency**: the same kind of expense always lands in the same place, so reports are reliable. * **Clarity**: anyone can see, at a glance, where money goes. * **Scale**: whether you have ten transactions or ten million, they all have a clear home. Without it, [double-entry](/en/start-here/fundamentals/accounting/double-entry-bookkeeping) entries would have nowhere consistent to land, and no one could assemble the [financial statements](/en/start-here/fundamentals/accounting/financial-statements). ## How it connects in Lerian *** In accounting, the chart of accounts is the structure that organizes your records. In a **ledger system**, that same idea becomes an **account hierarchy**, a tree that groups balances, movements, and the business entities behind them: ```mermaid theme={null} flowchart TD A["Chart of accounts"]:::root --> B["Assets"]:::family A --> C["Liabilities"]:::family A --> D["Equity"]:::family A --> E["Revenue"]:::family A --> F["Expenses"]:::family B --> B1["Cash"]:::leaf B --> B2["Accounts receivable"]:::leaf B --> B3["Equipment"]:::leaf F --> F1["Rent"]:::leaf F --> F2["Salaries"]:::leaf F --> F3["Supplies"]:::leaf classDef root fill:#f3f4f6,stroke:#6b7280,color:#111827 classDef family fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef leaf fill:#eff6ff,stroke:#93c5fd,color:#1e3a8a ``` In **Midaz**, that hierarchy lives inside a Ledger, so you can group and nest accounts to mirror the structure of a real business. [Accounting in Lerian](/en/start-here/fundamentals/accounting/accounting-in-lerian) shows how this idea and the other accounting ideas map onto the product. > [!NOTE] > > **See also in Core Banking** > > This same structure becomes an account hierarchy in a ledger. See [The building blocks](/en/start-here/fundamentals/core-banking/building-blocks) and [Designing your ledger plan](/en/start-here/fundamentals/core-banking/designing-your-ledger-plan). ## Next steps *** > [!NOTE] > > **Next up** > > Once you file every transaction into the right account, those totals roll up into reports. Meet them in [Financial statements](/en/start-here/fundamentals/accounting/financial-statements). # Debits and credits Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/debits-and-credits What debit and credit mean in a banking system: the two ends of a money movement, and why one balance is a wallet to you and a liability to the ledger. Two words trip up almost everyone the first time they read a banking system: **debit** and **credit**. They sound like accounting jargon, but they name the two ends of a money movement. A debit is where money comes **from**. A credit is where it **goes**. ## Debit is out, credit is in *** Every movement of money leaves one account and arrives in another. Those two ends have names: * A **debit** is the account money moves **out of** (the **source**). * A **credit** is the account money moves **into** (the **destination**). When you send R\$100 to a merchant, your account is **debited** (money out) and the merchant's account is **credited** (money in). One movement has two sides. ```mermaid theme={null} flowchart LR S["Your account
(source)"]:::debit M(("Movement
R$100")):::bal D["Merchant account
(destination)"]:::credit S -->|"debit · R$100 out"| M M -->|"credit · R$100 in"| D classDef debit fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef credit fill:#fde68a,stroke:#d97706,color:#78350f classDef bal fill:#f3f4f6,stroke:#6b7280,color:#111827 ``` This is how your bank statement already reads: money leaving your account shows as a debit, money arriving shows as a credit. ## Your wallet is not the whole story *** The everyday intuition and the accounting meaning part ways here. In your **wallet**, money in is good, and money out leaves you with less. When your bank says it **credited** your account, your balance went **up**. A **debit** took money away. So it's tempting to read *credit = add, debit = subtract*. But that's your wallet's point of view. The **ledger** that holds your money sees the same balance another way. To the institution, your balance is money it **owes you**, not something it owns. Whether a debit or credit grows or shrinks a balance depends on that balance's persisted direction, not account type alone. So keep the two ideas apart: * **Wallet thinking** asks: did *my* number go up or down? * **Accounting thinking** asks: which account did this movement leave (**debit**), and which did it arrive in (**credit**)? The accounting meaning is the reliable one, and it never changes: **a debit is the source, a credit is the destination**. Whether that raises or lowers a given balance is a *separate* question. The direction persisted on that balance answers it. ## Assets and liabilities: the two sides of the ledger *** Each balance in a Ledger has a **direction**. That direction, not an account category alone, decides whether a debit or credit changes its available amount. In Midaz, a balance direction is `debit` or `credit`: * A balance with direction **`debit`** increases its available amount on a debit and decreases it on a credit. * A balance with direction **`credit`** decreases its available amount on a debit. On a credit, Midaz repays the [overdraft](/en/products/midaz/balance-overdraft) in use first, and any remainder increases its available amount. An account type can supply a default direction, but Midaz applies the direction persisted on the balance. For every **[asset](/en/products/midaz/assets)** you define (BRL, USD, a loyalty point), the Ledger automatically keeps an external account named after it (`@external/BRL`, `@external/USD`). You can also define your own named external accounts. > [!NOTE] > > The same R\$100 is an **asset** in your wallet and a **liability** on the institution's Ledger. Both are right. They are the two sides of the same movement. [The outside world](/en/start-here/fundamentals/core-banking/external-accounts-and-reconciliation) follows the asset side across the boundary. ## Debits always equal credits *** **Total debits always equal total credits**. Every movement is recorded on both sides at once: the same amount out of the source and into the destination. The two sides match exactly. If they don't, something is wrong, and the books say so. Take that R\$100 payment. R\$100 leaves your account as a debit and R\$100 arrives in the merchant's account as a credit. One event makes two entries with equal totals: ```mermaid theme={null} flowchart LR D["Your account
DEBIT R$100"]:::debit C["Merchant account
CREDIT R$100"]:::credit D --- BAL{{"Total debits R$100
= Total credits R$100"}}:::bal C --- BAL classDef debit fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef credit fill:#fde68a,stroke:#d97706,color:#78350f classDef bal fill:#dcfce7,stroke:#16a34a,color:#14532d ``` The money didn't appear or vanish. It moved from one account to another, and the matching debit and credit prove it. This matching is the basis of **double-entry bookkeeping**, which records every movement twice, once as it leaves and once as it arrives. > [!TIP] > > An **[operation](/en/products/midaz/operations)** is the smallest Midaz record of a balance effect. A non-pending transfer can produce a source debit and destination credit. Pending or canceled flows can also include `ON_HOLD` or `RELEASE` operations. > [!NOTE] > > **See also in Core Banking** > > See what debit and credit mean from the ledger's side in [How money is recorded](/en/start-here/fundamentals/core-banking/double-entry-explained). ## Next steps *** > [!NOTE] > > **Next up** > > Debits and credits only make sense as a pair. See how they work together in [Double-entry bookkeeping](/en/start-here/fundamentals/accounting/double-entry-bookkeeping). # Double-entry bookkeeping Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/double-entry-bookkeeping Why every transaction touches two accounts so nothing gets lost or invented: the idea behind double-entry bookkeeping, with simple everyday examples. **Double-entry bookkeeping** sounds technical, but you already understand the idea: **money never vanishes or appears. It always moves from somewhere to somewhere else.** Double-entry is the habit of recording *both* ends of that movement, every time. ## One event, two sides *** Think about handing a friend \$10 for lunch. Two things happened at once: **your** wallet went down by \$10, and **their** wallet went up by \$10. One event, two effects. Accounting insists you write down **both**. Every transaction touches **at least two accounts**: one giving, one receiving. That's why it's called *double*-entry. Equal value on the other side must match the **value** recorded on one side. The movement is not always physical cash, but the two amounts always agree. So a transaction is **one event with two connected effects**, not a single line floating on its own. Recording both keeps everything in balance: ```mermaid theme={null} flowchart LR A["One business
event"]:::event --> B["Effect 1
one account changes"]:::effect A --> C["Effect 2
another account changes"]:::effect B --> D["Equal value
on both sides"]:::equal C --> D D --> E["Books stay
balanced"]:::balanced classDef event fill:#f3f4f6,stroke:#6b7280,color:#111827 classDef effect fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef equal fill:#fde68a,stroke:#d97706,color:#78350f classDef balanced fill:#dcfce7,stroke:#16a34a,color:#14532d ``` This is the same balance rule from [debits and credits](/en/start-here/fundamentals/accounting/debits-and-credits): one account gets a debit, another gets a credit, and the two totals agree. ## Why bother recording it twice? *** Recording both sides feels like extra work. It is also a lie detector. * **Nothing gets lost.** If money left an account, it *must* show up somewhere else. * **Nothing gets invented.** Money can't appear out of thin air. For it to land somewhere, it had to come from somewhere. * **Errors reveal themselves.** If the two sides don't match, you know instantly that something's wrong, before it becomes a real problem. A single-entry list (just "money in, money out") can't do any of this. Double-entry turns the record into something you can **trust and prove**, which is why banks and ledger systems build on it. ## A simple example *** **Paying rent, \$1,000 in cash:** ```mermaid theme={null} flowchart LR Cash["Cash (an asset)
− $1,000
money left"]:::cash Rent["Rent Expense
+ $1,000
where it went"]:::rent Cash -->|"$1,000 moves"| Rent classDef cash fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef rent fill:#fee2e2,stroke:#dc2626,color:#7f1d1d ``` | Account | Effect | | - | - | | **Cash** (an asset) | Goes **down** \$1,000: money left | | **Rent expense** | Goes **up** \$1,000: that's what the money was for | The \$1,000 didn't disappear. It moved from your cash into the cost of rent: two accounts, one matched movement, a clear source and a clear destination. Money coming *in* works the same way in reverse. Take a \$2,000 customer payment: **Cash** goes up, and **Revenue** goes up to record where it came from. You'll write both of these out properly (debit and credit, side by side) in [Journal entries](/en/start-here/fundamentals/accounting/journal-entries). ## How it keeps the equation balanced *** Remember **Assets = Liabilities + Equity**? Double-entry is what keeps that equation true after every transaction. Because you record each event with equal and opposite effects, the two sides of the equation can never drift apart. The bookkeeping habit and the balancing rule are the same idea, viewed from two angles. > [!NOTE] > > **See also in Core Banking** > > Core banking uses this same both-sides rule. See [How money is recorded](/en/start-here/fundamentals/core-banking/double-entry-explained). ## Next steps *** > [!NOTE] > > **Next up** > > See how you write a transaction down, step by step, in [Journal entries](/en/start-here/fundamentals/accounting/journal-entries). # Financial statements Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/financial-statements The three reports that summarize a business's money (the Balance Sheet, Income Statement, and Cash Flow Statement) and what each answers, in plain language. All those carefully recorded transactions add up to **financial statements**. These are the summaries that turn thousands of tiny entries into a picture anyone can read. There are three main ones, and each answers a different question about the business. You don't need to know how to build them, just what each one tells you. ## The three statements at a glance *** | Statement | The question it answers | Think of it as | | - | - | - | | **Balance Sheet** | What do we own and owe *right now*? | A snapshot | | **Income Statement** | Did we make a profit *over a period*? | A highlight reel | | **Cash Flow Statement** | Where did the cash actually *move*? | A bank-account story | ## The Balance Sheet: a snapshot in time *** The **Balance Sheet** is a photograph of the business at a single moment. It lists everything the company **owns** (assets), everything it **owes** (liabilities), and what's **left over for the owners** (equity). It's the [accounting equation](/en/start-here/fundamentals/accounting/assets-liabilities-equity) (*Assets = Liabilities + Equity*) printed as a report. If you want to know how healthy a business is *today*, this is where you look. ## The Income Statement: profit over time *** The **Income Statement** (also called the *Profit & Loss* or *P\&L*) covers a stretch of time: a month, a quarter, a year. It starts with the **money earned** (revenue), subtracts the **money spent** (expenses), and shows whether the business ended up with a **profit or a loss**. Where the Balance Sheet is a snapshot, this is the story of what happened *between* two snapshots. ## The Cash Flow Statement: where the cash moved *** The **Cash Flow Statement** tracks **cash and cash equivalents** (shortened to *cash* on this page) going in and out over a period. A business can look profitable on paper yet still run out of cash, for example if customers haven't paid their bills yet. Accrual accounting recognizes revenue when a business earns it, and expenses when the business incurs them, not when cash moves. Cash-flow reporting tracks whether the business has the liquidity to pay its bills. ## How they fit together *** The three are views of the same reality: ```mermaid theme={null} flowchart TD A["Income Statement
Did we make a profit?"]:::is --> B["Profit changes
equity"]:::link D["Cash Flow Statement
Where did cash move?"]:::cf --> E["Cash balance
changes"]:::link B --> C["Balance Sheet
What do we own & owe now?"]:::bs E --> C classDef is fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef cf fill:#fef3c7,stroke:#d97706,color:#78350f classDef bs fill:#dcfce7,stroke:#16a34a,color:#14532d classDef link fill:#f3f4f6,stroke:#6b7280,color:#111827 ``` * The **Income Statement** shows whether you earned a profit. * That profit flows into **equity** on the **Balance Sheet**. * The **Cash Flow Statement** explains why the cash on that Balance Sheet went up or down. Read together, they tell you whether a business is profitable, solid, and able to pay its bills. Anyone who lends money or makes a decision needs those three facts. > [!NOTE] > > **See also in Core Banking** > > See how a ledger's records are proved against the outside world in [The outside world](/en/start-here/fundamentals/core-banking/external-accounts-and-reconciliation). ## Next steps *** > [!NOTE] > > **Next up** > > See why profit and cash differ, and when each one enters the records, in [Accrual vs. cash accounting](/en/start-here/fundamentals/accounting/accrual-vs-cash). # Journal entries Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/journal-entries How you record a transaction, step by step: from debits and credits to writing it down, with T-accounts and real examples like paying rent. You've met [debits and credits](/en/start-here/fundamentals/accounting/debits-and-credits) and [double-entry](/en/start-here/fundamentals/accounting/double-entry-bookkeeping) as ideas. You write a transaction down as a **journal entry**, the basic unit of recording. ## What a journal entry is *** A **journal entry** is the record of a single transaction. It names the accounts involved, gives the amount, and marks which side (debit or credit) each account is on. Think of it as the sentence accounting uses to describe an event. Every entry has the same three parts: * **Which accounts** are affected (at least two). * **How much** the amount is. * **Which side** each account sits on: debit (left) or credit (right). And it follows one unbreakable rule you already know: **total debits must equal total credits**. If they don't, the entry is wrong before you've even finished writing it. ## The steps, every single time *** Recording any transaction is the same short routine. Walk through it slowly the first few times and it becomes automatic. 1. **What happened?** Describe the event in plain words: "we paid rent," "a customer paid us." 2. **Which accounts does it touch?** Every event hits at least two. One gives, one receives. 3. **Does each account go up or down?** Decide the direction for each. 4. **Translate up/down into debit/credit.** Use the account type to know which side that means. 5. **Check the balance.** Debits on the left, credits on the right. The two totals must match. ```mermaid theme={null} flowchart TD A["1 · What happened?"]:::step --> B["2 · Which accounts
are affected?"]:::step B --> C["3 · Did each account
go up or down?"]:::step C --> D["4 · Translate into
debit or credit"]:::step D --> E["5 · Check:
debits = credits"]:::check classDef step fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef check fill:#dcfce7,stroke:#16a34a,color:#14532d ``` Step 4 is the one that trips people up, so keep the cheat sheet from [debits and credits](/en/start-here/fundamentals/accounting/debits-and-credits) handy: | Account type | To increase it | To decrease it | | - | - | - | | **Assets** (what you own) | Debit | Credit | | **Liabilities** (what you owe) | Credit | Debit | | **Equity** (what's yours) | Credit | Debit | | **Revenue** (money earned) | Credit | Debit | | **Expenses** (money spent) | Debit | Credit | ## T-accounts in practice *** A **T-account** is a way to picture one account as a big letter **T**: debits on the left, credits on the right. A journal entry is what you get when you write down the matching halves of two (or more) T-accounts at once. ``` Cash (an asset) Rent expense ----------------------- ----------------------- Debit (+) | Credit (-) Debit (+) | Credit (-) ----------------------- ----------------------- | $1,000 $1,000 | ----------------------- ----------------------- ``` The left side of one account lines up with the right side of another. That mirror is the entry. ## Example 1: paying rent in cash *** **What happened:** the business paid \$1,000 for rent. * It touches two accounts: **Cash** and **Rent expense**. * **Cash** goes *down*: money left the business. Cash is an asset, so a decrease is a **credit**. * **Rent expense** goes *up*: that's what the money was for. Expenses increase with a **debit**. Written as a journal entry: | Account | Debit | Credit | | - | - | - | | **Rent expense** | \$1,000 | | | **Cash** | | \$1,000 | Debits (\$1,000) equal credits (\$1,000). The entry balances. It reduces cash and recognizes rent expense for the period. Both effects are on the record. ## Example 2: receiving payment for a cash sale *** **What happened:** a customer paid the business \$2,000 for a cash sale. * It touches **Cash** and **Revenue**. * **Cash** goes *up*: money arrived. Cash is an asset, so an increase is a **debit**. * **Revenue** goes *up*: that's where the money came from. Revenue increases with a **credit**. | Account | Debit | Credit | | - | - | - | | **Cash** | \$2,000 | | | **Revenue** | | \$2,000 | Again, debits equal credits, and the money has a clear source and destination. Cash was debited this time and credited last time. The same account moves in opposite directions, depending on whether money came in or went out. If the payment settles an earlier invoice, the credit is to Accounts Receivable rather than Revenue. > [!NOTE] > > **See also in Core Banking** > > In a ledger system a journal entry becomes a transaction made of operations. See [How money moves](/en/start-here/fundamentals/core-banking/how-money-moves) and [The building blocks](/en/start-here/fundamentals/core-banking/building-blocks). ## Next steps *** > [!NOTE] > > **Next up** > > Every entry posts to an account. See where that list of accounts comes from in the [Chart of accounts](/en/start-here/fundamentals/accounting/chart-of-accounts). # Revenue, expenses & costs Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/revenue-and-expenses What revenue, expenses, and costs are, told apart in plain language: the words that drive the Income Statement and why the difference matters. Two words show up everywhere in accounting: **revenue** and **expenses**. They're the money a business *earns* and the money it *spends*. Get these two straight and the [Income Statement](/en/start-here/fundamentals/accounting/financial-statements), the report that says whether you made a profit, reads like a simple subtraction. ## Revenue: the money you earn *** **Revenue** is the amount a business earns from doing what it does: selling a product, providing a service, charging for a subscription. A business recognizes revenue when it earns it. That moment may differ from the moment cash arrives. Picture a bakery. Every loaf it sells brings in revenue. Add up a day's sales and that total is the day's revenue. Everything else measures against that inflow. Revenue is about what you earned, not necessarily the cash sitting in your account today. [Accrual vs. cash](/en/start-here/fundamentals/accounting/accrual-vs-cash) covers that difference. For now, think of revenue as *money earned from the work*. ## Expenses: the money you spend to earn it *** An **expense** is a cost a business recognizes in a period to keep running and earn revenue: rent, salaries, electricity, flour for the bakery. It may or may not involve a cash payment in that same period. Expenses are the fuel. You can't sell bread without buying flour and paying the baker. The point of accounting is to know what they are, so you can tell whether the revenue was worth it. ## Cost: close to expense, but not identical *** People use **cost** and **expense** as if they mean the same thing, and in casual talk they nearly do. The distinction is small: * A **cost** is what you *pay* for a resource: the price of acquiring it. Buying an oven for the bakery has a cost. * An **expense** is a cost *counted against the revenue of a period*: the portion that's "used up" in earning this stretch's income. The flour baked into today's bread is an expense today. A **cost** becomes an **expense** once it's used up in the work of earning revenue. The oven is a cost when you buy it. The slice of its wear-and-tear that helped make this month's bread becomes an expense this month. | Term | Plain meaning | Bakery example | | - | - | - | | **Revenue** | Money earned from the work | Selling loaves | | **Cost** | What you pay to acquire something | Buying the oven | | **Expense** | A cost used up to earn this period's revenue | The flour baked today, the rent this month | "Cost" leans toward *acquiring*, and "expense" leans toward *using up to earn revenue*. Follow one bag of flour through the bakery and the whole chain falls into place: ```mermaid theme={null} flowchart LR A["Buy flour
cost"]:::cost --> B["Bake the bread
expense"]:::expense B --> C["Sell the bread
revenue"]:::revenue C --> D["Revenue − expenses
profit or loss"]:::profit classDef cost fill:#fef9c3,stroke:#ca8a04,color:#713f12 classDef expense fill:#fed7aa,stroke:#ea580c,color:#7c2d12 classDef revenue fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef profit fill:#dcfce7,stroke:#16a34a,color:#14532d ``` ## Why they matter to the Income Statement *** These two words are the entire engine of the [Income Statement](/en/start-here/fundamentals/accounting/financial-statements): * Start with **revenue**: the amount recognized as earned. * Subtract **expenses**: the costs recognized for that period. * What's left is **profit** (or, if expenses were bigger, a **loss**). A month at the bakery, in one line: $$ \underbrace{\$1{,}000}_{revenue} - \underbrace{\$700}_{expenses} = \underbrace{\$300}_{profit} $$ This is a simple view. Revenue minus expenses tells you whether the business reported profit or loss over a period. A full statement can group and present those amounts in more detail. That profit flows into **equity**. Earn a profit and, before any distributions to owners, the owners' stake in the business grows. Run a loss and it shrinks on the same basis. This links back to [Assets, liabilities & equity](/en/start-here/fundamentals/accounting/assets-liabilities-equity): the Income Statement is the story of *how* equity changed over a period. ## Next steps *** > [!NOTE] > > **Next up** > > See how you write down every change to the five account families in [Debits and credits](/en/start-here/fundamentals/accounting/debits-and-credits). # What is accounting? Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/what-is-accounting The core idea behind accounting: a trustworthy record of money in, money out, and what a business owns versus what it owes. **Accounting** is the practice of keeping a clear, honest record of a business's money. It covers everything of value the business owns or owes, cash on hand included. Think of it as a diary that answers three questions at any moment: what came in, what went out, and where do we stand right now. A business wants to know what it owns, what it owes, and whether the two add up. Accounting is how it keeps that picture accurate, day after day. ## The three things every business tracks *** Accounting watches three flows: * **Money coming in**: sales, payments from customers, loans received, money the owners put in. * **Money going out**: rent, salaries, supplies, loan repayments. * **What's owned vs. what's owed**: the cash, equipment, and money others owe you, balanced against the debts you still have to pay. A good record keeps these connected. If money moved, write it down. If something is owned or owed, account for it. Controls and reconciliation help identify missing or inconsistent records. ## Why it has to be trustworthy *** Imagine running a shop where you *think* you have money but aren't sure. You can't pay suppliers with a guess, prove to a bank that you're worth lending to, or tell if you're making a profit. Accounting uses records and controls to make financial information checkable. A balanced entry is an arithmetic check: it confirms the recorded sides match, but does not by itself prove authorization, classification, or completeness. | Without good accounting | With good accounting | | - | - | | You guess how much you have | Your records show how much you have and why | | Money can quietly go missing | Controls and reconciliation help catch missing records | | You can't prove anything to others | Auditors and banks can verify it | | Profit is a mystery | Profit is a number you can see | > [!NOTE] > > **See also in Core Banking** > > Banking platforms exist to keep the same trustworthy-record promise. See [Core banking fundamentals](/en/start-here/fundamentals/core-banking/what-is-core-banking). ## Next steps *** > [!NOTE] > > **Next up** > > See why accounting matters the moment software starts holding money in [Why accounting matters](/en/start-here/fundamentals/accounting/why-accounting-matters). # Why accounting matters? Source: https://docs.lerian.studio/en/start-here/fundamentals/accounting/why-accounting-matters The "so what?" for builders: why double-entry is a system requirement, what balancing does and does not guarantee, and why financial systems rely on it. You already know *what* accounting is: an honest record of money in, money out, and what's owned versus owed. That record matters for what you build: a ledger, a wallet, a payments flow, a banking platform. The moment software starts holding other people's money, it inherits accounting's rules whether it names them or not. The same ideas that keep a shopkeeper's books honest keep your system from quietly losing or inventing a customer's balance. ## Money is a promise, and promises need a ledger *** A balance in an app is a **promise**, not cash sitting in a box. The promise is a claim that some amount belongs to someone and can be moved or withdrawn. Lose the record, or let it drift, and the money effectively doesn't exist, or worse, exists twice. That's why every financial product, underneath the UI, is a record-keeping problem first. Transfers, fees, settlement, and statements all sit on top of one question: who owns what, right now? Accounting is the discipline that has answered that question reliably for centuries. ## Why double-entry is a system requirement, not a convention *** Imagine a customer moves \$50 from one wallet to another. If the first wallet goes down by \$50 *and* the second goes up by \$50, matching recorded totals let the system check its internal record of that transfer. If only one side gets recorded, the mismatch is a signal to investigate rather than proof that the business event was correct. That's why double-entry exists. It gives a transaction a checkable constraint: the recorded sides must match. Encode that as a rule and you get a consistency control: * **A movement records its participating accounts.** The record identifies the accounts affected by the transaction. * **The recorded sides must equal.** Matching totals make the entry arithmetically checkable. * **A mismatch surfaces immediately.** If the recorded sides do not match, the transaction can be rejected before the inconsistency compounds. Midaz applies this directly: it rejects a transaction when its resolved source, destination, and send totals differ. That check is valuable, but it does not prove authorization, account selection, classification, valuation, or complete business correctness. ## Balance is a consistency control *** Balanced records make one part of a transaction continuously testable: the recorded amounts agree. Matching debits and credits detects a recorded amount mismatch. In accounting, *Assets = Liabilities + Equity* is a statement-level equation, not a runtime assertion Midaz applies after each operation. Records can balance while an account is wrong, a transaction lacks authorization, a value has the wrong classification, or another required record does not exist. Financial systems still rely on this control. Recording both sides gives balance a useful tripwire: when it breaks, the recorded amounts are inconsistent and the system must investigate before proceeding. Balanced records keep the amounts behind a balance consistent. You still need reconciliation and separate controls to trust it fully: ```mermaid theme={null} flowchart LR A["User sees
a balance"]:::step --> B["System keeps
ledger records"]:::step B --> C["Each movement
has two sides"]:::step C --> D["Books stay
balanced"]:::step D --> E["Recorded amounts
are consistent"]:::trust classDef step fill:#dbeafe,stroke:#2563eb,color:#1e3a8a classDef trust fill:#dcfce7,stroke:#16a34a,color:#14532d ``` ## Financial systems are accounting systems wearing different clothes *** Strip a core banking platform down to its foundation and you find a ledger. Strip the ledger down and you find double-entry accounting, enforced by code instead of by a clerk with a pen. The product vocabulary changes (*accounts*, *transactions*, *operations*, *balances*), but the same accounting ideas remain, now at scale and in real time. That shapes what you build: * **Accounting is the data model**. Accounts, entries, and balances are the app's source of truth. * **The safety properties use accounting controls.** A balanced posting detects mismatched recorded amounts. Authorization, classification, and completeness require additional controls. * **The hard problems come from accounting at scale**. You handle many transfers at once, keep every copy of the data in agreement, and prove what happened long after the fact. All of it comes down to keeping that balanced record correct across millions of movements. Learn the accounting once and a lot of system design stops feeling arbitrary. > [!NOTE] > > **See it in the product** > > These ideas have direct counterparts in Lerian and Midaz: accounts, transactions, operations, and balanced movements. See how they map in [Accounting in Lerian](/en/start-here/fundamentals/accounting/accounting-in-lerian), or step into the [Core banking fundamentals](/en/start-here/fundamentals/core-banking/what-is-core-banking). ## Next steps *** > [!NOTE] > > **Next up** > > Start with [Assets, liabilities & equity](/en/start-here/fundamentals/accounting/assets-liabilities-equity), the equation everything rests on. # The building blocks Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/building-blocks The five core nouns of core banking (Organization, Ledger, Asset, Account, and Balance), each in one sentence, in the order they depend on each other. Walk into a library and the structure is obvious before anyone explains it. There is the library itself, the catalog that organizes everything, and the shelves. There is also what sits on each shelf right now, and the *kind* of thing a shelf holds. A core banking system has five pieces that line up the same way. You only need to see how each one rests on the one before it. ## They stack in order *** Each block depends on the one above it: a shelf sits in a library, a balance sits in an account. Here they are, top to bottom. * **Organization**: your company, the outer boundary of everything you run. The *library building itself*. All your records live inside it and belong to it. * **Ledger**: one self-contained book of records. The *catalog*. You can keep more than one, say one per business line or per region. Each ledger keeps its own independent, balanced set of books. * **Asset**: the *kind* of value you track, such as a currency like USD, loyalty points, or anything countable. The *category of thing on a shelf*. The system tracks the unit separately from the amount, so it knows that 100 of one thing isn't 100 of another. * **Account**: a container tied to one asset. A non-external account can have one or more keyed balance records. An external account has exactly one `default` balance. A *single shelf*. Every movement of money has accounts on both sides. * **Balance**: one keyed record of the amount an account holds, including available and held amounts. Each balance record has its own sending and receiving settings. What sits *on the shelf at this moment*. > [!NOTE] > > An **Organization** can hold many **Ledgers**. A **Ledger** holds many **Accounts**. An **Account** always has one **Asset** and can carry one or more keyed **Balance** records. Read top to bottom, each block is the home of the next. ```mermaid mermaid theme={null} flowchart TB O["Organization
your company"] L["Ledger
one book of records"] Acc["Account
holds value, sends & receives"] Bal["Balance
the amount held right now"] As["Asset
the kind of value"] O --> L L --> Acc Acc --> Bal As -.-|"defines the unit"| Acc classDef box fill:#e8f0fe,stroke:#4285f4,color:#333; classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class O,L,Acc,As box; class Bal bal; ``` ## A balance is a result, not a setting *** A **balance** is the **result** of every movement into and out of the account, added up. You do not type it in or adjust it by hand. Money arrives, money leaves, and the balance is where that leaves you. You cannot edit a balance directly, so the books stay trustworthy. Recorded movements with two sides each *move it into the shape it has*. > [!TIP] > > A balance isn't always one single number you can spend. Part of it can be **available** (yours to use now) while part is **held**, set aside for a movement that hasn't finished. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > See the building blocks in practice: [Core entities](/en/products/midaz/core-entities), [Ledgers](/en/products/midaz/ledgers), [Accounts](/en/products/midaz/accounts), [Balances](/en/products/midaz/balances), and [Assets](/en/products/midaz/assets). # Designing your ledger plan Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/designing-your-ledger-plan How to model your own business as a set of accounts: a simple, worksheet-style method for designing a chart of accounts before you build anything. By now you know the pieces: accounts, balances, movements, the rules that govern them. Now you put them to work on *your* business. The goal is to move from "I understand the terms" to "I can model what my company does". A **ledger plan** (sometimes called a **chart of accounts**) is a *deliberate classification* of the accounts your business needs, and how they relate. It is not a list of accounts you rush to create. Designing it well, up front, saves you from painful restructuring later. ## Think rooms before you build *** Imagine designing a house. Before you pour any concrete, you decide what each room is for (kitchen, bedroom, office) and who's allowed in. You don't start laying bricks and figure out the floor plan afterward. A ledger plan works the same way. You decide what each account is *for*, what rules it follows, and how money flows between rooms, before you create anything. The four steps below are that method. ## Step 1: List your real-world actors *** Start away from the software entirely. On paper, list every real-world party that touches money in your business. Don't worry about structure yet. Just name them. A typical list looks like this: * **Customers**: the people or companies who hold value with you * **Treasury**: your own operating funds * **Revenue**: money you earn * **Fees**: charges you collect on movements * **Settlement**: money in transit to or from the outside world * **Expenses**: money you pay out This is your raw material. Every business has its own version of this list. ## Step 2: Decide what needs its own truth *** Not every actor needs its own account. The test is simple: **does this thing need its own separate, trustworthy balance, its own truth?** If you need to know, at any moment, exactly how much value sits with this actor, it needs its own account. If it's just a label or a detail of something else, it doesn't. > [!TIP] > > As a rule of thumb, if you'd ever want to ask "how much is in *here* right now?" then that's an account. If two things should never share a balance, they should never share an account. ## Step 3: Classify and group with three questions *** For each account you kept, ask **three universal questions**. Together they tell you how to structure and group your accounts. | Ask yourself | What it's about | | - | - | | Do these accounts need a **rule that validates** what they are or how they behave? | Classification: enforcing that an account is a certain *kind*, with its own constraints. | | Do I need to **slice them for reporting**? | Labeling: tagging accounts so you can later filter and report by group (region, tier, department). | | Do I need to **group them operationally** around a customer or wallet? | Operational grouping: bundling several accounts that belong together for one owner. | These three questions are independent. An account might need all three, or just one. Keep them separate in your mind: ```mermaid mermaid theme={null} flowchart TD A["An account in your plan"] --> Q1{"Needs a rule that
validates its kind?"} Q1 -->|yes| C["Give it a classification"] A --> Q2{"Needs to be sliced
for reporting?"} Q2 -->|yes| L["Give it a reporting label"] A --> Q3{"Belongs to a customer
or wallet group?"} Q3 -->|yes| G["Put it in an operational group"] classDef q fill:#fff8e1,stroke:#f4b400,color:#333; class Q1,Q2,Q3 q; ``` The big mistake here is to collapse these three into one. A *classification* controls what kind an account can be. A *reporting slice* is how you group an account in a report. An *operational group* is which accounts belong to one customer. Each is different, and treating them as one tangled thing is how ledger plans become unmanageable. ## Step 4: Sketch the movements *** Finally, draw the arrows. For each kind of movement your business makes, sketch which account is the source and which is the destination. That sketch is the input you'll need when you later define reusable rules for those movements. ## A worked example: a simple wallet business *** Say you run a wallet app. Customers load money in, send it to each other, and you take a small fee on transfers. Walk the method: **Actors:** customers, your fee/revenue account, and a settlement account for money entering from the outside world. **Own truth?** Each customer wallet needs its own balance. So do the fees you collect. So does settlement, which mirrors the outside world. **Three questions:** * *Validation?* Customer wallets behave differently from your fee account, so they're a different **kind**. Classify them. * *Reporting slice?* You want to report customers by country, so add a **label** for region. * *Operational group?* A premium customer might hold several wallets, so **group** them together. **Movements:** a transfer moves value from one customer wallet to another, plus a small part into the fee account. Money entering the app moves from settlement into a customer wallet. ```mermaid mermaid theme={null} flowchart LR S["Settlement
(outside world)"] -->|load| C1["Customer wallet A"] C1 -->|transfer| C2["Customer wallet B"] C1 -->|fee part| F["Fee / revenue"] classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class C1,C2,F,S bal; ``` That's a complete ledger plan for a small business, sketched before touching any tool. ## Common first-timer mistakes *** * **Over-classifying.** Creating a dozen account kinds when two would do. Start coarse. Refine only when a real rule demands it. * **Mixing reporting into structure.** Don't bake a reporting slice (like "region") into an account's *kind*. Keep how you classify separate from how you report. * **Treating the plan as a list.** Rushing to create accounts before sketching movements leaves you reorganizing later. * **Skipping the "own truth" test.** Giving everything its own account, or cramming unrelated things into one, both cause pain. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > Those three questions map onto how Lerian models accounts: > > * *Validation rule?* → **Account Types** > * *Reporting slice?* → **Segments** > * *Operational grouping?* → **Portfolios** > > See it all together in [Accounting in Midaz](/en/products/midaz/accounting-in-midaz), then put your plan to work with the console [Setup path](/en/products/midaz/console/midaz-console-setup-path) and [Concepts map](/en/products/midaz/console/midaz-console-concepts-map). # How money is recorded Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/double-entry-explained Why every movement of money has two sides, what debit and credit mean in a ledger, and how double-entry keeps every transaction balanced and auditable. If you've ever looked at a banking system and felt lost the moment someone said "debit" and "credit", start here. You don't need an accounting background. You need one idea, and once it clicks, almost everything else in core banking falls into place. **Money never appears out of nowhere, and it never vanishes.** Every time money moves, it leaves one place and arrives at another. Recording *both* sides of that movement is the whole idea behind **double-entry accounting**. ## Money always comes from somewhere *** Think about pouring water between two buckets. The water that leaves the first bucket is exactly the water that fills the second. Nothing appears or disappears. It only changes place. You can always check that the amounts match. A core banking system records money the same way. Every movement has two parts: * **Where it came from**: the source * **Where it went**: the destination If a customer sends R\$100 to a merchant, the system doesn't just say "the merchant has R\$100 more". It records the *full story*: R\$100 **left** the customer and R\$100 **arrived** at the merchant. Two sides of one movement, always equal. > [!NOTE] > > It's called double-entry because the system records every movement on both sides, once as it leaves and once as it arrives. A single-sided record makes mismatches harder to detect. Recording both sides gives the system an arithmetic constraint to check. ## The two sides have names: debit and credit *** The two sides of a movement have traditional names. In this movement, they describe the recorded source and destination: * A **debit** is the entry on the account that money moves **out of**. * A **credit** is the entry on the account that money moves **into**. When the customer pays the merchant, the system records a **debit** on the customer's side and a **credit** on the merchant's side. Same amount, opposite directions. In accounting more broadly, debit and credit are sides of an entry. Whether either increases or decreases a balance depends on the account type and its configured direction. You'll sometimes see debit and credit described as "decrease" and "increase", but that's not always true. It depends on the kind of account. For the transfer shown here, **debit is the source and credit is the destination**. Don't treat that example as a universal rule for every account type. ## Why both sides are always required *** Because the system records every movement on both sides, the totals always have to match. The sum of everything that left equals the sum of everything that arrived. If they don't balance, something is wrong. The system won't let the movement through. ```mermaid theme={null} flowchart LR A["Customer account
(source)"] -->|"– R$100 · debit"| T(("Movement
R$100")) T -->|"+ R$100 · credit"| B["Merchant account
(destination)"] classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class A,B bal; ``` This rule (*the two sides must balance*) is a consistency control. Midaz validates that the source total, the destination total, and the sent value all match. This check catches a recorded amount mismatch, but it does not by itself prove authorization, classification, or completeness. You can still trace every recorded movement to its source and destination. > [!TIP] > > Each individual part of a movement, a single debit or a single credit, is an **operation**. A movement of money consists of operations that balance out. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > See these ideas in practice: [Transactions](/en/products/midaz/transactions) and the [Glossary](/en/start-here/glossary). # The outside world Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/external-accounts-and-reconciliation The doorway between your Ledger and the outside world: how external accounts work and how reconciliation proves your records match reality across systems. Everything so far has lived neatly inside your Ledger. But money doesn't stay inside. It arrives from banks, card networks, and other systems, and it leaves to them too. Two ideas explain how a self-contained Ledger connects to the world outside, and how you *prove* your records still match what really happened out there. Picture a building with a front door. The door doesn't store anything itself. It just marks the boundary between inside and outside. Your Ledger has a door like this. ## External accounts: the doorway to the outside *** An **external account** is the doorway between your Ledger and the world beyond it: banks, card networks, other systems. Money entering your Ledger comes *from* an external account. Money leaving goes *to* one. In Midaz, the default external account has `debit` direction. When R\$100 flows *in* to a customer, Midaz uses that external account as the source. Its debit increases the available amount and balances the credit on the receiving account. The direction does not mean the external account has a negative balance. An external balance created before Midaz 3.7.0 keeps the `credit` direction, so its available amount decreases when money comes in. > [!NOTE] > > Think of the building's front door again. The external account is that door. Its direction tells Midaz how to apply a debit or credit. It does not label a balance as missing money. ```mermaid mermaid theme={null} flowchart LR E["External account
(the doorway)"] -->|"+ R$100 in"| A["Customer account
(inside the Ledger)"] classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class A bal; classDef ext fill:#eef2ff,stroke:#6366f1,color:#333; class E ext; ``` ## Reconciliation: proving the books match reality *** Once you have a boundary, you need to check that what you recorded inside matches what the outside world recorded. That check is **reconciliation**: proving your internal records line up with external records (bank statements, processor reports, settlement files). You compare the two, line by line, and confirm they agree. When they don't, reconciliation is how you catch it: * **Missing** movements: something happened outside that your Ledger never recorded. * **Duplicated** movements: the same thing recorded twice. * **Mismatched** movements: amounts or details that don't line up. The timing depends on your business: some reconcile **continuously** as records arrive, others at the **end of each day**. Either way, the moment you connect to the outside world, you take on the job of proving the two sides still agree. > [!NOTE] > > Reconciliation is like **counting the till against the receipts** at the end of a shift. The cash drawer is your Ledger. The receipts are the outside record. Counting them against each other proves the books match what happened, and flags anything that doesn't. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > See these ideas in practice: [Transactions](/en/products/midaz/transactions) and the [Glossary](/en/start-here/glossary). # Account roles: Holders, Accounts, Aliases & Instruments Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/holders-accounts-aliases Understand the distinct roles of Holders, Ledger Accounts, account aliases, and CRM Instruments in Midaz. Midaz keeps the balance record, the party context, and the identifiers used to find an account separate. That separation makes each concern explicit. ## Accounts hold balances and movements An **Account** is the Ledger record that holds balances and receives movements. It is the transactional record. ## Holders represent people or companies A **Holder** is the CRM record for a person or company. A Holder supplies the party context that can be associated with Ledger Accounts. On the v2 API, an Account names its Holder in `holderId`. Unless the ledger requires a Holder, a non-external Account created without one belongs to your organization's own Holder. ## Aliases identify Accounts An **alias** is a friendly identifier for an Account. It helps people and systems refer to an Account without using its full identifier. ## Instruments associate CRM context with Accounts An **Instrument** is the CRM record that adds context to an Account's Holder. It carries the `ledgerId` and `accountId` and can hold banking details, regulatory fields, metadata, and related parties. An Instrument is not an alias. An alias identifies an Account. An Instrument adds Holder and CRM context to a Ledger Account. ```mermaid theme={null} flowchart LR ACC["Account
(balance and movements)"] -- holderId --> H["Holder
(person or company)"] I["Instrument
(optional CRM context)"] -.-> ACC I -.-> H AL["Alias
(friendly identifier)"] -.identifies.-> ACC classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class ACC bal; ``` ## Next steps > [!NOTE] > > **See it in Lerian** > > Explore [Accounts](/en/products/midaz/accounts) and [Instruments](/en/products/midaz/crm/alias-accounts). # How money moves Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/how-money-moves What counts as one movement of money, what its parts are called (transactions, operations, and holds), and where money sits before it finally settles. You already know that money never appears or vanishes. It moves from a source to a destination, and both sides get recorded. Now for the *movement* itself: what one complete movement is, the names of its pieces, and where the money sits before a movement finishes. Picture handing cash across a counter. The moment the cash leaves your hand and lands in the other person's, the whole exchange happened as one event. A banking system treats movement the same way, as one complete handover recorded in full at once. ## One movement, recorded in full *** A **transaction** is one complete movement of value: the whole event, start to finish. When a customer sends R\$100 to a merchant, that single transaction *is* the R\$100 changing hands. But you've already seen that every movement has two sides. So a transaction has smaller pieces: * An **operation** is one part of the movement: a single debit or a single credit. The R\$100 transfer is one transaction with two operations. One is a debit of R\$100 that leaves the customer. The other is a credit of R\$100 that arrives at the merchant. The two operations move the same amount in opposite directions, and the system records them together. > [!TIP] > > An operation is one part of a movement. A transaction is the whole movement. ## The shapes a movement can take *** The simplest movement has one source and one destination, but a single transaction can spread across more accounts. However many parts it has, it always balances. The common shapes: * **One-to-one**: one source, one destination. A plain transfer: customer out, merchant in. * **One-to-many**: one source, several destinations. The customer pays R\$103: R\$100 goes to the merchant and R\$3 to a fee account. Three operations, still balanced (R\$103 out = R\$100 + R\$3 in). * **Many-to-one**: several sources, one destination. A few accounts pooling money into a single fund. * **Many-to-many**: several sources and several destinations at once, like a marketplace splitting incoming payments across sellers and fees. The rule never changes, no matter how many parts there are. Everything that leaves must equal everything that arrives. > [!NOTE] > > Not every ledger supports all four shapes. Simpler systems may allow only one-to-one (or one-to-many) movements, while others handle the full many-to-many case in a single transaction. What's possible depends on the ledger you use. > [!NOTE] > > A transaction is **all-or-nothing**. Either every operation succeeds together, or none of them happen. The books never stay half-recorded. The name for this property is **atomicity**. ## Money in transit: holds and two-phase movements *** Many movements don't settle the instant they start. The system first **reserves** the amount: it's set aside, still in the account, but no longer free to spend. Then the transaction either **commits** (settles for good) or **cancels** (releases the reservation). This is a **two-phase** movement: reserve first, then commit or cancel. An account's money has two parts: * **Available balance**: what you can spend right now. * **Held balance**: what's reserved for a movement that hasn't finished. It is still yours, frozen in place until it settles or releases. > [!NOTE] > > Think of a hotel pre-authorization on your card. At check-in the hotel **reserves** an amount. It isn't gone, but you can't spend it. At check-out the charge **commits**, or the hold is **canceled** and the money frees up. ```mermaid mermaid theme={null} flowchart LR R["Reserve
amount held"] -->|"settles"| C["Commit
moves to destination"] R -->|"released"| X["Cancel
returns to available"] classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class R,C,X bal; ``` ## Spending control *** Once you can see money as *available* versus *held*, controlling spending becomes natural. At any moment, an account's money sits in one of three states: * **Available**: free to spend. * **Held**: reserved for a movement in progress (in transit). * **Blocked**: frozen on purpose, set aside so it can't move at all. On top of that, **limits** can cap movement. A limit sets a ceiling on how much can flow. Together, these answer a common question about why an account can't spend. Usually the reason is a hold, a block, or a limit, not missing money. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > See these ideas in practice: [Transactions](/en/products/midaz/transactions), [Operations](/en/products/midaz/operations), and [Balances](/en/products/midaz/balances). # The rules that govern movement Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/routes-and-fees The reusable transaction routes that keep each kind of money movement recorded correctly, and why a fee is just a few more operations on the same journey. You know how money moves and how it's recorded. But who decides the *rules*? When a payment happens, something has to check that the right kinds of accounts take part. It must also record the right parts the same way every time. And when a fee shows up, where does it come from? Think of a paper form built for one kind of request. Someone designed it once: the boxes it has, the line for who's allowed to sign, the rule for how it's filed. After that, any clerk just fills in the details, and every request of that kind comes out identical, with no guessing. That's the idea behind a route. You set the rule once, and it applies the same way every time. ## A route is a reusable rule for one kind of movement *** A **route** is a reusable rule for one *kind* of movement. It answers three questions, once, so you don't answer them again on every transaction: * **Who can be the source?** Which accounts may send. * **Who can be the destination?** Which accounts may receive. * **Which parts belong in the record?** Which debits and credits the movement should produce. Define the rule once. When a Ledger has route validation enabled, it checks transactions of that kind against the route. A "customer payment" route spells out that a customer account sends, a merchant account receives, and exactly which operations to write. When a Ledger has route validation enabled, it checks the record of each movement of that kind against the rule. It also checks that the participating accounts are valid for it. Without that setting, a route is still a reusable definition but does not enforce those checks. > [!NOTE] > > A route is like a **form template** for one kind of transaction. It lays out the intended participants and booking. When a Ledger has route validation enabled, it checks movements against the route. A fee is just an extra line on that form. ## Fees are more operations *** A transaction consists of **operations**, each one a single debit or credit. A fee is *more operations* in the same transaction, sending value into a fee or revenue account. Take the one-to-many example from before. A customer pays **R\$103**: * **R\$100** lands at the **merchant**. * **R\$3** lands in a **fee account**. That's one transaction with three operations. The customer's R\$103 leaving balances exactly against R\$100 + R\$3 arriving. No value appears and no value disappears. The fee is real money that moves to a real account, recorded like any other part. ```mermaid mermaid theme={null} flowchart LR C["Customer
– R$103"] --> R{{"Route
(rule + parts)"}} R -->|"+ R$100"| M["Merchant"] R -->|"+ R$3"| F["Fee account"] classDef bal fill:#fff8e1,stroke:#f4b400,color:#333; class M,F bal; ``` ## When you'd reach for routes and fees *** You don't need a route for a one-off movement. You reach for one when a *kind* of movement repeats and you must book it the same way every time: payments, transfers, settlements. And you add a **fee** whenever a movement should also send a slice of value into a revenue or cost account. You define these deliberately up front, as part of the ledger plan that comes next. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > See these ideas in practice: [Accounting Routes entities](/en/products/midaz/transaction-routing-entities) and the [Fees Engine](/en/products/midaz/fees/fees-engine-overview). # What is core banking? Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/what-is-core-banking A plain definition of core banking, what it manages (accounts, balances, transactions), and the five responsibilities we use to explain a modern core system. A **core banking system** is the central platform a financial institution runs on. It manages **accounts, balances, transactions, the customers behind them, and money moving in and out**, all in one place, as a single source of truth. Underneath all of it sits a trustworthy record of **who owns what** and **what moved**. The other jobs all connect to it by feeding it, moving value through it, reading it, and proving it's right. ## Why it's harder than it looks *** Keeping that record right is deceptively hard, and it's the reason most of the system exists: * **It must always balance**: money can't appear or disappear, ever. * **It has to stay correct at scale**: millions of movements, all consistent with each other. * **It must be provable**: to auditors and regulators, long after the fact. ## How we'll explain it: five jobs *** There are many ways to describe a core banking platform. In this guide we use **five core responsibilities**. This is how we organize the topic for learning, not an official taxonomy. | Job | What it does | | - | - | | **Record value** | Keeps the trustworthy record of who owns what. Everything else builds on this. | | **Move value** | Brings money in, sends it out, and transfers it between accounts. | | **Identify** | Registers the people and companies behind the accounts. | | **Report** | Turns the raw record into statements and reports that you and regulators can read. | | **Trace & prove** | Keeps an auditable trail of everything that happened. | The **Ledger** is the foundation, but it's only **one of the five**. A complete core banking system is all five of them together, not a Ledger with extras bolted on. The other four build on the Ledger once it records value. Capabilities like **fees** attach to it to extend it. You adopt these pieces one at a time, not as a single machine you switch on. The same handful of ideas (accounts, balances, movements) run through all of them. Learn those once, here, and the rest of the documentation gets much easier to follow. ## Next steps *** > [!NOTE] > > **See it in Lerian** > > See how these jobs map to real solutions in the [Core banking vision](/en/start-here/about-lerian/core-banking-vision) and [Products and plugins](/en/products/products-and-plugins). # Where to go next Source: https://docs.lerian.studio/en/start-here/fundamentals/core-banking/where-to-go-next How everything you learned about core banking shows up in Lerian and Midaz, and where to go next to start building, integrating, and running transactions. You've gone from "lost the moment someone said debit and credit" to modeling your own business as a ledger plan. That's the whole foundation. Next, see how it shows up in Lerian and where to start. ## How the concepts show up in Lerian *** Everything you just learned has a home in Lerian: * **Recording value**: the accounts, balances, and assets you learned about, and the double-entry that keeps them in check, all live in [Midaz](/en/products/midaz/what-is-midaz), the Ledger. It's the foundation everything else builds on. * **Moving value**: Midaz records transfers, operations, and holds as [transactions](/en/products/midaz/transactions). When value crosses the boundary with the outside world, [payment interfaces](/en/interfaces/introduction) such as Pix and TED carry it. Plenty of movement never crosses that boundary, and the Ledger records it. The routes and fees you saw come from Midaz's [transaction routing](/en/products/midaz/transaction-routing-entities) and the [Fees Engine](/en/products/midaz/fees/fees-engine-overview). * **Identifying who owns what**: the holders behind your accounts live in [CRM](/en/products/midaz/crm/crm-overview). * **Reading the record back**: you build [account statements](/en/products/midaz/building-account-statements) from Midaz operations, and [Reporter](/en/products/reporter/what-is-reporter) builds richer reports and templates for audits, analytics, and decisions. * **Deciding what may happen**: [Tracer](/en/products/tracer/what-is-tracer) evaluates your rules and spending limits. It returns an allow, deny, or review decision before a transaction executes. And when you design your own ledger plan, the three questions (validation, reporting slice, operational grouping) map to **Account Types, Segments, and Portfolios** in Midaz. ## Ready to start? *** Pick the path that fits your team: > [card] [Build with the API](/en/start-here/getting-started) > > Integrate programmatically. Start here, then go deeper with the Guides and API Reference for the integration details. > [card] [Set it up in the Console](/en/platform/console/about-lerian-console) > > Prefer a UI? Do the whole setup by hand in the Lerian Console, no code required. > [!NOTE] > > Need a term? The [Glossary](/en/start-here/glossary) defines every word from this section. Keep it bookmarked, and see how the pieces come together in [Building a complete core banking](/en/products/building-a-complete-core-banking). # Where to start Source: https://docs.lerian.studio/en/start-here/fundamentals/introduction A quick map of the Fundamentals section of Start Here: two plain-language series, Core Banking and Accounting, and which one to read first. The **Fundamentals** section of Start Here is where you build intuition before touching anything Lerian-specific. It holds two short, plain-language series that build a foundation for core banking from two angles. Accounting explains trustworthy financial records. Core Banking explains how a complete banking platform applies them. > [card] [Accounting](/en/start-here/fundamentals/accounting/what-is-accounting) > > Explains the language underneath it: assets, liabilities, debits, credits, and how the books stay balanced. > [card] [Core Banking](/en/start-here/fundamentals/core-banking/what-is-core-banking) > > Explains a complete core banking platform: its ledger foundation, accounts, balances, value movement, customer identity, reporting, and auditability. They sit side by side because they answer different questions. Core Banking shows you the *machine*. Accounting shows you the *grammar* behind it. ## Which one first *** | If you want to… | Start with | | - | - | | Understand how a complete core banking platform works, including its ledger foundation | **Core Banking** | | Understand the accounting language behind it | **Accounting** | | Understand both | **Accounting**, then **Core Banking** | > [!TIP] > > If you're unsure, start with **Accounting**. The vocabulary it teaches makes everything in Core Banking (and the rest of the docs) easier to follow. # Getting started Source: https://docs.lerian.studio/en/start-here/getting-started Begin with Lerian: evaluate the platform, choose a deployment model, and run your first double-entry transaction with Midaz. Use this page to evaluate the platform or to start building. > [!NOTE] > > **New to core banking?** If terms like *Ledger*, *debit and credit*, or *chart of accounts* aren't yet second nature, start with the fundamentals first. They make everything here easier to follow. > > **[Begin with Core Banking Fundamentals](/en/start-here/fundamentals/core-banking/what-is-core-banking)** ## Evaluating the platform *** Follow these steps to understand the platform's capabilities, architecture, and deployment options. **1. Understand why Lerian exists** Learn what problems the platform solves and who we built it for, in business terms. **[Why Lerian →](/en/start-here/about-lerian/why-lerian)** **2. Explore the architecture** Lerian organizes around four pillars (**Ledger**, **Transactional Services**, **Governance**, and **Connectivity**) that form a composable financial platform. **[Read the Core Banking vision →](/en/start-here/about-lerian/core-banking-vision)** **3. Choose a deployment model** Decide between Lerian Cloud (SaaS), fully managed by Lerian, or self-hosted BYOC based on your compliance requirements and operational maturity. **[Compare deployment models →](/en/start-here/evaluate-and-deploy/deployment-models)** **4. See it in action** Explore real-world use cases: digital banking, global portfolios, Pix, and more. **[Browse use cases →](/en/products/midaz/use-cases)** ## Building with Lerian *** Follow these steps to go from zero to your first double-entry transaction. Choose the path that matches your deployment model. > [tab] SaaS (Lerian Cloud) > > **1. Receive your credentials** > > Your Lerian onboarding team provides you with API credentials (client ID and secret) and the base URL for your environment. > > **2. Authenticate and get your token** > > Use the Access Manager Auth API to exchange your credentials for a JWT access token. This token contains your tenant context. You don't need to manage a tenant ID explicitly. > > **[Learn how to authenticate →](/en/platform/access-manager/using-access-manager)** > > **3. Make your first API call** > > Include the token as a Bearer token in the `Authorization` header of every request. Your calls are automatically scoped to your tenant. > > **[Make your first API call →](/en/reference/products/midaz/quick-start-guide)** > > **4. Create your first organization** > > Follow the same API flow as any Midaz deployment: create an organization, a ledger, assets, and accounts. > > **[Follow the recommended workflow →](/en/products/midaz/recommended-workflow)** > > > [!TIP] > > > > The API surface is identical across deployment models. Lerian Cloud requires a Bearer token and scopes requests to the authenticated tenant. A permitted non-production BYOC deployment can have authentication disabled. > [tab] BYOC (self-hosted) > > **1. Choose your deployment model** > > Decide how you want to run the platform. BYOC gives you full control over data, security, and networking, in your own cloud or on-premises. > > **[Compare deployment models →](/en/start-here/evaluate-and-deploy/deployment-models)** > > **2. Understand the architecture** > > Lerian organizes around four pillars (**Ledger**, **Transactional Services**, **Governance**, and **Connectivity**) that form a composable financial platform. Understanding this helps you model integrations correctly from day one. > > **[Read the Core Banking vision →](/en/start-here/about-lerian/core-banking-vision)** > > **3. Install Midaz** > > Midaz is Lerian's double-entry core ledger. Install it when you need to model accounts and record transactions. The other products stay modular, and you can adopt them one at a time. > > **[Install Midaz →](/en/products/midaz/midaz-setup)** > > **4. Create your first resources through the API** > > With Midaz running, create the essential building blocks: an organization, a Ledger, assets, and accounts. > > **[Make your first API call →](/en/reference/products/midaz/quick-start-guide)** > > **5. Follow the recommended workflow** > > Follow the end-to-end operational workflow, from resource setup to transaction routing and balance management. > > **[Follow the recommended workflow →](/en/products/midaz/recommended-workflow)** ## What's next? *** With your Ledger running and your first transactions created, pick the capability you want to add next. > [card] [Reconcile transactions](/en/products/matcher/getting-started/matcher-quick-start) > > Run your first automated reconciliation between a bank statement and your Ledger. > [card] [Validate in real time](/en/products/tracer/getting-started) > > Set up spending limits and validation rules to evaluate transactions before they proceed and return an ALLOW, DENY, or REVIEW decision for your authorization flow to act on. > [card] [Generate reports](/en/products/reporter/using-reporter) > > Create a report template and generate your first financial report from a configured data source. For Midaz data, connect Reporter to Midaz first. > [card] [Integration diagrams](/en/diagrams/introduction) > > Learn how the integration diagrams show the messages of a Brazil rail combining into a journey. # Glossary Source: https://docs.lerian.studio/en/start-here/glossary Key financial, ledger, and platform terms explained for non-technical audiences, a quick reference for language used across Lerian and Midaz docs. This glossary defines the core financial and platform terms used throughout Lerian's documentation. It helps product managers, sales teams, and anyone new to financial infrastructure quickly understand the language used in our guides. *** ## A *** ### Account The fundamental unit of value storage in a ledger. An account holds a balance denominated in a specific asset (e.g., BRL, USD). Accounts can represent account holders' accounts, internal settlement accounts, fee collection accounts, or any other container for tracking value. ### Account Type A classification that defines the nature and purpose of an account, such as checking, savings, escrow, or settlement. Account types enable proper transaction routing and consistent business rules across account categories. ### Asset A unit of value tracked in the ledger. Assets can be traditional currencies (BRL, USD, EUR), digital currencies (BTC, ETH), or custom units like loyalty points or academic credits. Every account links to exactly one asset. ### Atomic (Atomicity) A property of transactions where all operations either succeed together or fail together. There is no partial execution. If a transaction involves three operations (a debit, a credit, and a fee), either all three happen or none do. This prevents incomplete financial events. ### Audit trail A chronological record of every action and transaction in the system. Audit trails are immutable. Once recorded, an audit trail cannot change or be deleted. Regulatory compliance and dispute resolution require this. *** ## B *** ### Balance The current amount of an asset held in an account. Midaz tracks the **available** amount (ready for immediate use) and the **on hold** amount (reserved for pending transactions). ### Blast radius The scope of impact if a failure, misconfiguration, or security incident occurs. In multi-tenancy contexts, blast radius counts the tenants that suffer when something goes wrong in one tenant's scope. See also: **Tenant isolation**. ### BYOC (Bring Your Own Cloud) A deployment model where you run Lerian software on your own infrastructure, whether public cloud (AWS, GCP, Azure), private cloud, or on-premises. This gives you full control over data residency, security, and scaling. See also: **SaaS**. *** ## C *** ### CEL (Common Expression Language) A lightweight, type-safe expression language that Tracer uses for writing business rules. CEL lets analysts and compliance teams define validation logic without writing application code or requiring deployments. One example: "if transaction amount exceeds 10,000 and account type is personal, flag for review". ### Core banking A complete banking platform that combines a ledger foundation with the capabilities required to operate financial products. Those capabilities are accounts and balances, value movement, account holder identity, reporting, governance, connectivity, and auditability. A ledger is foundational, but it is not the whole core banking platform. ### Child account A sub-account created under a parent account, typically used for budgeting or organizational purposes. For example, an account holder's savings account might have child accounts for "Vacation Fund" and "Emergency Fund." Each child account tracks its own balance. *** ## D *** ### Double-entry accounting An accounting principle where every financial movement has a source and a destination of equal value. This ensures the system always balances. Midaz rejects a transaction whose source total, destination total and sent value differ. ### DSL (Domain-Specific Language) A simplified programming language designed for a specific domain. In Flowker, the DSL lets teams define workflow steps, conditions, and integrations using a structured format, without writing general-purpose code. *** ## E *** ### ERP (Enterprise Resource Planning) A business management software system (such as SAP, Oracle, or NetSuite) that integrates core processes like accounting, procurement, and inventory. ERPs are common data sources for reconciliation with Matcher. ### External account A special account in Midaz that represents value entering or leaving the system from outside. Midaz creates one for each asset, with the alias `@external/` followed by the asset code, for example `@external/BRL`. You can also create external accounts with an alias you choose. External accounts are boundaries between your ledger and the outside world. *** ## F *** ### Fail closed A safety posture where a system denies access by default when it cannot verify a required condition, rather than allowing access and risking a breach. In Lerian multi-tenancy, tenant resolution is fail-closed. When the JWT does not identify the tenant, or when the tenant configuration does not load, the system rejects the request. The request never falls back to a default or shared tenant. See also: **Tenant isolation**, **Multi-tenancy**. *** ## H *** ### Helm Chart A pre-configured deployment package for Kubernetes. Helm Charts contain all the instructions needed to install, configure, and upgrade software in a Kubernetes cluster. Lerian provides Helm Charts for deploying products in BYOC (self-hosted) environments. *** ## I *** ### Idempotency The property that an operation produces the same result whether executed once or multiple times. In financial systems, this prevents duplicate transactions. If you accidentally send a payment request twice, idempotency ensures the money only moves once. ### Immutable (Immutability) A property meaning "cannot change or be deleted after creation." This guarantees data integrity for compliance and auditing. *** ## K *** ### Kubernetes A platform for running and managing software applications at scale across multiple servers. Kubernetes automates deployment, scaling, and recovery, so applications stay available even when individual servers fail. *** ## L *** ### Ledger The core financial book that records all transactions, balances, and operations for an organization. Think of it as the single source of truth for a business unit's finances. An organization can have multiple ledgers for different purposes (e.g., retail operations, treasury). *** ## M *** ### Metadata Additional information attached to entities like accounts, transactions, or organizations. Metadata takes the form of key-value pairs. It enriches records for reporting and integration, and fee packages and Tracer rules can select on transaction metadata. ### Multi-tenancy An operating model where one deployment serves independent institution contexts (called tenants) with product-specific request scoping and storage isolation. Lerian Cloud operates multi-tenant. See also: **Tenant**, **Tenant isolation**. *** ## O *** ### Onboarding domain The part of Midaz responsible for structuring your financial ecosystem: creating organizations, ledgers, assets, accounts, portfolios, and segments. This is the "setup" phase before any transactions occur. ### Operation The atomic unit of movement in the ledger: a single debit or credit. Every transaction consists of one or more operations, which gives precise traceability for compliance and reporting. ### Operation Route A reusable template that defines the rules for one "leg" of a financial transaction. It specifies which accounts participate, in what direction (source/destination), and under what accounting annotation. ### Organization The top-level business entity in Midaz, typically a bank, fintech, or subsidiary. Each organization holds its own ledgers. *** ## P *** ### Pix Brazil's instant payment system, operated by the Central Bank of Brazil (BACEN). Pix enables real-time transfers 24/7 between individuals, businesses, and government entities. ### Portfolio A grouping of accounts belonging to the same account holder, business unit, or purpose. For example, a single account holder may hold checking, savings, and investment accounts across different currencies. A portfolio ties them together for a unified view. ### Plugin An optional extension that adds functionality to a specific Lerian product. Examples include Pix (instant payments), TED (bank transfers), and Payments (boletos and bill payment). All available plugins extend Midaz. *** ## R *** ### Reconciliation The process of comparing two sets of records (for example, your internal ledger against bank statements) to verify they match. Matcher automates this process by applying matching rules and flagging discrepancies. *** ## S *** ### Lerian Cloud (SaaS) Lerian's fully managed deployment model. Lerian operates the licensed platform modules and underlying infrastructure. Institutions use the supported product APIs and configuration surfaces. See also: **BYOC**. ### Segment A classification applied to accounts that share characteristics, like account holder tiers (VIP, Student, Business) or regional divisions. Segments enable differentiated rules, pricing, and benefits across your account holders. ### Settlement The process of finalizing a financial transaction, transferring the actual funds between institutions. Settlement accounts in Midaz are clearing points. Money waits there before it moves to its final destination (e.g., via Pix or TED to the central bank). ### Streaming Hub Lerian's event-delivery service. It sits at the edge between the platform's internal event stream and the systems you run outside it. It delivers each event you care about to a destination you own: a webhook, a cloud queue, or a cursor you pull. *** ## T *** ### Tenant A logically isolated institution context in a multi-tenant deployment. The supported product service defines its data model, authentication claims, routing, and backing resources. Do not assume one product's tenant model applies to another. See also: **Multi-tenancy**, **Tenant isolation**. ### Tenant isolation The controls that prevent another tenant from using one tenant's supported product service, data, configuration, and operations. Authentication and routing controls remain product-specific. See also: **Multi-tenancy**, **Tenant**. ### Terraform An infrastructure automation tool that provisions and manages cloud resources (servers, databases, networks, security groups) through declarative configuration files. Lerian provides Terraform templates for setting up BYOC infrastructure on AWS, GCP, or Azure. ### TED (Transferência Eletrônica Disponível) A Brazilian electronic bank transfer system for high-value or same-day transfers between financial institutions. Unlike Pix, TED operates only during business hours. In the Lerian ecosystem, the TED plugin connects Midaz to the TED network. ### Transaction A movement of value between accounts. Transactions can involve multiple operations (debits and credits), and Midaz processes them atomically. Either all operations succeed, or none do. This ensures no partial financial events occur. ### Transaction domain The part of Midaz responsible for executing financial movements: processing transactions, updating balances, and maintaining audit trails. ### Accounting Route (Transaction Route) A complete transaction blueprint composed of multiple Operation Routes. For example, a "Pix Transfer" route defines all the debits and credits involved, so every transaction of that type complies with double-entry accounting. Called **Accounting Route** in the Lerian Console and product docs. In the API it is the `transaction-routes` resource, and a transaction names it in `routeId`. *** ## W *** ### Webhook An automated notification sent from one system to another when a specific event occurs. # Welcome to our guides Source: https://docs.lerian.studio/en/start-here/welcome-to-our-guides Navigate the Lerian documentation, one tab per area of the platform, from the fundamentals to the products, the Brazil rails, the integration diagrams, and the API reference. Lerian's guides sit next to the API reference, one area of the platform per tab. Use the top bar to pick an area, then use the left sidebar to move inside it. ## How to navigate *** **1. Pick a tab in the top bar** Start Here holds the fundamentals, the getting-started path, and the glossary. Lerian Products holds the products and the platform services. Brazil Rails holds the rails and the interfaces. Integration Diagrams shows how the messages of a rail combine into a journey. API Reference holds the endpoints, and News holds the release notes. **2. Pick a section in the left sidebar** Each tab splits into sections. Lerian Products holds one section per product, plus a Platform section. Brazil Rails holds one section per rail, plus an Interfaces section. **3. Read the overview page first** Each section opens with an overview page. Read it first. The pages after it carry the detail, such as how the software works, how to integrate with it, and how to operate it. # About Midaz Console Source: https://docs.lerian.studio/en/products/midaz/about-midaz-console See how the standalone Midaz Console moved into the Lerian Console Midaz Module. Midaz v3.5.0 and later releases do not include the standalone Midaz Console. The **Midaz Console** was the visual administrative interface for Midaz. You used it to configure organizations, ledgers, accounts, assets, and transactions, with no direct API calls. From Midaz v3.5.0, Midaz no longer includes the Console. Its features moved into the **Lerian Console** as the [Midaz Module](/en/products/midaz/console/midaz-module). ## What changed *** The Midaz Console moved from a standalone interface to an integrated module in the Lerian Console. This change separates Midaz, the core ledger engine, from the platform tools that manage it. | Aspect | Before (prior to v3.5.0) | Now (v3.5.0+) | | :- | :- | :- | | **Distribution** | Bundled with Midaz | Part of the Lerian Console | | **Scope** | Standalone admin interface | Integrated product module with cross-product capabilities | ## For existing users *** If you run a Midaz version before v3.5.0, the Console remains part of your installation. It works as expected in those versions. > [!WARNING] > > Midaz v3.5.0 and later releases do not include the standalone Midaz Console. Migrate to the Lerian Console. ## Moving forward *** The [Midaz Module](/en/products/midaz/console/midaz-module) in the Lerian Console replaces the standalone Console. It adds unified authentication, cross-product navigation, and ongoing feature development. To see what the Midaz Module offers, read the documentation: > [card] [Midaz Module overview](/en/products/midaz/console/midaz-module) > > Full documentation for the Midaz Module within the Lerian Console. > [card] [Lerian Console](/en/platform/console/about-lerian-console) > > Learn about the unified platform for managing all Lerian products. # Auditability Source: https://docs.lerian.studio/en/products/midaz/auditability Understand the scoped audit mechanisms in Midaz: CRM protection events and optional Ledger transaction audit messages. Midaz does not provide one universal audit trail for every platform action. Its audit behavior is specific to the mechanism that produces the data. ## CRM protection audit events *** When CRM runs with envelope encryption, Midaz emits **Protection Audit Events** for encryption-protection activity. Midaz stores these events per Organization. You can read them through the [List Protection Audit Events](/en/reference/products/midaz/v2/get-audit-events) endpoint. This mechanism is not available in legacy encryption mode. The audit writer is best-effort: a failed audit emission is logged, but it does not block the CRM operation. Use protection audit events to investigate encryption-protection activity for an Organization. Do not interpret them as a complete record of every Ledger or platform action. ## Ledger transaction audit messages *** The Ledger publishes transaction audit messages only when `AUDIT_LOG_ENABLED` is `true`. Set the flag to `true` only after you configure your downstream consumer, its retention, and its investigation workflows. The Ledger sends these messages to the RabbitMQ exchange set in `RABBITMQ_AUDIT_EXCHANGE`, with the routing key set in `RABBITMQ_AUDIT_KEY`. Publishing is best-effort: Midaz logs a failed publish and does not block the transaction. Midaz does not expose them as a general queryable Ledger audit-record API. The receiving system owns retention, indexing, and investigation workflows. ## Designing your audit trail *** Choose the mechanism that matches the data you need to observe: * Use **Protection Audit Events** for CRM envelope-encryption activity. * Enable **Ledger transaction audit messages** only after you configure your downstream consumer to retain and process them. * Keep controls, retention, and evidence requirements in the system responsible for the data after Midaz emits it. > [!NOTE] > > For help designing an audit and retention architecture around Midaz, [contact us](https://lerian.studio/contact). # Setting up accounting in the Console Source: https://docs.lerian.studio/en/products/midaz/console/accounting-setup-in-console Walk through a Console-only guide to build your accounting model in Midaz, from planning a chart of accounts to running your first Pix payment. This guide shows you how to set up accounting in the Midaz Module of the Lerian Console. You use only the screens and forms in the Console, and you write no code. It is the Console companion to the developer-focused [Accounting Walkthrough](/en/products/midaz/accounting-walkthrough). You reach the same result through Console forms instead of API calls. It targets product managers, implementation teams, and developers who prefer to model their accounting in the UI. > [!NOTE] > > You will not see any JSON or API calls here. You do everything below through Console forms. To automate the same setup later, follow the technical reference each section links to. ## What you are building *** Configure your accounting routes deliberately. A route defines the source and destination Operation Routes for a direct transaction, or a Bidirectional Operation Route that covers both sides. With **Validate Routes** enabled, Midaz validates transactions against the configured route rules. Route validation is disabled by default. Enable it only after you configure the routes your Ledger needs. Cancellation is a source-only lifecycle action: it releases held funds on the source Account and does not involve a destination Account. Each layer builds on the one before it: **1. Plan your chart of accounts** Decide which balances your product needs (customer funds, fees, settlement, treasury, revenue). **2. Create Account Types** Define the categories that classify your accounts. **3. Create Accounts** Open the actual balance containers, each with a **Type** and an Asset. You select the Type for non-external Accounts. When you enable **External account**, the Type becomes `external` automatically. When **Validate Account Type** is enabled, the Type of every non-external Account must match a registered Account Type. **4. Create Accounting Routes** Set the rules for which accounts can join each transaction and how the ledger posts entries. > [!TIP] > > Work top to bottom. Routes are much easier to build once you already know which accounts represent customers, treasury, fees, and settlement. ## Step 1: Plan your chart of accounts *** In traditional accounting, a **Chart of Accounts (CoA)** is the master list of every account category your business uses: assets, liabilities, revenue, and expenses. It also defines how you classify each movement against those categories. In Midaz there is no single "Chart of Accounts" screen to fill in. Instead, your CoA emerges from the building blocks you create in the Console: Assets, Account Types, and Accounts. You plan it up front, mostly as a paper (or whiteboard) exercise. Before you open the Console, list the balances your product needs. For a typical payments product that might be: | Balance you need | What it represents | | - | - | | Customer funds | Money your end users hold | | Settlement | Funds waiting to clear | | Fee revenue | Fees you collect | | Fee expense | Fees you pay to providers | | Treasury | Your own internal operating funds | This list is your blueprint. The next steps turn each line into something concrete in the Console. > [!NOTE] > > Before any account can exist, it needs an **Asset**, the unit of value it holds (for example `BRL`). If you have not created your assets yet, start with [Creating an Asset](/en/products/midaz/console/creating-an-asset). ## Step 2: Create your Account Types *** **Account Types** are the categories that classify your accounts. Think of them as labels like `customer`, `treasury`, or `fee` that group accounts by their role. Later, Accounting Routes use these labels to decide which accounts a transaction can use. In the Console you create one Account Type per category from your blueprint, not one per individual customer. > [card] [Create an Account Type](/en/products/midaz/console/creating-an-account-type) > > Open the New Account Type form and define a category with a clear name and a stable key value. A typical payments setup uses these Account Types: | Account Type | Use it for | | - | - | | `customer` | Liquid customer balances | | `settlement` | Funds awaiting clearing | | `fee` | Fees collected as revenue | | `treasury` | Internal operations | | `expense` | Fees paid out to providers | > [!WARNING] > > The **Key Value** of an Account Type (for example `customer`) is what routes and accounts rely on. Keep it short, lowercase, and stable. You cannot change it later. To use a different key, create a new Account Type and recreate the accounts and routes that depend on it. > [!NOTE] > > The Account Types menu appears only after you enable **Validate Account Type** in your Ledger settings. To turn it on, see [Managing Ledgers](/en/products/midaz/console/managing-ledgers-via-console#ledger-settings). ## Step 3: Create your Accounts *** **Accounts** are the balance containers that hold value and that money moves between. Each account has a **Type** and one Asset (its currency). You select the Type for non-external Accounts. When you enable **External account**, the Type becomes `external` automatically. When **Validate Account Type** is enabled, the Type of a non-external Account must match a registered Account Type (external Accounts skip this check). A human-readable **alias** identifies it. `@customer_123_brl` is one common convention. For each line in your blueprint, create one Account in the Console. > [card] [Create an Account](/en/products/midaz/console/creating-an-account) > > Open the New Account form, choose its Type and Asset, and give it a clear alias. When you fill in the form, a few choices are permanent and worth getting right the first time: | Field | Why it matters | | - | - | | **Account Alias** | The name routes and transactions use to find the account. Cannot be changed after creation. | | **Type** | The Account Type that classifies it. Cannot be changed after creation. | | **Asset** | The currency or unit it holds. Cannot be changed after creation. | > [!WARNING] > > The Console locks Alias, Type, and Asset when you save the account. To change any of them, create a new account. Double-check before you save. ### Available and On Hold balances When you open an account in the Console, Midaz splits its balance into two **buckets**. You always know what you can spend and what the ledger holds back: | Bucket | What it means when you look at an account | | - | - | | **Available** | Money that is free to spend or send right now. This is the number that goes up and down with normal payments. | | **On Hold** | Money that a pending operation has reserved but not yet finalized. It still belongs to the account. The ledger sets it aside, and you cannot spend it until the hold is confirmed or cancelled. | Both amounts appear as exact decimal values (for example, `12.50`). There is no scale factor to apply when you read them. > [!NOTE] > > **On Hold** powers two-step payments. When you authorize a payment but do not yet capture it, the amount moves from **Available** to **On Hold**. Confirming the payment releases it to the destination. Cancelling returns it to Available. You see each of these movements on the account at every stage. ## Step 4: Create your Accounting Routes *** With **Validate Routes** enabled, each transaction must specify a valid Accounting Route in the ledger. An Accounting Route is a reusable rule for one kind of transaction, such as a *Pix transfer* or a *fee charge*. It answers three questions: * Which accounts can send on the **source** side? * Which accounts can receive on the **destination** side? * Which debit and credit **entries** should the ledger post when it runs? The Console builds these through a guided 3-step wizard, so you do not have to assemble anything by hand. > [card] [Manage Accounting Routes](/en/products/midaz/console/managing-accounting-routes) > > See how the Accounting Routes page works and what each part of the wizard does. > [card] [Create an Accounting Route](/en/products/midaz/console/creating-an-accounting-route) > > Walk through the 3-step wizard to define a route, its operation rules, and its entries. To decide how to shape a route, see [Accounting rules](/en/products/midaz/console/mc-accounting). It explains the choices in plain terms. > [accordion] Source, Destination, or Bidirectional? > > Each rule inside a route applies to one side of a transaction: > > * **Source**: the sending side (where value comes from). > * **Destination**: the receiving side (where value lands). > * **Bidirectional**: the same rule applies to both sides, for cases where one kind of account can both send and receive. > > A valid route needs at least one required Source **and** one required Destination, or a single required Bidirectional rule. A rule marked optional does not count, and a transaction may leave it unused. > [accordion] How should an account be validated? > > Each rule checks accounts in one of two ways: > > * **Account Type**: the rule accepts any account of a given category (for example, any `customer` account can send). Use this for flexible, scalable flows. > * **@Alias**: the rule accepts only one exact account (for example, only `@fee_revenue` can receive). Use this for fixed operational accounts like treasury, fees, or settlement. > [accordion] Which accounting scenario? > > Scenarios decide how the debit and credit entries get recorded: > > * **Direct Transaction**: a one-step movement, posted immediately. > * **Two-Step Transaction**: a hold-then-commit flow. It uses separate entries to reserve, confirm, and cancel funds, and it drives the **On Hold** bucket. > * **Reversal**: entries the ledger records to undo a completed transaction. > * **Overdraft**: entries the ledger records when a debit exceeds the account's available funds and draws on an overdraft line. > * **Block**: entries the ledger records when funds on an account are blocked or unblocked. > [!WARNING] > > Turn on **Validate Routes** in Ledger settings **only after** the routes you need already exist. If validation is on but a matching route is missing, those transactions will fail. ## Example: a simple Pix payment *** Let's run the whole flow in the Console for a basic **Pix cash-out**: a customer sends BRL out of their wallet to a settlement account. Assume your `BRL` asset already exists. **1. Create the Account Types** From the **Account Types** page, create: * `customer`: for end-user balances. * `settlement`: for funds leaving to the outside world. See [Creating an Account Type](/en/products/midaz/console/creating-an-account-type). **2. Create the Accounts** From the **Accounts** page, create: * `@customer_123_brl`: Type `customer`, Asset `BRL`. The customer's wallet. * `@external_brl`: Type `settlement`, Asset `BRL`. Where funds settle when they leave the ledger. See [Creating an Account](/en/products/midaz/console/creating-an-account). > [!NOTE] > > `@external_brl` is a regular, ledger-owned settlement Account. This example uses it so the route can validate the `settlement` Account Type. It is not the canonical external Account `@external/BRL`, which Midaz creates automatically together with the `BRL` Asset. The `@external/` alias prefix is reserved, so you cannot create that Account yourself. For money that actually enters or leaves Midaz, use `@external/BRL`. See [Common mistakes to avoid](/en/products/midaz/common-mistakes-to-avoid). **3. Create the Accounting Route** From the **Accounting Routes** page, start the wizard and build a `Pix cash-out` route: * A **Source** operation rule validating Account Type `customer` (the wallet sends). * A **Destination** operation rule validating Account Type `settlement` (the settlement account receives). * A **Direct Transaction** accounting scenario, with a debit entry on the source and a credit entry on the destination. While **Validate Routes** is off, the sidebar hides **Accounting Routes**. Open it from the page search (**Search pages...**). See [Creating an Accounting Route](/en/products/midaz/console/creating-an-accounting-route). **4. Turn on Validate Routes** Turn on **Validate Routes** in the [Ledger settings](/en/products/midaz/console/managing-ledgers-via-console#ledger-settings). The transaction form then shows the **Transaction Route** and **Operation Route** fields. **5. Run a transaction** Create a transaction that moves, say, `100.00 BRL` from `@customer_123_brl` to `@external_brl` using your `Pix cash-out` route. See [Creating a Transaction](/en/products/midaz/console/creating-a-transaction). **6. Check the result** Open each account and look at the balance: * `@customer_123_brl`: **Available** drops by `100.00`. * `@external_brl`: **Available** rises by `100.00`. Both movements belong to the same transaction, so the audit trail stays balanced. > [!TIP] > > For an authorize-then-capture flow, use a **Two-Step Transaction** scenario on the route. You see the amount move into **On Hold** when reserved, and out of it when you confirm or cancel. The New Transaction form in the Console posts direct transactions only. Create, confirm, and cancel a two-step transaction through the API (see [Two-Phase Transaction flow](/en/products/midaz/transactions)), then follow its balances on the account in the Console. ## What to do next *** To go deeper, use these technical references. They cover how to automate the setup, understand the entities, and turn ledger activity into reports: > [card] [Accounting Walkthrough (developer)](/en/products/midaz/accounting-walkthrough) > > The end-to-end developer version of this guide, including the data model and double-entry detail. > [card] [Accounting overview](/en/products/midaz/accounting-in-midaz) > > How the core accounting primitives relate to one another. > [card] [Transaction Routing entities](/en/products/midaz/transaction-routing-entities) > > The technical model behind Accounting Routes, operation routes, and entries. > [card] [Balances](/en/products/midaz/balances) > > The full balance model behind available and on-hold amounts. # Adding a Portfolio to an Account Source: https://docs.lerian.studio/en/products/midaz/console/adding-portfolio-to-account Link a Midaz Account to a Portfolio from the Console, either from the Accounts list or the edit form, to group Accounts under one customer or wallet. Use Portfolios to group Accounts that belong to the same Entity. To add an Account to a Portfolio, follow one of these procedures: ## Adding from the Accounts page If the Account does not belong to a Portfolio yet, add it directly from the **Accounts** page. Follow these steps: **Step 1** Click the **Link portfolio** option in the **Portfolio** column of the Account you want to add. **Step 2** The Console displays the form to edit the Account. **Step 3** Switch to the **Portfolio** tab and select the **Portfolio** you want. **Step 4** Click the **Save** button to link the Account to the selected Portfolio. ## Add by editing the Account You can also edit the **Account** to add or change its Portfolio: **Step 1** On the **Accounts** page, find the Account you want to edit. Click the three dots () in the **Actions** column. Select **Details** to open the Account details page. **Step 2** Click the **Edit** button. In the edit form, select the **Portfolio** you want. **Step 3** Click the **Save** button to confirm the procedure. > [card] API equivalent > > [Update an Account endpoint](/en/reference/products/midaz/v2/update-account) # Adding a Segment to an Account Source: https://docs.lerian.studio/en/products/midaz/console/adding-segment-to-account Assign a Segment to an existing Account from the Console to classify it by shared characteristics and apply the associated benefits or business rules. Segments group Accounts by shared characteristics and benefits. To learn more about Segments, see the [Segments](/en/products/midaz/segments) page. To add a Segment to an Account, follow these steps: **Step 1** Open the **Accounts** page. Find the Account you want to add to the Segment. In the **Actions** column, click the three dots (). Select **Edit**. **Step 2** The edit sheet opens on the **Account Details** tab. Select the Segment from the **Segment** list. **Step 3** Click the **Save** button to confirm. > [card] API equivalent > > [Update an Account endpoint](/en/reference/products/midaz/v2/update-account) # Checking Transaction details Source: https://docs.lerian.studio/en/products/midaz/console/checking-transaction-details Open the full details of a Transaction in the Console to audit its movements, review the Transaction Data tab, and edit its description when needed. To check the details of a transaction, follow these steps: **Step 1** On the **Transactions** page, find the transaction to check. In its **Actions** column, click the three dots (). Select **See details**. **Step 2** A page opens with the transaction summary. When the transaction has a scheme, the summary shows it. **Step 3** Then select the **Transaction Data** tab to see more information. > [!TIP] > > In the **Transaction Data** tab, edit the description if needed. # Creating a Ledger Source: https://docs.lerian.studio/en/products/midaz/console/creating-a-new-ledger Create a new Ledger in the Console to isolate Assets, Accounts, Routes, and Transactions, and configure Account Type or Route validation while you set it up. A Ledger isolates Assets, Accounts, Routes, and Transactions in one accounting workspace. Create a new Ledger when you need a separate balance domain, product line, environment, or accounting model. ## Before you start *** You need an existing Organization. If this is the first setup, create the Organization first in [Creating an Organization](/en/products/midaz/console/creating-an-organization). Decide what the Ledger boundary means before you create it. Do not use one Ledger for unrelated products that need different account structures, routes, or operational controls. ## Create the Ledger *** **Step 1** From the **Ledgers** page, click the **New Ledger** button in the top-right corner. **Step 2** The **New Ledger** form appears. **Step 3** In the **Ledger Details** tab, enter the Ledger name in the **Ledger Name** field. **Step 4** (Optional) To include metadata, select the **Metadata** tab. This tab displays two fields: **Key** and **Value**. * To add more metadata, click the plus (+) icon next to the first row. **Step 5** (Optional) Select the **Settings** tab to configure validation rules for this Ledger. * Enable **Validate Account Type** if Accounts must use registered Account Types. * Enable **Validate Routes** if Transactions must follow pre-configured Accounting Routes. **Step 6** After you complete the form, click **Save**. **Step 7** A success message appears at the top center. The main **Ledgers** page now lists the new Ledger. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Ledger Name | A clear name for the accounting workspace. Use a name that shows the product, country, environment, or business boundary. | `Brazil Payments Ledger` | | Metadata Key | Optional classification or integration field name. | `environment` | | Metadata Value | Value for the metadata key. | `production` | | Validate Account Type | Optional setting. Turn on when every new non-external Account in this Ledger must use a previously registered Account Type. Leave off if you will not classify Accounts by type yet. | `Enabled` | | Validate Routes | Optional setting. Turn on only after the Accounting Routes for this Ledger are planned or configured, because Transactions must match a valid route when this is enabled. | `Disabled` | > [!TIP] > > The fields in the Metadata tab are open. The tab has no predefined keys or values. Use consistent key names across your Organization, such as `environment`, `businessLine`, or `region`, so you can filter and audit Ledgers later. ## Ledger settings *** The **Settings** tab controls the validation rules for this Ledger. ### Validate Account Type When you enable this setting, every new non-external Account must use an Account Type registered for this Ledger. Enable it when you want operators to classify Accounts consistently, such as `customer`, `merchant`, `treasury`, or `fee`. > [!WARNING] > > After you enable **Validate Account Type**, the Ledger rejects any non-external Account without a valid Account Type. ### Validate Routes When you enable this setting, Transactions must match the Accounting Routes configured for this Ledger. Enable it only after you plan or configure your route model. > [!WARNING] > > If you enable **Validate Routes** before routes exist, any Transaction without a matching route fails validation. ## What to do next *** After you create the Ledger: 1. Review whether **Validate Account Type** and **Validate Routes** are correct for this Ledger. 2. Create at least one Asset in [Creating an Asset](/en/products/midaz/console/creating-an-asset). 3. If you need to change the validation rules later, use the **Settings** tab described in [Managing Ledgers](/en/products/midaz/console/managing-ledgers-via-console#ledger-settings). > [card] API equivalent > > [Create a Ledger endpoint](/en/reference/products/midaz/v2/create-ledger) # Creating a Portfolio Source: https://docs.lerian.studio/en/products/midaz/console/creating-a-portfolio Create a new Portfolio in the Console to group Accounts under a customer, business unit, or reporting boundary, and set an Entity ID for external systems. A Portfolio groups Accounts under a customer, business unit, or reporting boundary. ## Before you start *** You need an existing Organization and Ledger. Create a Portfolio when you want to group Accounts under a customer, business unit, product, or reporting boundary. ## Create the Portfolio *** To create a Portfolio, follow these steps: **Step 1** From the **Portfolios** page, click the **New Portfolio** button. **Step 2** The **New Portfolio** form opens on the right side of the screen. **Step 3** Fill in the fields and click the **Save** button. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Portfolio Name | Required name for the customer, business unit, or reporting group. Minimum 3 characters. | `Acme Retail Portfolio` | | Entity Id | Optional external entity or system identifier. The Console shows this field only when you create the Portfolio. You can update it later through the Portfolio update API when the new value is non-empty. | `customer_acme` | | Metadata Key | Optional classification or integration field name. | `relationshipManager` | | Metadata Value | Value for the metadata key. | `ops-team-1` | ## What to do next *** Now link the Portfolio to Accounts from [Adding Portfolio to Account](/en/products/midaz/console/adding-portfolio-to-account). You can also create Accounts that belong to it in [Creating an Account](/en/products/midaz/console/creating-an-account). > [card] API equivalent > > [Create a Portfolio endpoint](/en/reference/products/midaz/v2/create-portfolio) # Creating a Segment Source: https://docs.lerian.studio/en/products/midaz/console/creating-a-segment Create a new Segment in the Console to classify Accounts by shared characteristics, business rules, or reporting needs across your Ledger. A Segment classifies Accounts by shared characteristics or business rules. ## Before you start *** You need an existing Organization and Ledger. Create a Segment when a group of Accounts needs a shared classification for reporting, filtering, or fee rules. ## Create the Segment *** To create a Segment, follow these steps: **Step 1** From the **Segments** page, click the **New Segment** button. **Step 2** The **New Segment** form opens on the right side of the screen. **Step 3** In the **Segment Details** tab, enter the **Segment Name**. **Step 4** (Optional) Select the **Metadata** tab to add metadata. **Step 5** When the details are complete, click the **Save** button. **Step 6** The Segment appears in the list of Segments for your Ledger. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Segment Name | Required name for a group of Accounts with shared characteristics or rules. | `Retail Customers` | | Metadata Key | Optional classification or integration field name. | `region` | | Metadata Value | Value for the metadata key. | `BR-SP` | > [!TIP] > > The Metadata fields have no predefined keys or values. Use consistent key names across your Organization, such as `region`, `businessLine`, or `channel`. Consistent keys keep Segments useful for filtering and reporting. ## What to do next *** After you create the Segment, link it to Accounts from [Adding Segment to Account](/en/products/midaz/console/adding-segment-to-account). You can also create Accounts that belong to it in [Creating an Account](/en/products/midaz/console/creating-an-account). > [card] API equivalent > > [Create a Segment endpoint](/en/reference/products/midaz/v2/create-segment) # Creating a Transaction Source: https://docs.lerian.studio/en/products/midaz/console/creating-a-transaction Create a new Transaction in the Console using the 1:1 or n:n wizard to move Asset balances between source and destination Accounts by alias. A Transaction moves value between Accounts in a Ledger. Create one only after the Asset, source account, destination account, and any required Accounting Route are ready. ## Before you start *** Confirm that: * The source and destination Accounts exist in the selected Ledger. * Both Accounts use the Asset selected for the Transaction. * You know each Account alias. A leading `@` is a common convention, not a requirement. * Source accounts allow sending and destination accounts allow receiving. * If **Validate Routes** is on, the Transaction must match an existing Accounting Route. ## Create the Transaction *** **Step 1** From the **Transactions** page, click the **New Transaction** button. **Step 2** The **New Transaction** modal will open. Select the type of transaction you want to create: * **Simple 1:1** - Transactions using one source and one destination * **Complex n:n** - Transactions using more than one source or destination **Step 3** After selecting the transaction type, the **New Transaction** page opens with a step-by-step form: **1. Transaction Data** Fill in the basic transaction information: * (Optional) Add a **Transaction description** * If **Validate Routes** is on, select the **Transaction Route** * Enter the **Value** (amount) to transfer * Select the **Asset** for the transaction * (Optional) Enter the **Scheme** of the transaction, for example `PIX` or `CARD`. The Console saves it in upper case * (Optional) Turn on **Skip fees** to post the transaction without running the Fees Engine. The switch appears only when the Ledger allows skipping fees * (Optional) Turn on **Skip the Tracer** to post the transaction without the Tracer limits and rules. The switch appears only when the Ledger allows skipping the Tracer **Step 2** Click **Continue to the next step** to proceed to the accounts selection step. **3. Source / Destination** Specify the accounts involved: * Search for the **source account** by alias and select it * Search for the **destination account** by alias and select it * For complex transactions, you can add multiple sources and/or destinations > [!WARNING] > > You **must** use the account alias to perform transactions. Make sure you save it when you create your account. > > If you forget your alias, you can find it by [editing account information](/en/products/midaz/console/editing-account-information). **Step 4** Click **Continue to the next step** to proceed to the operations step. **5. Operations** Review and adjust the operation details: * For simple transactions (1:1), the Console fills the amounts automatically * For complex transactions (n:n), specify the amount for each source (debit) and destination (credit) * Expand each operation to add an optional **Operation description**. If **Validate Routes** is on, select its **Operation Route**. The selector marks optional operation routes with an **Optional** badge * Add metadata in the **Transaction Metadata** section > [!NOTE] > > For complex transactions, the sum of all source amounts must equal the sum of all destination amounts. > [!NOTE] > > If **Validate Routes** is on, the Console checks the Transaction Route at **Go to Review**. It checks the route again when you send. Select each required operation route with Direct Transaction entries on at least one operation of its side. A Bidirectional route can be on either side. **Step 4** When all the information is correct, click the **Go to Review** button. **Step 5** The Console shows a review page with a summary of all the transaction information: * Transaction value and asset * Source and destination accounts * Individual debit and credit operations * Metadata records (if any) **Step 6** Review the information carefully. If everything is correct: * Click **Send Transaction** to submit the transaction * Click **Send and Create another** to submit and immediately start a new transaction **Step 7** When the Tracer or the Ledger refuses the Transaction, the Console says why and nothing is posted. When the Ledger no longer allows a skip, reload the page and post again. **Step 8** On success, the Console shows **Transaction created** with the operations the Ledger recorded. Click **View Transaction** to open the transaction details page. ## Field guide *** **Transaction Data** | Field | What to enter | Example | | - | - | - | | Transaction description | Optional business description of the movement. | `Customer payment to merchant` | | Transaction Route | Shown when **Validate Routes** is on. Select the Transaction Route that the Transaction must match. | `Pix Transfer Route` | | Asset | Asset used by the Transaction. It must match the selected Accounts. | `BRL` | | Value | Total amount to move. For complex transactions, source totals must equal destination totals. | `100.00` | | Scheme | Optional payment scheme of the Transaction. The Console saves it in upper case. | `PIX` | | Skip fees | Shown when the Ledger allows skipping fees. Turn on to post the Transaction without running the Fees Engine. | `Disabled` | | Skip the Tracer | Shown when the Ledger allows skipping the Tracer. Turn on to post the Transaction without the Tracer limits and rules. | `Disabled` | **Source / Destination** | Field | What to enter | Example | | - | - | - | | Source | Account alias that will be debited. | `@customer_123` | | Destination | Account alias that will be credited. | `@merchant_456` | **Operations** | Field | What to enter | Example | | - | - | - | | Operation description | Optional description for the operation. | `Debit for the source account` | | Operation Route | Shown when **Validate Routes** is on. Select the Operation Route that this transaction leg must match. | `Checking account validation for Pix` | | Metadata Key | Optional classification or integration field name. | `externalReference` | | Metadata Value | Value for the metadata key. | `order_98765` | ## Transaction types explained *** ### Simple Transaction (1:1) Use for straightforward transfers between two accounts: * One source account (debit) * One destination account (credit) * Same amount debited and credited **Example**: Transfer \$100 from Customer A to Merchant B. ### Complex Transaction (n:n) Use for transactions involving multiple parties: * Multiple source accounts (debits) and/or multiple destination accounts (credits) * You can distribute amounts across accounts * Total debits must equal total credits **Examples**: * Payment with fees: * Customer pays \$103 * Merchant receives \$100 * Fee account receives \$3 * Consolidated payment: Multiple customers fund a single vendor payment > [!TIP] > > The fields in the **Transaction Metadata** section are open. There are no default keys or values. Use consistent key names across your Organization, such as `externalReference`, `orderId`, or `channel`, to link Transactions back to source systems for reconciliation and audit. ## What to do next *** After sending the Transaction, review the details page and confirm the status, source operation, destination operation, and account balances. > [card] [Create a direct Transaction](/en/reference/products/midaz/v2/create-transaction-direct) > > Create a Transaction programmatically with the v2 direct endpoint, which the Console uses. > [card] [Retrieve a Transaction](/en/reference/products/midaz/v2/get-transaction) > > Inspect the Transaction status and operations via API. # Creating an Account Source: https://docs.lerian.studio/en/products/midaz/console/creating-an-account Create a new Account in the Console, tie it to an Asset, set its alias and type, and optionally link it to a Portfolio or add metadata during setup. > [!WARNING] > > You **must** link an Account to an existing Asset. [Create the Asset](/en/products/midaz/console/creating-an-asset) before you create the Account. ## Before you start *** You need an existing Organization, Ledger, and Asset. If the Ledger uses **Validate Account Type**, create the required Account Types before you open this form. Decide what the account represents before you choose its type and alias. Common examples include customer, merchant, treasury, fee revenue, settlement, suspense, and expense accounts. ## Create the Account *** To create an Account, follow these steps: **Step 1** From the **Accounts** page, click the **New Account** button. **Step 2** The **New Account** form will open on the right side of the screen with three tabs: **Account Details**, **Portfolio**, and **Metadata**. **Step 3** Fill in the required information in the **Account Details** tab. For more information about the fields in the form, refer to the [Field guide](#field-guide) section. **Step 4** *(Optional)* Switch to the **Portfolio** tab to link this account to a portfolio for reports and management. * Select a portfolio from the dropdown list * If no portfolios exist, you can [create one first](/en/products/midaz/console/managing-portfolios) * You can link or unlink accounts from portfolios at any time **Step 5** *(Optional)* Switch to the **Metadata** tab to add custom key-value pairs for additional context or integration purposes. **Step 6** Click the **Save** button to create the Account. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Account Name | Required descriptive name for the account, 3 to 255 characters. | `John Doe Checking Account` | | Account Alias | Required unique human-readable identifier of up to 100 characters. Use letters, numbers, hyphens (`-`), underscores (`_`), `@`, and `:`. A leading `@` is a common convention, not a requirement. An alias cannot start with `@external/`. This cannot be changed after creation. | `@customer_john_checking` | | Type | Account classification. Required. When Account Type validation is enabled, you select from the predefined Account Types; otherwise you type it freely. This cannot be changed after creation. | `customer` | | External account | Switch available when creating an account. Turn it on to create an external account. The type is set to `external` automatically and represents balances held outside this ledger. | — | | Entity ID | Optional external holder, customer, department, or partner identifier. | `customer_123` | | Asset | Asset this account will use. Select an existing Asset. This cannot be changed after creation. | `BRL` | | Segment | Optional grouping category, available when Segments exist. | `Retail` | | Portfolio | Optional reporting or management group for this Account. | `Customer Portfolio` | | Metadata Key | Optional classification or integration field name. | `costCenter` | | Metadata Value | Value for the metadata key. | `BR_11101997` | ## Quick examples *** > [tab] Customer Checking Account > > **Scenario**: Create a checking account for a customer. > > | Field | Value | > | - | - | > | Account Name | `John Doe Checking` | > | Account Alias | `@customer_123_checking` | > | Type | `checking` | > | Entity ID | `customer_123` | > | Asset | `USD` | > | Allow Sending | `true` | > | Allow Receiving | `true` | > [tab] Treasury Account > > **Scenario**: Create a main treasury account for company operations. > > | Field | Value | > | - | - | > | Account Name | `Main Treasury` | > | Account Alias | `@treasury_main` | > | Type | `treasury` | > | Entity ID | `org_treasury_dept` | > | Asset | `USD` | > | Segment | `Finance` | > | Allow Sending | `true` | > | Allow Receiving | `true` | > [tab] Department Budget Account > > **Scenario**: Create a budget account for the engineering department. > > | Field | Value | > | - | - | > | Account Name | `Engineering Budget 2024` | > | Account Alias | `@eng_budget_2024` | > | Type | `expense` | > | Entity ID | `dept_engineering` | > | Asset | `USD` | > | Segment | `Engineering` | > | Allow Sending | `true` | > | Allow Receiving | `true` | ## Immutable fields, type validation and permissions *** > [accordion] Fields that cannot be changed after creation > > You cannot change the following fields after you create the account: > > * **Account Alias** - Choose it carefully, because transactions use the alias > * **Type** - You cannot reclassify it after you set it > * **Asset Code** - You cannot change the account's currency or commodity > > To change any of these fields, create a new account. > [accordion] Account Type Validation > > If your ledger uses Account Type validation: > > * You select the **Type** from your predefined Account Types instead of typing it freely > * You must select from predefined account types or create them first > * This ensures consistency across your organization's chart of accounts > > See [Managing Accounts](/en/products/midaz/console/managing-accounts#account-type-validation) for more information. > [accordion] Allow Sending and Allow Receiving > > These flags control transaction permissions: > > * **Allow Sending = false**: You cannot use the account as a source (debit side) in transactions > * **Allow Receiving = false**: You cannot use the account as a destination (credit side) in transactions > > Both flags default to on. You can change them only after you create the account. Use these flags to: > > * Freeze an account temporarily > * Create a receive-only account (for example, escrow) > * Create a send-only account (rare case) > [!NOTE] > > After you create an account, you can use it in transactions immediately. Make sure all the information is correct before you save, especially the immutable fields. ## What to do next *** After you create the source and destination Accounts: 1. Create or review Accounting Routes in [Creating an Accounting Route](/en/products/midaz/console/creating-an-accounting-route). 2. Create a Transaction in [Creating a Transaction](/en/products/midaz/console/creating-a-transaction). > [card] API equivalent > > [Create an Account endpoint](/en/reference/products/midaz/v2/create-account) # Creating an Account Type Source: https://docs.lerian.studio/en/products/midaz/console/creating-an-account-type Create a new Account Type in the Console to classify Accounts and enforce validation used by Accounting Routes when transactions are recorded. Account Types classify Accounts. Accounting Routes use these types to define which accounts an operation can use. Create them before Accounts if you enabled **Validate Account Type** for the Ledger. ## Before you start *** You need an existing Organization and Ledger. If you cannot see the Account Types menu, enable **Validate Account Type** in [Ledger Settings](/en/products/midaz/console/managing-ledgers-via-console#ledger-settings). Define Account Types from the accounting model, not from individual customer names. Examples: `customer`, `merchant`, `treasury`, `fee`, `settlement`, `revenue`, `expense`. ## Create the Account Type *** **Step 1** From the **Account Types** page, click the **New Account Type** button. **Step 2** The **New Account Type** form will open on the right side of the screen. **Step 3** Fill in the information and click the **Save** button. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Account Type Name | Clear operator-facing name for this Account Type. | `Customer` | | Description | Optional explanation of when operators should use this type. | `Accounts that represent end customers and can send or receive BRL payments.` | | Key Value | Stable value used to classify Accounts and route rules. Use a short lowercase value that will remain stable. | `customer` | > [!TIP] > > Accounts and Accounting Routes reference the **Key Value**. Keep it short, lowercase, and aligned with your accounting model. You cannot change it after you create the Account Type. To use a different value, create a replacement Account Type, recreate dependent Accounts with the new type, and update dependent routes. ## What to do next *** After creating Account Types, create Accounts and select the correct type in [Creating an Account](/en/products/midaz/console/creating-an-account). > [card] API equivalent > > [Create an Account Type endpoint](/en/reference/products/midaz/v2/create-account-type) # Creating an Accounting Route Source: https://docs.lerian.studio/en/products/midaz/console/creating-an-accounting-route Create a new Accounting Route in the Console using the 3-step wizard to define transaction routes, operation routes, and accounting scenarios. You create an Accounting Route through a guided 3-step wizard. The wizard walks you through the transaction route, the operation routes with their accounting scenarios, and a final review. ## Before you start *** Create the Account Types and Accounts that the route validates. If you have not chosen the operation type, the validation type, and the accounting scenarios yet, read [Accounting rules](/en/products/midaz/console/mc-accounting) first. > [!WARNING] > > If you enable **Validate Routes** for the Ledger, every transaction must match an existing route. Do not enable route validation until the required Accounting Routes are ready. The sidebar shows **Accounting Routes** only when **Validate Routes** is on for the Ledger. When it is off, open the page from the Console page search (**Search pages...**). ## Step 1: Basic information *** **Step 1** From the **Accounting Routes** page, click **New Route**. **Step 2** The creation wizard opens on the **Transaction Route** step. **Step 3** Fill in the basic information: * **Route Title** (required): a descriptive name for this transaction route. You must fill in this field to continue. * **Description** (optional): a description of the route's purpose. If you leave it empty, the wizard submits and stores an empty description. **Step 4** Click **Next** to proceed to Step 2. ## Step 2: Operation Routes *** In this step, you add and configure the operation routes. Operation routes define how the ledger validates accounts and records accounting entries. > [!NOTE] > > A **Bidirectional** operation route is both source and destination. When you later create a transaction, the ledger matches a bidirectional route on both the source side and the destination side. A single route can then validate both ends of the flow. **Step 1** Click **Add Operation Route** to create your first operation route card. **Step 2** Configure the operation route: * **Title** (required): a name for this operation route. The operation route has a single required text field and no separate description field. You cannot advance to the next step until you fill it in. * **Type**: **Source**, **Destination**, or **Bidirectional**. * **Validation Type**: **Account Type** or **@Alias**. The wizard requires at least one Account Type or an alias for each operation route. * **Account Type or Alias**: the selected Account Type values or the specific account alias. * **Optional route**: off by default. Turn it on when a transaction may leave this operation route unused. When a transaction uses the route, the Ledger validates it like the others. **Step 3** Configure **Accounting Scenarios** to define how the ledger records entries. **Direct Transaction** is always on, and you must fill in its entries. Toggle on the other scenarios you need: > [tab] Direct Transaction > > Standard one-step transaction. Define the **Account Code** and **Description** for: > > * **Debit**: The account code debited on execution > > * **Credit**: The account code credited on execution > > > [!TIP] > > > > For Direct Transactions, which sides appear depends on the operation type. Source routes show debit only, destination routes show credit only, and bidirectional routes show both. > [tab] Two-Step Transaction > > Transactions with a hold-then-commit cycle. Configure entries for each phase: > > * **Hold (Value Reserve)**: Entries that record reserved funds > * **Commit (Reservation Confirmation)**: Entries that confirm the reservation > * **Cancel (Reservation Cancellation)**: Entries that cancel the reservation. Fill these fields too: the ledger validates Hold, Commit, and Cancel as an atomic group and rejects the route when the Cancel mapping is absent. > > The available entry fields vary by operation type: > > * **Source**: Hold and Cancel show both debit and credit fields. Commit shows debit only. > * **Destination**: Only the Commit phase appears, with credit only. Hold and Cancel are not available. > * **Bidirectional**: All phases show both debit and credit fields. > [tab] Reversal > > Entries that record the reversal of a completed transaction. Define the debit and credit account codes and descriptions for the reversal entries. > > > [!NOTE] > > > > The Reversal scenario is only available for **Bidirectional** operation routes. > [tab] Overdraft > > Entries that apply when a debit exceeds the account's available funds and draws on an overdraft line. Define the debit and credit account codes and descriptions for the overdraft draw and later repayment. > > > [!NOTE] > > > > Overdraft is available for **Source** and **Bidirectional** operation routes. > [tab] Block > > Entries that record blocking and unblocking funds on an account. Configure two independent sections, **Block** and **Unblock**. Each section is all-or-nothing: leave it empty to use the default entries, or fill in both the account code and the description for every visible side. > > > [!NOTE] > > > > Block is available for all operation types. Source routes show debit entries only, destination routes show credit entries only, and bidirectional routes show both. **Step 4** *(Optional)* Click **Add Operation Route** again to add more operation routes to this Accounting Route. > [!WARNING] > > Add at least one required source and one required destination operation route, or one required bidirectional route. Optional routes do not count. The wizard will not proceed without a valid route configuration. **Step 5** Click **Next** to proceed to Step 3. ## Step 3: Review *** **Step 1** Review the complete configuration: * Transaction route title and description * Each operation route with its type, validation rules, and accounting entries. An **Optional** badge marks each optional route * Accounting scenarios with debit and credit entries per transaction type **Step 2** To adjust anything, click **Previous** to go back. **Step 3** Click **Create Transaction Route** to create the Accounting Route. The Ledger can refuse the save and name an operation route. Then the wizard returns to Step 2 and shows the refusal on that card. ## Field guide *** ### Basic information | Field | What to enter | Example | | - | - | - | | Route Title | Required route name. Keep it short and specific to the business flow. | `Pix Transfer Route` | | Description | Optional explanation of what the route validates or records. | `Handles Pix transfers between customer accounts.` | ### Operation route | Field | What to enter | Example | | - | - | - | | Title | Required name for this operation route card. Must be filled before advancing; there is no separate description field. | `Checking account validation for Pix` | | Type | Accounting side this operation route applies to: **Source**, **Destination**, or **Bidirectional**. This cannot be changed after creation. | **Bidirectional** | | Validation Type | Required account-validation rule. Use **Account Type** for account classes or **@Alias** for a specific account. | **Account Type** | | Account Type or Alias | Account Types or aliases accepted by this operation route. | `customer` | | Optional route | Switch, off by default. Turn it on when a transaction may leave this operation route unused. | Off | | Accounting Scenarios | Transaction scenarios this route should record: Direct, Two-Step, Reversal, Overdraft, or Block. | `Direct Transaction` | | Account Code | Accounting code used in the debit or credit entry for the selected scenario. | `1.1.1.001` | | Entry Description | Entry-level description shown in the scenario configuration. | `Customer checking - outbound` | ## Quick example *** > [accordion] Pix Transfer with a Direct scenario > > **Transaction Route** > > | Field | Value | > | - | - | > | Title | `Pix Transfer Route` | > | Description | `Handles Pix instant transfers between checking accounts` | > > **Operation Route 1: Bidirectional** > > | Field | Value | > | - | - | > | Title | `Checking account validation for Pix` | > | Type | **Bidirectional** | > | Validation Type | **Account Type** | > | Account Types | `checking` | > > **Direct Transaction scenario** > > | Side | Account Code | Description | > | - | - | - | > | Debit | `1.1.1.001` | `Customer checking — outbound` | > | Credit | `1.1.1.002` | `Customer checking — inbound` | ## What to do next *** After you create the route, create a transaction that matches the same account types, aliases, and scenario in [Creating a Transaction](/en/products/midaz/console/creating-a-transaction). > [card] [Create Transaction Route](/en/reference/products/midaz/v2/create-transaction-route) > > Create the transaction-level route via API. > [card] [Create Operation Route](/en/reference/products/midaz/v2/create-operation-route) > > Create operation-level routing rules via API. # Creating an Asset Source: https://docs.lerian.studio/en/products/midaz/console/creating-an-asset Create a new Asset in the Console (currency, crypto, commodity, or custom) and set the code that Accounts and Transactions use. An Asset defines the unit of value that Accounts and Transactions use inside a Ledger. Create Assets before you create Accounts, because every Account uses one Asset. ## Before you start *** You need an existing Organization and Ledger. Decide whether the Asset is a currency, crypto asset, commodity, or another custom unit of value. > [!WARNING] > > Choose Asset codes carefully. Accounts and Transactions depend on them. ## Create the Asset *** **Step 1** From the **Assets** page, click the **New Asset** button. **Step 2** The **New Asset** form opens on the right side of the screen. **Step 3** Select the **Type** of Asset. * *Crypto*: for cryptocurrencies such as Bitcoin, Ethereum, and Ripple. * *Commodity*: for tradable raw materials such as gold, natural gas, soybeans, and corn. * *Currency*: for currencies such as Brazilian Real, US Dollar, and Euro. * *Others*: for any other type of Asset. > [!CAUTION] > > You cannot reuse an Asset name or code in the same Ledger. Both the name and the code must be unique. **Step 4** Specify the **Asset Name**. **Step 5** Specify the **Code** for the Asset. Use uppercase letters only. * If the Asset is a currency, select its code from the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217#List_of_ISO_4217_currency_codes) list. **Step 6** \[Optional] Select the **Metadata** tab to add custom metadata. **Step 7** After you fill in the fields, click the **Save** button. **Step 8** The Asset appears in the list of available Assets for your Ledger. > [!NOTE] > > Saving an Asset also provisions a system-managed External Account when one does not already exist for that Asset code. Its canonical alias is `@external/`. > [!TIP] > > The fields in the Metadata tab are open. There are no predefined keys or values. Use consistent key names across your Organization, such as `country`, `settlementNetwork`, or `regulatoryClass`, so you can filter and audit Assets later. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Type | Asset category. Use `Currency` for fiat money, `Crypto` for crypto assets, `Commodity` for tradable commodities, or `Others` for custom units. | `Currency` | | Asset Name | Human-readable Asset name shown to operators. | `Brazilian Real` | | Code | Asset code in uppercase letters. For currencies, use the ISO 4217 code. | `BRL` | | Metadata Key | Optional classification or integration field name. | `settlementNetwork` | | Metadata Value | Value for the metadata key. | `pix` | ## What to do next *** After creating the Asset, create Accounts that use it in [Creating an Account](/en/products/midaz/console/creating-an-account). > [card] API equivalent > > [Create an Asset endpoint](/en/reference/products/midaz/v2/create-asset) # Creating an Organization Source: https://docs.lerian.studio/en/products/midaz/console/creating-an-organization Create a new Organization in the Midaz Module to set the business boundary that will own your Ledgers, Assets, Accounts, and Transactions. An Organization is a container for Midaz operations. It can be a top-level Organization or a child of another Organization. Create it before you create Ledgers, Assets, Accounts, or Transactions. ## Before you start *** Decide which business boundary this Organization represents. In most setups, it maps to the company, business unit, or regulated entity that owns one or more Ledgers. > [!NOTE] > > If you set up Midaz for the first time, follow the [Setup path](/en/products/midaz/console/midaz-console-setup-path) before you create downstream entities. ## Create the Organization *** **Step 1** Go to the **Organizations** page. Click the **New Organization** button. **Step 2** The **New Organization** page opens. **Step 3** Fill in the required details about the Organization. * **Optional**: To include metadata, expand the **Metadata** section. The section then shows the **Key** and **Value** fields. * To add more metadata entries, click the plus (+) sign next to the first row. > [!TIP] > > See the [Field guide](#field-guide) section for details about each field. **Step 4** After you enter all the details, click **Save**. **Step 5** Your new Organization appears on the Organizations page. You can now manage and configure it. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Legal Name | Official registered name. Use a name operators will recognize later. | `Lerian Payments Brazil` | | Trade Name | Commercial or customer-facing name. | `Lerian` | | Document | Official tax ID or registration number. Enter the identification document number. | `12345678000190` | | Address | Street name, number, and main address line. | `Avenida Paulista, 1234` | | Complement | Extra address details, such as suite, floor, or apartment. | `CJ 123` | | Country | Select the country where the Organization is registered. | `Brazil` | | State | Select the state, province, or region of the selected country. | `São Paulo` | | City | City where the Organization is registered. | `São Paulo` | | ZIP Code | Postal code, digits only, up to 12 digits. | `04696040` | | Parent Organization | Optional. Select the Organization that this Organization is affiliated with, to create it as a child. | `Acme Holding` | ### Metadata Metadata is optional key-value data. Use it for internal classification, integration references, or reporting. | Field | What to enter | Example | | - | - | - | | Key | The metadata field name. | `costCenter` | | Value | The value for that metadata field. | `BR_11101997` | ## What to do next *** After you create the Organization, create its first Ledger in [Creating a new Ledger](/en/products/midaz/console/creating-a-new-ledger). > [card] API equivalent > > [Create an Organization endpoint](/en/reference/products/midaz/v2/create-organization) # Creating an Alias from the Holder Source: https://docs.lerian.studio/en/products/midaz/console/crm-alias-from-holder Create an Alias Account directly from the Holders page in the Console so the Holder ID is preset and the new Alias is linked to its owner in one step. You can also create an Alias Account from the **Holders** page. To do so, follow these steps: **Step 1** On the **Holders** page, find the Holder that you want to link to the Alias Account. **Step 2** In the Actions column, click the three dots () and select **Create Alias Account**. **Step 3** The Console opens the Alias Accounts page and shows the New Alias Account form. **Step 4** Fill in the fields as required, then click **Create Alias Account**. > [!NOTE] > > The Console pre-fills the **Holder ID** field. You cannot change it. With Access Manager, the **Create Alias Account** action needs the create permission on instruments. # Creating a Holder Source: https://docs.lerian.studio/en/products/midaz/console/crm-creating-a-holder Create a new Holder in the Midaz Module as an Individual or Corporate record to represent the person or company that owns one or more Accounts. A Holder represents the person or company behind one or more Accounts. Create the Holder before you create Alias Accounts. An Alias Account connects customer-facing account information to a ledger Account. ## Before you start *** Decide whether the Holder is an **Individual** or **Corporate** record. The type you choose controls which identity and registration fields the form shows. ## Create the Holder *** **Step 1** Go to the **Holders** page. Click the **New Holder** button. **Step 2** A window opens. Choose the Holder type you want to create. * If you select **Individual** (Natural Person), the **New Holder** page opens for you to enter the individual's information. * If you select **Corporate** (Legal Person), the **New Holder** page opens for you to enter the company's information. **Step 3** Follow the on-screen instructions to enter the required information. Click **Create Holder**. **Step 4** When the creation succeeds, you see a confirmation message. The list refreshes and shows the new Holder. ## Field guide *** ### Individual **Basic Information** | Field | What to enter | Example | | - | - | - | | External ID | Optional ID from your CRM, core banking, KYC, or customer system. | `customer_123` | | Type | A read-only field that indicates the type of Holder. | `Natural Person` | | Name | The full name of the Holder. | `John Doe` | | Document | Tax ID, national ID, or company registration number expected by your operation. | `12345678900` | **Contact Information** | Field | What to enter | Example | | - | - | - | | Primary Email | The main email used to contact the Holder. | `john.doe@example.com` | | Secondary Email | An alternative email used to contact the Holder. | `john.doe2@example.com` | | Mobile Phone | Contact phone number, including country or area code when required. | `+5511999999999` | | Other Phone | An alternative phone number, including country or area code when required. | `+551188888888` | **Addresses** | Field | What to enter | Example | | - | - | - | | Address Line 1 | Street name and building number. | `Rua Botucatu 10` | | Address Line 2 | Extra address details, for example, apartment or suite number. | `Casa B` | | Zip Code | Postal or ZIP code. | `04023060` | | City | City where the address is located. | `São Paulo` | | State | State, province, or region. | `SP` | | Country | Two-letter country code (ISO 3166-1 alpha-2). | `BR` | **Personal Details** | Field | What to enter | Example | | - | - | - | | Favorite Name | Nickname or preferred name. | `Johnny` | | Social Name | Social name, if different from the legal name. | `Johnny Doe` | | Gender | Gender identity of the person. | `Male` | | Birth Date | Date of birth in YYYY-MM-DD format. | `1990-01-01` | | Civil Status | Civil status, for example: Single, Married, or Divorced. | `Married` | | Nationality | Nationality, for example, Brazilian. | `Brazilian` | | Mother's Name | Mother's full name. | `Jane Doe` | | Father's Name | Father's full name. | `Richard Doe` | | Status | Current status of the individual in the system. | `Active` | **Metadata** | Field | What to enter | Example | | - | - | - | | Key | Optional classification or integration field name. | `kycStatus` | | Value | Value for the metadata key. | `approved` | ### Corporate **Basic Information** | Field | What to enter | Example | | - | - | - | | External ID | Optional ID from your CRM, core banking, KYC, or customer system. | `company_123` | | Type | A read-only field that indicates the type of Holder. | `Legal Person` | | Name | The name of the company in the system. | `ACME` | | Document | Tax ID, national ID, or company registration number expected by your operation. | `59014899000183` | **Contact Information** | Field | What to enter | Example | | - | - | - | | Primary Email | The main email used to contact the company. | `acme@example.com` | | Secondary Email | An alternative email used to contact the Holder. | `acme2@example.com` | | Mobile Phone | Contact phone number, including country or area code when required. | `+5511999999999` | | Other Phone | An alternative phone number, including country or area code when required. | `+551188888888` | **Addresses** | Field | What to enter | Example | | - | - | - | | Address Line 1 | Street name and building number. | `Rua Silva 100` | | Address Line 2 | Extra address details, for example, apartment or suite number. | `Cj 12` | | Zip Code | Postal or ZIP code. | `04013060` | | City | City where the address is located. | `São Paulo` | | State | State, province, or region. | `SP` | | Country | Two-letter country code (ISO 3166-1 alpha-2). | `BR` | **Company Details** | Field | What to enter | Example | | - | - | - | | Trade Name | The registered business name of the company, if applicable. | `ACME BR` | | Activity | The type of business or activity the company engages in. | `Electronic devices development` | | Legal Type | The legal structure of the company. | `Limited Liability` | | Founding Date | The date when the company was established, in YYYY-MM-DD format. | `2025-01-01` | | Company Size | The size classification of the company. | `Medium` | | Status | Current status of the company in the system. | `Active` | | Representative Name | The legal representative's name. | `Jane Doe` | | Representative Document | The document number of the legal representative. | `43522116992` | | Representative Email | The email address of the legal representative. | `janedoe@corporate.com` | | Role | The role of the legal representative within the company. | `CFO` | **Metadata** | Field | What to enter | Example | | - | - | - | | Key | Optional classification or integration field name. | `kycStatus` | | Value | Value for the metadata key. | `approved` | ## What to do next *** After you create the Holder, create an Alias Account to connect the Holder to a Midaz ledger Account. See [Creating an Alias Account](/en/products/midaz/console/crm-creating-alias-account). > [card] API equivalent > > [Create Holder endpoint](/en/reference/products/midaz/v2/create-holder) # Creating an Alias Account Source: https://docs.lerian.studio/en/products/midaz/console/crm-creating-alias-account Create a new Alias Account in the Midaz Module to link a Holder to a Midaz Account with banking, regulatory, and customer-facing account details. An Alias Account links a Holder to an underlying Midaz Account and stores customer-facing account identifiers separately from ledger balances. ## Before you start *** You need an existing Holder and an existing Midaz Account. Keep the Account ID available because this page connects Holder information to the ledger Account. ## Create the Alias Account *** **Step 1** Go to the **Alias Accounts** page and click the **New Alias Account** button. **Step 2** A window will open where you can specify the information about the account. **Step 3** Fill in all the necessary information and click **Create Alias Account**. **Step 4** If the creation is successful, you will receive a confirmation message, and the list will refresh to show the new Alias Account. ## Field guide *** **Alias Account Details** | Field | What to enter | Example | | - | - | - | | Holder ID | The unique identifier of the Holder that owns or controls this Alias Account. | `019ed1d9-7694-7bba-a721-d8e53911ab08` | | Account ID | The unique identifier of the Account for which you want to create the Alias Account. | `019ed1eb-21f8-781c-a30f-f5fca470497d` | | Ledger | The name of the Ledger of which the account is part. | `Test Ledger` | **Banking Details** | Field | What to enter | Example | | - | - | - | | IBAN | International Bank Account Number (IBAN) tied to the account. | `US12345678901234567890` | | Bank ID | Bank identifier used to link the account to its institution. | `12345` | | Branch | Branch number or code where the account is held. | `0001` | | Account | Customer-facing account number or external account identifier. | `1234567` | | Type | ISO 20022 account type code (for example, CACC for a current account or SVGS for savings). | `CACC` | | Opening Date | Date when the account was opened. | `2010-01-01` | | Country Code | ISO 3166-1 alpha-2 country code where the bank is based. | `US` | **Regulatory** The related party fields below (Document, Name, Role, Start Date, and End Date) belong to a repeatable **Related Parties** group. Click **Add related party** to add each related party entry. | Field | What to enter | Example | | - | - | - | | Participant Document | The document number of the participant institution (e.g., CNPJ for Brazilian financial institutions). Optional field. | `---` | | Document | Identification document of the related party (e.g., CPF or CNPJ). | `98765432100` | | Name | Full legal name of the related party. | `Jane Doe` | | Role | The type of relationship between the related party and the Alias Account. The select shows **Primary Holder**, **Legal Representative**, and **Responsible Party**. | `Legal Representative` | | Start Date | Start date of the relationship with the Alias Account. | `2024-01-01` | | End Date | End date of the relationship with the Alias Account. If not provided, the relationship is considered ongoing. | `2025-01-01` | ## What to do next *** After creating the Alias Account, use it to identify the customer account in operational flows, or return to [Managing Alias Accounts](/en/products/midaz/console/managing-crm-alias-accounts) to review the record. > [card] API equivalent > > [Create Alias Account endpoint](/en/reference/products/midaz/v2/create-instrument) # Deleting a Holder Source: https://docs.lerian.studio/en/products/midaz/console/crm-deleting-a-holder Delete a Holder from the Midaz Module only after the Holder has no linked Alias Accounts or Accounts, within your deployment's data-retention and compliance policies. > [!CAUTION] > > Confirm your data-retention, compliance, and regulatory policies before you delete a Holder. In regulated environments, you may need to retain Holder records to meet legal, regulatory, audit, reporting, or compliance obligations. To delete a Holder, follow these steps: **Step 1** On the **Holders** page, find the Holder you want to delete. **Step 2** In the **Actions** column, click the three dots (). Select **Delete**. **Step 3** A confirmation dialog appears. **Step 4** Click **Confirm** to delete the Holder. ## Data deletion options *** > [!WARNING] > > **Regulated deployments** > > In environments under financial regulation (for example, BACEN, LGPD, or GDPR), mandatory retention periods can apply to Holder records tied to financial transactions. Before you hard delete in production, ask your Legal and Compliance team to review the action. When you delete a Holder in the Console, the Midaz Module performs a **soft delete**. It marks the Holder as deleted and keeps the record in the database. The record stays available for audit. A **hard delete** (permanently removing the record from the database) is available only through the API. Use the `?hard_delete=true` query parameter on the delete Holder endpoint. This action is irreversible, so use it only when your retention policy allows it. > [!NOTE] > > Deletion fails while the Holder still has linked Alias Accounts or Accounts. Delete them before you delete the Holder. For more information about data security and deletion, see [CRM Data Security](/en/products/midaz/crm/crm-data-security). # Deleting an Alias Account Source: https://docs.lerian.studio/en/products/midaz/console/crm-deleting-alias-account Delete an Alias Account from the Midaz Module. Your deployment's data-retention and compliance policies can keep the underlying record. > [!CAUTION] > > When you delete an Alias Account, the Midaz Module removes it from the active list. Your deployment's data-retention and compliance policies still apply. In a regulated environment, the underlying record can stay for audit, regulatory, or reporting purposes. Confirm your retention policy before you delete. To delete an Alias Account, follow these steps: **Step 1** From the **Alias Accounts** page, find the alias account to delete. **Step 2** In the Actions column, click the three dots (). **Step 3** Select **Delete**. **Step 4** A confirmation dialog opens. **Step 5** Click **Confirm** to delete the alias account. # Editing a Holder Source: https://docs.lerian.studio/en/products/midaz/console/crm-editing-a-holder Edit an existing Holder in the Midaz Module to update personal, corporate, contact, or address information and keep customer records accurate. To edit the information of a Holder, follow these steps: **Step 1** From the **Holders** page, find the Holder that you want to edit. **Step 2** Click the three dots () from the Actions column, and select **Edit**. **Step 3** The Holders form will open. **Step 4** Edit the information as needed and click **Update Holder**. > [!NOTE] > > The **Document** field stays read-only when you edit a Holder. You cannot change it after you create the Holder. # Editing an Alias Account Source: https://docs.lerian.studio/en/products/midaz/console/crm-editing-alias-account Edit an existing Alias Account in the Midaz Module to update banking details or regulatory data. To edit the information of an Alias Account, follow these steps: **Step 1** From the **Alias Accounts** page, find the alias account that you want to edit. **Step 2** Click the three dots () from the Actions column, and select **Edit**. **Step 3** The Alias Account form will open. **Step 4** Edit the information as needed and click **Update Alias Account**. # Deleting a Ledger Source: https://docs.lerian.studio/en/products/midaz/console/deleting-a-ledger Delete a Ledger from your Organization in the Console when it is no longer used. Data retention and compliance policies may keep audit records available. To delete a Ledger, follow these steps: > [!CAUTION] > > Check your data retention and compliance policy before you delete a Ledger. The Console removes the Ledger from active listings, but keeps the underlying record. Your retention policy controls how long the record stays available for audit, regulatory, or reporting purposes. **Step 1** On the **Ledgers** page, find the Ledger you want to delete. **Step 2** Click the three-dot menu () in the **Actions** column. Select **Delete**. **Step 3** A confirmation dialog will appear. **Step 4** Click **Confirm** to delete the Ledger. > [!WARNING] > > Midaz rejects Ledger deletion when `ENV_NAME=production`. > [!NOTE] > > After you delete a Ledger, you can no longer use it. Its data may stay available for audit, regulatory, or reporting purposes, based on your retention policy. > [card] API equivalent > > [Delete a Ledger endpoint](/en/reference/products/midaz/v2/delete-ledger) # Deleting a Portfolio Source: https://docs.lerian.studio/en/products/midaz/console/deleting-a-portfolio Delete a Portfolio from the Console when its Accounts no longer need to be grouped together, subject to your deployment's data retention rules. > [!CAUTION] > > Check your data retention policy before you delete a Portfolio. The Console removes it from active listings. Your deployment can keep the underlying record for audit, regulatory, or reporting purposes. To delete a Portfolio, follow these steps: **Step 1** On the **Portfolios** page, find the Portfolio to delete. **Step 2** In the **Actions** column, click the three-dot menu () and select **Delete**. **Step 3** A confirmation dialog opens. **Step 4** Click **Confirm** to delete the Portfolio. > [card] API equivalent > > [Delete a Portfolio endpoint](/en/reference/products/midaz/v2/delete-portfolio) # Deleting a Segment Source: https://docs.lerian.studio/en/products/midaz/console/deleting-a-segment Delete a Segment from the Console when it no longer classifies any Accounts, subject to your deployment's data retention and compliance policies. > [!CAUTION] > > When you delete a Segment, the Console removes it from active listings. Deletion follows your deployment's data retention and compliance policies. In regulated environments, the underlying record remains for audit, regulatory, or reporting purposes. Confirm your retention policy first. To delete a Segment, follow these steps: **Step 1** On the **Segments** page, find the Segment to delete. In the **Actions** column, click the three dots (). Select **Delete**. **Step 2** A confirmation dialog opens. **Step 3** Click **Confirm** to delete the Segment. **Step 4** After you confirm, the Console removes the Segment from active listings. > [card] API equivalent > > [Delete a Segment endpoint](/en/reference/products/midaz/v2/delete-segment) # Deleting an Account Source: https://docs.lerian.studio/en/products/midaz/console/deleting-an-account Delete an Account from your Ledger in the Console when it is no longer used. External Accounts cannot be removed and retention policies still apply. > [!CAUTION] > > When you delete an Account, Midaz removes it from active listings. Midaz also archives the Account's Alias Accounts, ends its account plan assignment, and removes its alias from the Ledger's fee and billing packages. A fee package left without fees is disabled, and so is a billing package that debits or credits that alias or has no target alias left. See [Fees Engine overview](/en/products/midaz/fees/fees-engine-overview). Your deployment's data retention and compliance policies apply. In regulated environments, your deployment can keep the record for audit, regulatory, or reporting purposes. Review your retention policy before you delete an Account. To delete an Account, follow these steps: **Step 1** On the **Accounts** page, find the Account to delete. In the **Actions** column, click the three dots (), then select **Delete**. **Step 2** A confirmation dialog appears. **Step 3** Click **Confirm** to delete the Account. **Step 4** Midaz removes the Account from active listings. > [!NOTE] > > Before deleting an Account, make sure every balance has `available`, `onHold`, and `overdraftUsed` equal to zero, and that no balance owes [fee debt](/en/products/midaz/fees/fee-debt) and no other balance owes fee debt to it. Otherwise, Midaz rejects the deletion. > [!WARNING] > > You cannot directly delete or modify External Accounts. Midaz creates them automatically with each Asset. Deleting an Asset soft-deletes active External Accounts with the same Asset code in the same Organization and Ledger. > [card] API equivalent > > [Delete an Account endpoint](/en/reference/products/midaz/v2/delete-account) # Deleting an Asset Source: https://docs.lerian.studio/en/products/midaz/console/deleting-an-asset Delete an Asset from your Ledger in the Console when it is no longer used. Your deployment's data retention and compliance policies still apply. > [!CAUTION] > > When you delete an Asset, Midaz removes it from active listings. Your deployment's data retention and compliance policies apply. In regulated environments, your deployment can keep the record for audit, regulatory, or reporting purposes. Review your retention policy before you delete an Asset. To delete an Asset, follow these steps: **Step 1** On the **Assets** page, find the Asset to delete. In the **Actions** column, click the three dots (), then select **Delete**. **Step 2** A confirmation dialog appears. **Step 3** Click **Confirm** to delete the Asset. **Step 4** Midaz removes the Asset from active listings. Your deployment's data retention and compliance policies still apply. > [!NOTE] > > Deleting an Asset soft-deletes all active External Accounts with the same Asset code in that Organization and Ledger. > [card] API equivalent > > [Delete an Asset endpoint](/en/reference/products/midaz/v2/delete-asset) # Deleting an Organization Source: https://docs.lerian.studio/en/products/midaz/console/deleting-an-organization Remove an Organization from the Midaz Module, subject to your deployment's data retention and compliance policies. To delete an Organization in **Midaz Module**, follow these steps: > [!CAUTION] > > When you delete an Organization, you cannot use it anymore. It no longer appears in active listings. Your deployment's data retention and compliance policies govern the record after that. In regulated environments, the record remains for audit, regulatory, or reporting purposes. Confirm your retention policy before you delete. **Step 1** On the **Organizations** page, find the Organization you want to delete. **Step 2** In the **Actions** column, click the three-dot menu ( ). Then select **Delete**. **Step 3** A confirmation dialog will appear. **Step 4** Click **Confirm** to delete the Organization. > [!WARNING] > > Midaz rejects Organization deletion when `ENV_NAME=production`. > [card] API equivalent > > [Delete an Organization endpoint](/en/reference/products/midaz/v2/delete-organization) # Editing a Ledger Source: https://docs.lerian.studio/en/products/midaz/console/editing-a-ledger Edit a Ledger from the Console to update its name, metadata, or the Validate Account Type and Validate Routes settings without any redeployment. To view or edit the details of a Ledger, follow these steps: **Step 1** On the **Ledgers** page, locate the Ledger you want to view or update. Click the three dots () in the **Actions** column and select **Edit**. **Step 2** The edit panel opens with three tabs: **Ledger Details**, **Metadata**, and **Settings**. Use the **Ledger Details** tab to edit the Ledger name, and the **Metadata** tab to manage custom key-value pairs. Click **Save** to apply the name and metadata changes. **Step 3** To configure validation rules for this Ledger, click the **Settings** tab. From there you can enable **Validate Account Type** and **Validate Routes** for this Ledger, and set its Tracer **Mode**, **Fail Posture**, **Timeout (ms)**, and **Allow Tracer skip** switch. Each switch saves when you change it, and the Console shows **Ledger settings updated successfully**. The **Settings** tab has no **Save** button. > [card] [Ledger Settings](/en/products/midaz/console/managing-ledgers-via-console#ledger-settings) > > Learn how to enable Validate Account Type and Validate Routes for this Ledger. > [card] API equivalent > > [Update a Ledger endpoint](/en/reference/products/midaz/v2/update-ledger) > > [Update Ledger Settings endpoint](/en/reference/products/midaz/v2/update-ledger-settings) # Editing Account information Source: https://docs.lerian.studio/en/products/midaz/console/editing-account-information Edit an existing Account in the Console to update its name, metadata, or other details. External Accounts created with an Asset cannot be changed. To edit an Account, follow these steps: **Step 1** On the **Accounts** page, find the Account that you want to edit. In the **Actions** column, click the three dots () and select **Edit**. **Step 2** The edit sheet opens with three tabs: **Account Details**, **Portfolio**, and **Metadata**. **Step 3** Edit the information as needed and click **Save**. > [!WARNING] > > You cannot edit External Accounts. Midaz creates one automatically for each Asset. > [card] API equivalent > > [Update an Account endpoint](/en/reference/products/midaz/v2/update-account) # Editing an Account Type Source: https://docs.lerian.studio/en/products/midaz/console/editing-account-type Edit the name, description, and metadata of an existing Account Type from the Console. To edit the information of an Account Type, follow these steps: **Step 1** From the **Account Types** page, find the Account Type that you want to edit, click the three dots ( ) from the **Actions** column, and select **Details**. **Step 2** The **Edit** form will open on the right side of the screen. **Step 3** Edit the information as needed and click **Save**. > [!NOTE] > > You cannot change the **Key Value** when editing an Account Type. Only the name, description, and metadata are editable. > [card] API equivalent > > [Update an Account Type endpoint](/en/reference/products/midaz/v2/update-account-type) # Editing an Accounting Route Source: https://docs.lerian.studio/en/products/midaz/console/editing-an-accounting-route Edit an existing Accounting Route in the Console to update its operation routes, validation rules, and accounting scenarios. You can edit an existing Accounting Route. The Console edit flow changes its operation routes. **Step 1** Go to the **Accounting Routes** page. Find the Accounting Route to edit. Click the three dots () on the route's card. Select **Details**. **Step 2** A detail sheet opens on the right side of the screen. It shows the route configuration: all operation routes, their types, validation rules, and accounting entries. **Step 3** Click **Edit** at the bottom of the detail sheet. **Step 4** The edit form opens with the existing configuration already filled in. It uses the same multi-step layout as the creation wizard. **Step 5** Change the information as needed: * Edit existing operation routes (title, optional setting, validation type, account types or alias, accounting scenarios) * Add new operation routes * Remove an operation route with the delete button on its card > [!NOTE] > > You cannot change the transaction route **Title** or **Description** in the Console edit flow. The edit wizard skips the basic-info step and submits operation-route changes only. You set the title and description at creation. To change them later, use the [Update Transaction Route](/en/reference/products/midaz/v2/update-transaction-route) API. > [!WARNING] > > You cannot change the **Operation Type** (Source, Destination, or Bidirectional) of an existing operation route. To change the direction, delete the operation route and create a new one. **Step 6** Click **Update Transaction Route** to apply your changes. If Midaz refuses the update and names an operation route, the Console opens that card and shows the refusal on it. ## Viewing route details *** To view an Accounting Route without editing it: **Step 1** Go to the **Accounting Routes** page. Click the three dots () on the route's card. Select **Details**. **Step 2** A detail sheet opens on the right side of the screen. It shows the route configuration: all operation routes, their types, validation rules, and accounting entries. If an operation route has a **Code**, set on the Operation Routes page or through the API, the detail sheet also shows it. An **Optional** badge marks each optional operation route. > [!TIP] > > You can also expand a route's card in the Accounting Routes list. The card shows a summary of its operation routes in the card-accordion view. ## Removing individual operation routes *** You can remove a single operation route from an Accounting Route without affecting the rest of the configuration: **Step 1** Open the Accounting Route in **Edit** mode (via **Details** → **Edit**). **Step 2** Find the operation route card to remove. Click the delete button. **Step 3** Click **Confirm** in the dialog. The Console removes the card from the form. **Step 4** Click **Update Transaction Route**. The removal applies only at this step. After the update, the Console tries to delete each removed operation route. When the ledger keeps one, the Console shows a warning with the reason. For example, another Accounting Route still uses it. > [!WARNING] > > When editing, the resulting Accounting Route must contain 2–100 Operation Routes. It must include a required Source and a required Destination route, or at least one required Bidirectional route. Midaz rejects a change that breaks this rule. > [card] [Update Transaction Route](/en/reference/products/midaz/v2/update-transaction-route) > > Update the transaction-level route via API. > [card] [Update Operation Route](/en/reference/products/midaz/v2/update-operation-route) > > Update operation-level routing rules via API. # Editing an Organization Source: https://docs.lerian.studio/en/products/midaz/console/editing-an-organization Edit an Organization in the Midaz Module through the icon shortcut or the Organizations page to update legal name, address, metadata, or avatar. There are two ways of editing the details of an Organization in **Midaz Module**. ## Editing via icon *** To edit the Organization via the icon, follow these steps: **Step 1** Select the Organization switcher at the top of the left sidebar. **Step 2** Select **Edit** from the displayed window. **Step 3** You can update the following supported Organization fields: * **Legal and Trade names** * **Address information** * **Parent Organization** * **Metadata** * **Avatar**: an image of 2 MB or less * **Accent color** **Step 4** After making your changes, click **Save** to persist the supported changes. ## Editing via the Organization page *** **Step 1** Go to the **Organizations** page and locate the Organization you want to update. **Step 2** Click the three-dot menu ( ) in the **Actions** column, then select **Edit**. **Step 3** The Organization edit page opens, where you can edit the supported Organization fields. **Step 4** After making your changes, click **Save** to apply them. > [card] API equivalent > > [Update an Organization endpoint](/en/reference/products/midaz/v2/update-organization) # Editing an Asset Source: https://docs.lerian.studio/en/products/midaz/console/editing-asset-information Edit an existing Asset from the Console to update its name or metadata without affecting balances. The Asset type itself cannot be changed later. To edit the information of an Asset, follow these steps: **Step 1** From the **Assets** page, find the Asset that you want to edit, click the three dots () from the **Actions** column, and select **Edit**. **Step 2** The edit form opens on the right side of the screen. **Step 3** Edit the information as needed and click **Save**. * You cannot change the type or the **Code** of the Asset after creation. You can edit the name and metadata. > [card] API equivalent > > [Update an Asset endpoint](/en/reference/products/midaz/v2/update-asset) # Editing Portfolio information Source: https://docs.lerian.studio/en/products/midaz/console/editing-portfolio-information Edit an existing Portfolio in the Console to update its name, metadata, or details and keep your Account groupings accurate over time. To edit the information of a Portfolio, follow these steps: **Step 1** From the **Portfolios** page, find the Portfolio that you want to edit, click the three dots () from the **Actions** column, and select **Details**. **Step 2** The **Portfolio Details** form will open on the right side of the screen. **Step 3** Edit the information as needed and click **Save**. > [card] API equivalent > > [Update a Portfolio endpoint](/en/reference/products/midaz/v2/update-portfolio) # Editing Segment information Source: https://docs.lerian.studio/en/products/midaz/console/editing-segment-information Edit an existing Segment in the Console to update its name or metadata and refine how Accounts are classified for reporting and business rules. To edit the information of a Segment, follow these steps: **Step 1** From the **Segments** page, find the Segment that you want to edit, click the three dots () from the **Actions** column, and select **Details**. **Step 2** The **Segment Details** form will open on the right side of the screen. **Step 3** Edit the information as needed and click **Save**. > [card] API equivalent > > [Update a Segment endpoint](/en/reference/products/midaz/v2/update-segment) # Managing Account Types Source: https://docs.lerian.studio/en/products/midaz/console/managing-account-types Manage Account Types from the Midaz Module: enable Validate Account Type on a Ledger, then create and edit the categories that classify Accounts. You use the Midaz Module to manage Account Types. Account Types classify accounts by their role in your Organization’s financial structure. For more details, refer to the [Account Types](/en/products/midaz/account-types) page. ### Enabling Account Type validation You enable Account Type validation for a specific Ledger from the **Lerian Console**. You do not edit environment configuration files. **1. Open the Ledger Settings** On the **Ledgers** page, click the three dots () next to the Ledger. Select **Edit**. In the edit panel, click the **Settings** tab. **2. Enable Validate Account Type** Toggle on the **Validate Account Type** switch. The Console saves the change when you toggle the switch. > [!WARNING] > > The Type field is required whether or not validation is on. Validation changes the Type field from free text to a dropdown restricted to the registered Account Types. ## Accessing the Account Types page *** To open the **Account Types** page, select the **Account Types** option in the **Foundation** section of the left sidebar menu. > [!NOTE] > > The **Account Types** menu item appears only when you enable **Validate Account Type** for the active Ledger. If validation is off, the menu item is hidden. The **Account Types** page lists all Account Types you created for the current Ledger. > [!WARNING] > > **Account type validation disabled**. If **Validate Account Type** is off, a banner appears at the top of this page. You can view and edit the registered account types. The Ledger does not validate these rules when you create accounts. To enforce the rules, turn on **Validate Account Type** in the Ledger settings. ### Available actions From the **Account Types** page, you can: > [card] [Create an Account Type](/en/products/midaz/console/creating-an-account-type) > [card] [Edit an Account Type](/en/products/midaz/console/editing-account-type) # Managing Accounting Routes Source: https://docs.lerian.studio/en/products/midaz/console/managing-accounting-routes Manage Accounting Routes in the Console: create, edit, or delete Source, Destination, and Bidirectional operation routes and accounting scenarios. Use the **Midaz Module** to manage **Accounting Routes**, the configuration for transaction routing in Midaz. A guided wizard walks you through three steps: define the transaction route, add the operation routes, and review the setup. An Accounting Route defines the full routing logic for a transaction. It has three parts: * The transaction-level metadata is the title and description. * The operation routes set which accounts participate and in which direction. * The accounting scenarios control how the ledger records entries for each transaction type. > [card] [Accounting rules](/en/products/midaz/console/mc-accounting) > > Start here if you need to decide whether to use Source, Destination, Bidirectional, Account Type validation, alias validation, Direct, Two-Step, or Reversal scenarios. For technical details on the underlying entities, refer to the [Accounting Routes entities](/en/products/midaz/transaction-routing-entities) page. ## Key concepts *** ### Operation route types Each operation route within an Accounting Route has one of three types: * **Source**: defines validation rules for accounts where funds originate (debit side) * **Destination**: defines validation rules for accounts that receive funds (credit side) * **Bidirectional**: applies to both sides of the transaction as both source and destination > [!NOTE] > > A valid Accounting Route requires at least one required source and one required destination operation route, or at least one required bidirectional route. Optional operation routes do not count toward this rule. > [!TIP] > > A bidirectional route works as both source and destination. ### Required and optional operation routes Each operation route in an Accounting Route is required or optional. A transaction may leave an optional route unused. When it uses an optional route, the Ledger validates it like the others. You set this with the **Optional route** switch when you create or edit the Accounting Route. The setting applies to that Accounting Route only. ### Validation types Each operation route validates accounts by one of two methods: * **Account Type**: validates against one or more account type categories (e.g., `checking`, `savings`). Use when any account of a certain type is valid. * **@Alias**: validates against a specific account alias (e.g., `@treasury_main`). Use when you need to target an exact account. ### Accounting scenarios Accounting scenarios define how the ledger records debit and credit entries for each operation route. You can configure entries for five transaction types: * **Direct Transaction**: standard one-step transaction. Define the debit and credit account codes and descriptions for immediate settlement. * **Two-Step Transaction**: transactions that go through a hold-then-commit cycle. Configure entries for: * **Hold (Value Reserve)**: entries recorded when the ledger reserves funds * **Commit (Reservation Confirmation)**: entries recorded when you confirm the reservation * **Cancel (Reservation Cancellation)**: entries recorded when you cancel the reservation * **Reversal**: entries recorded when you reverse a completed transaction * **Overdraft**: entries recorded when a debit exceeds the account's available funds and draws on an overdraft line. Available for Source and Bidirectional operation routes, and requires both debit and credit entries on every supported route type. When you enable it, the Console also enables the Direct scenario. * **Block/Unblock**: entries recorded when you hold and release funds on the account's balance. The scenario tab label is **Block**. Available for all operation route types. Each scenario entry includes an **Account Code** and a **Description** for both the debit and credit sides. > [!TIP] > > The available entry sides depend on the operation route type and the scenario phase. The general rule is: > > * **Source**: debit entries in Direct, Hold, Commit, and Cancel. Credit entries only in Hold and Cancel. > * **Destination**: credit entries only, in Direct and Commit. Hold and Cancel are not available. > * **Bidirectional**: both debit and credit entries in all phases, including Reversal. > * **Block/Unblock**: available for all route types. It holds and releases funds on the account's balance. ## Accessing the Accounting Routes page *** > [!NOTE] > > The **Accounting Routes** menu appears only when you enable the **Validate Routes** setting for the current Ledger. To enable it, select **Edit** for the Ledger, go to the **Settings** tab, and toggle the **Validate Routes** switch. > [!WARNING] > > **Accounting Routes validation disabled**. If you open this page by URL while **Validate Routes** is off, a banner appears at the top of the screen. The Ledger does not yet process the accounting routes registered here. Entries follow these rules only after you enable **Validate Routes** in the Ledger settings. You can still view and edit routes, but they have no effect until you enable validation. To open the **Accounting Routes** page, select **Accounting Routes** in the **Accounting** section of the left sidebar menu. The **Accounting Routes** page displays your routes for the current Ledger as a **card-accordion list**. Each transaction route is a collapsible card. The card shows its title, transaction route ID, and an operation-count badge. When some operation routes are optional, the badge also shows how many, for example `3 Routes, 1 optional`. Expand a card to view its operation routes. Each one shows its ID, title, code, and operation type. The Console marks each operation type with its own badge, icon and color. A route with no operation routes appears as a static (non-expandable) card. An **Optional** badge marks each optional operation route. ### Available actions From the **Accounting Routes** page, you can: > [card] [Create an Accounting Route](/en/products/midaz/console/creating-an-accounting-route) > > Define a new transaction route with operation routes and accounting scenarios. > [card] [Edit an Accounting Route](/en/products/midaz/console/editing-an-accounting-route) > > Modify an existing accounting route and its operation routes. To delete an Accounting Route, open the menu () of its card and select **Delete**. Click **Confirm** in the dialog. The Console deletes only the Accounting Route. Its operation routes stay. ## Common use cases *** > [accordion] Pix transfers > > Create an Accounting Route with a bidirectional operation route that validates `checking` and `savings` account types. Enable Direct Transaction scenarios with the appropriate chart of accounts codes for Pix settlement entries. > [accordion] Two-step payment authorization > > Create an Accounting Route with separate source and destination routes. Enable Two-Step Transaction scenarios to record the hold (reservation), commit (confirmation), and cancel (cancellation) entries. On the source route, the ledger validates the hold, commit, and cancel entries as an atomic group. > [accordion] Treasury operations with reversal > > Create an Accounting Route with a bidirectional operation route that uses alias validation (`@treasury_main`). Enable both Direct Transaction and Reversal scenarios to handle standard movements and their reversals. Reversal entries require a bidirectional route. ## Best practices *** **1. Use descriptive titles** Name your Accounting Routes clearly to indicate the type of transaction they handle (e.g., `Pix Transfer Route` instead of `Route 1`). **2. Choose the right operation type** Use **Bidirectional** when the same validation rules apply to both sides. Use separate **Source** and **Destination** routes when each side has different account requirements. **3. Configure accounting scenarios early** Define your chart of accounts entries during route creation. This ensures that transactions processed through the route produce correct accounting records from the start. **4. Review before confirming** The wizard includes a Review step. Use it to verify all operation routes, validation rules, and accounting entries before you create the route. # Managing Accounts Source: https://docs.lerian.studio/en/products/midaz/console/managing-accounts Manage Accounts from the Lerian Console: create, edit, and delete internal Accounts, view balances, and classify them by type, portfolio, or segment. Use **Midaz Module** to manage **Accounts** associated with your Ledger. Accounts hold balances and participate in transactions within your financial system. ## What are Accounts? *** Accounts represent individual balance holders within your ledger structure. Each account: * **Holds balances** in a specific asset * **Participates in transactions** as sources or destinations of funds * **Belongs to an entity** such as a customer, business unit, or external party * **Supports portfolios, segments, and account types** for organization and reporting * **Tracks history** with complete audit trails of all movements Accounts can be classified as: * **Internal Accounts** - Accounts you create and manage for your organization's operations * **External Accounts** - Represent external assets or liabilities. Midaz creates one when you create an Asset, and you can create others with the **External account** option For technical details, refer to the [Accounts](/en/products/midaz/accounts) page. ## Key concepts *** * **Account Types** - Classify accounts according to your organization's financial structure (e.g., `checking`, `savings`, `revenue`). Enable validation to enforce account type rules. * **Account Alias** - A unique, human-readable identifier (e.g., `@customer_john_doe`) that makes it easier to reference accounts in transactions and queries. * **Portfolios** - Group related accounts together for reporting and management purposes. Useful for tracking customer portfolios or business divisions. * **Segments** - Group accounts by cost center, department, or region. ## Accessing the Accounts page *** To open the **Accounts** page, select the **Accounts** option in the **Accounts** section of the left sidebar menu. The **Accounts** page displays a table with all Accounts in the current Ledger, including: * **Account Name** - The account's display name * **ID** - The account's unique identifier * **Account Alias** - The unique, human-readable alias (if set) * **Assets** - The asset the account holds * **Metadata** - The number of custom key-value pairs on the account * **Portfolio** - The portfolio the account belongs to (if any) * **Actions** - The three-dots menu with the available actions. External accounts show a padlock icon instead > [!NOTE] > > The padlock icon marks an **external account**, which you cannot edit or delete. ### Available actions From the **Accounts** page, you can: > [card] [Create an Account](/en/products/midaz/console/creating-an-account) > > Add internal accounts for customers, departments, or business operations > [card] [Edit Account information](/en/products/midaz/console/editing-account-information) > > Modify account details, metadata, and organizational settings > [card] [Delete an Account](/en/products/midaz/console/deleting-an-account) > > Delete accounts you no longer need (internal accounts only) ## Account organization strategies *** > [accordion] Customer Account structure > > Create separate accounts for each customer, organized by account type and asset code. > > **Example**: > > * Customer checking account: `@customer_123_checking` (Type: `checking`, Asset: `USD`) > * Customer savings account: `@customer_123_savings` (Type: `savings`, Asset: `USD`) > * Group both under a Portfolio: `Customer 123 Portfolio` > [accordion] Treasury and float management > > Create dedicated treasury accounts to manage liquidity and operational funds. > > **Example**: > > * Main treasury: `@treasury_main` (Type: `treasury`, Asset: `USD`) > * Reserve fund: `@treasury_reserve` (Type: `reserve`, Asset: `USD`) > * Float account: `@float_operations` (Type: `float`, Asset: `USD`) > [accordion] Multi-currency operations > > Create separate accounts for each currency your organization handles. > > **Example**: > > * USD operations: `@ops_usd` (Type: `operations`, Asset: `USD`) > * EUR operations: `@ops_eur` (Type: `operations`, Asset: `EUR`) > * BRL operations: `@ops_brl` (Type: `operations`, Asset: `BRL`) > [accordion] Department cost centers > > Use segments and account types to track departmental expenses. > > **Example**: > > * Engineering expenses: `@eng_expenses` (Type: `expense`, Segment: `Engineering`) > * Marketing expenses: `@mkt_expenses` (Type: `expense`, Segment: `Marketing`) ## Account type validation *** Account type validation makes each account follow your organization's financial structure. ### Enabling Account type validation Account type validation is a per-ledger setting. To turn it on in the Console: on the **Ledgers** page, select **Edit** for the Ledger, click the **Settings** tab, and toggle on **Validate Account Type**. As a programmatic alternative, send a `PATCH` request to `/v1/organizations/{organization_id}/ledgers/{ledger_id}/settings` with this body: ```json theme={null} { "accounting": { "validateAccountType": true } } ``` For more information about managing account types, see [Managing Account Types](/en/products/midaz/console/managing-account-types). ## Best practices *** **1. Use descriptive names and aliases** Name accounts clearly and use aliases for easy reference (e.g., `@customer_john_checking` instead of UUID references). **2. Use account types** Enable account type validation to enforce your chart-of-accounts structure and prevent misclassification. **3. Organize with portfolios** Group related accounts into portfolios for better reporting and management, especially for customer relationships. **4. Plan your asset codes** Use consistent asset code conventions (ISO 4217 for currencies) to simplify multi-currency operations. **5. Document with metadata** Use metadata fields to store additional context like customer IDs, department codes, or integration references. # Managing Assets Source: https://docs.lerian.studio/en/products/midaz/console/managing-assets Manage the Assets registered in your Ledger from the Midaz Module: create, edit, and delete the currencies, tokens, or commodities you use. You can manage the Assets associated with your Ledger directly from **Midaz Module**. ## Accessing the Asset page *** To open the **Assets** page, select the **Assets** option in the **Foundation** section of the left sidebar menu. The **Assets** page will display a list of **Assets** created for the current Ledger. ### Available actions From the **Assets** page, you can: > [card] [Create an Asset](/en/products/midaz/console/creating-an-asset) > [card] [Edit an Asset](/en/products/midaz/console/editing-asset-information) > [card] [Delete an Asset](/en/products/midaz/console/deleting-an-asset) # Managing Balances Source: https://docs.lerian.studio/en/products/midaz/console/managing-balances Manage Account Balances from the Lerian Console: list, read, and create balances, and control sending and receiving permissions without leaving the interface. Use the **Midaz Module** to manage the **Balances** in your Accounts. A balance tracks one asset in one account. It records the available amount and the on-hold amount. You find balances in the **Balances** section of the account details page. ## What you can do * **List balances** for an account to see the available and on-hold amounts per balance key. * **Read a balance** to inspect its current state and metadata. * **Create an additional balance** for an account under a new balance key. The balance inherits the account's asset. * **Update a balance** to toggle whether it can send or receive funds (**Send** and **Receive** in **Balance Details**). > [!NOTE] > > You manage overdraft limits through the update-balance API, not the Console. > [!NOTE] > > The Console UI does not support balance history or balance deletion. # Managing Alias Accounts Source: https://docs.lerian.studio/en/products/midaz/console/managing-crm-alias-accounts Manage Alias Accounts in the Midaz Module: create, edit, and delete customer-facing account records that link Holders to their underlying Accounts. Use **Midaz Module** to manage **Alias Accounts**. Alias Accounts create the link between Holders and Midaz ledger accounts. They add business context such as bank account numbers and financial institution details. ## What are Alias Accounts? *** An **Alias Account** connects a Holder (individual or company) to a specific Midaz ledger account. In Midaz Module, each alias account stores: * **Account identification** - Bank ID, branch, account, and type * **Holder reference** - Link to the associated holder (Natural or Legal Person) * **Ledger account link** - Connection to the underlying Midaz account * **Banking details** - Opening date, IBAN, country code, and the Participant Document under Regulatory * **Related parties** - People linked to the account, each with a role and a start date, under Regulatory * **Custom metadata** - Additional fields for integration and business-specific needs Alias Accounts let you keep customer-facing account information separate from the transactional ledger. This supports multi-bank scenarios and external system integration. For technical details about the underlying CRM capabilities, refer to the [CRM Overview](/en/products/midaz/crm/crm-overview) page. ## Accessing the Alias Accounts page *** To open the **Alias Accounts** page, select the **Alias** option from the Accounts section of the left-side menu. With Access Manager, this page needs the read permission on instruments. To create, edit, or delete an alias account, you need the create, update, or delete permission on instruments. The **Alias Accounts** page displays a table listing the Alias Accounts of the current Organization, including: * **Holder Name** - The associated holder name * **Holder ID** - The identifier of the associated holder * **Account ID** - The identifier of the linked ledger account * **Ledger** - The ledger the linked account belongs to * **Type** - Classification of the account (checking, savings, etc.) * **Actions** - The actions available for each alias account > [!NOTE] > > If you do not have any Alias Accounts, the list will appear empty with a prompt to create your first alias account. ### Available actions From the **Alias Accounts** page, you can: > [card] [Create an Alias Account](/en/products/midaz/console/crm-creating-alias-account) > > Link a holder to a Midaz ledger account with bank details > [card] [Edit an Alias Account](/en/products/midaz/console/crm-editing-alias-account) > > Update account information and financial details > [card] [Delete an Alias Account](/en/products/midaz/console/crm-deleting-alias-account) > > Remove the link between a holder and ledger account ## Common use cases *** > [accordion] Linking customer accounts > > When a customer opens an account: > > 1. Create a Holder with customer information (Natural or Legal Person) > 2. Create an Alias Account linking the holder to a Midaz ledger account > 3. Add banking details (bank ID, branch, account, type) > [accordion] Multi-bank scenarios > > When customers have accounts at multiple institutions: > > * Create multiple Alias Accounts for the same Holder > * Each alias account references a different Midaz ledger account > * Track different account numbers and bank relationships > * Maintain clear separation between institutional relationships > [accordion] External system integration > > When integrating with external banking systems: > > * Use Alias Accounts to map external account numbers to internal ledger accounts > * Store regulatory identifiers such as the Participant Document ## Best practices *** **1. Create holders before alias accounts** Always create the Holder record first, then create Alias Accounts to link them to ledger accounts. **2. Use consistent account numbering** Follow your institution's account numbering standards when creating alias accounts to avoid confusion and integration issues. **3. Keep financial institution details accurate** Ensure Bank IDs and other banking details are correct for proper payment routing and regulatory compliance. # Managing Holders Source: https://docs.lerian.studio/en/products/midaz/console/managing-crm-holders Manage Holders in the Midaz Module: create, edit, and delete individuals or companies with their identity, contact, and address information. Use the **Midaz Module** to manage **Holders**. Holders represent the people or organizations behind your accounts. In the console, you create, view, edit, and manage their information. ## What are Holders? *** A **Holder** represents an individual (Natural Person) or a company (Legal Person) linked to your Midaz accounts. Each holder stores: * **Identity information** - Name, document number (CPF/CNPJ), and an optional free-text status * **Contact details** - Email addresses and phone numbers for communication * **Address information** - Primary and additional addresses with complete location data * **Person-specific data** - Personal details for individuals or business information for companies * **Custom metadata** - Additional fields for integration and business-specific needs Holders connect to ledger accounts through Alias Accounts. This keeps customer data separate from transactional operations. For technical details about the underlying CRM capabilities, refer to the [CRM Overview](/en/products/midaz/crm/crm-overview) page. ## Accessing the Holders page *** To open the **Holders** page, select the **Holders** option from the Accounts section of the left-side menu. The **Holders** page shows a table with the Holders of the current Organization. ### Available actions From the **Holders** page, you can: > [card] [Create a Holder](/en/products/midaz/console/crm-creating-a-holder) > > Add new individuals or companies as Holders > [card] [Edit a Holder](/en/products/midaz/console/crm-editing-a-holder) > > Update holder information, contact details, and status > [card] [Delete a Holder](/en/products/midaz/console/crm-deleting-a-holder) > > Remove holders (soft delete). Hard delete is available only through the API (`?hard_delete=true`) ## Understanding Holder types *** When you create a Holder, you select the holder type. The type determines which fields you can manage: ### Natural Person (Individual) For individual customers, the console shows fields for: * **Basic information**: Full name, document (CPF), contact details * **Personal details**: Favorite name, social name, gender, birth date * **Family information**: Civil status, mother's name, father's name * **Demographics**: Nationality ### Legal Person (Company) For corporate customers, the console shows fields for: * **Basic information**: Company name, document (CNPJ), contact details * **Business details**: Trade name, company activity, founding date * **Structure**: Company size, company type, business status * **Legal representation**: Representative name, document, role, contact ## Managing Holder status *** **Status** is an optional free-text field on the holder form. Use it to record any classification your business needs, such as `active` or `under-review`. > [!NOTE] > > To change the status, edit the holder. The holders list shows the **Name**, **ID**, **Type**, and **Primary E-mail** columns. Open a holder to see its status. ## Common use cases *** > [accordion] Setting up individual customers > > To onboard individual customers in the console: > > 1. Create a Natural Person holder with personal details > 2. Add primary address and contact information > 3. Link to checking/savings accounts via Alias Accounts > 4. Use metadata for customer-specific attributes (loyalty tier, risk profile, etc.) > [accordion] Managing business customers > > To manage corporate accounts in the console: > > 1. Create a Legal Person holder with company information > 2. Add legal representative details for compliance > 3. Include business addresses and contact points > 4. Link to corporate treasury and operational accounts > 5. Track company size and activity sector for reporting > [accordion] Integrating with external systems > > Use the External ID field in the console to keep systems in sync: > > * Map each holder to your existing CRM using External ID > * Keep document numbers consistent across systems > * Use metadata for integration-specific fields > * Update status in the console to reflect external system changes ## Best practices *** **1. Choose the correct holder type at creation** Select Natural Person for individuals and Legal Person for companies. You cannot change the type later. The type sets which fields the console forms show. **2. Keep document numbers accurate** Document numbers (CPF, CNPJ) must be unique and correctly formatted. The document field is required, but the console does not validate its format. Verify the numbers yourself for regulatory compliance. **3. Maintain updated contact information** Update email addresses and phone numbers in the console regularly. **4. Use External ID for integration** When you create a holder, fill in the External ID field. It maps the holder to your existing customer database. **5. Use metadata for custom needs** Use the Metadata step in the holder form to store extra information. You do not change the core structure. **6. Keep the status field meaningful** If you use the optional status field, define a consistent set of values for your team and update it to reflect customer relationship changes before deletion. # Managing Ledgers Source: https://docs.lerian.studio/en/products/midaz/console/managing-ledgers-via-console Manage Ledgers in your Organization from the Midaz Module: create, edit, and delete them, and enable Validate Account Type or Validate Routes. A Ledger groups the Accounts and Transactions in your Organization. You manage these Ledgers from the **Midaz Module**. ## Current Ledger *** The name of the current Ledger appears in the header of the home page (*Figure 1*). ![Home page header section displaying the name of the currently selected Ledger](https://mintcdn.com/lerian-49cb71fc/yneNeAhnXdrrmE3_/images/en/console/home-header-ledger.png?fit=max\&auto=format\&n=yneNeAhnXdrrmE3_\&q=85\&s=2b259ca02ffe000365bc5159be069b74) Figure 1. Section displaying the name of the current Ledger. ## Accessing the Ledgers page *** To open the **Ledgers** page, click the **Ledgers** option in the **Foundation** section of the left sidebar menu. The **Ledgers** page lists the Ledgers in your Organization and marks the current one with **(current)**. ### Available actions From the **Ledgers** page, you can: > [card] [Create a new Ledger](/en/products/midaz/console/creating-a-new-ledger) > [card] [Edit a Ledger](/en/products/midaz/console/editing-a-ledger) > [card] [Delete a Ledger](/en/products/midaz/console/deleting-a-ledger) ## Ledger settings *** Each Ledger has a **Settings** tab where you can enable validation rules for Accounts and Transactions. In edit mode, the tab also holds the Tracer settings of the Ledger. **1. Open the Ledger edit panel** On the **Ledgers** page, find the Ledger you want to configure. Click the three dots () in the **Actions** column. Select **Edit**. **2. Open Settings** In the edit panel, click the **Settings** tab. **3. Update validation rules** Enable or disable **Validate Account Type** and **Validate Routes** for this Ledger. In edit mode, set the Tracer **Mode**, **Fail Posture**, and **Timeout (ms)**, and the **Allow Tracer skip** switch. The Console saves each change when you make it. ### Available settings | Setting | What it controls | When to enable | | - | - | - | | Validate Account Type | Requires new Accounts to use an Account Type registered for this Ledger. | Enable when Accounts must follow a controlled classification model. | | Validate Routes | Requires Transactions to match configured Accounting Routes. | Enable after your Accounting Routes are planned or configured. | | Tracer **Mode** | **Off** does not call Tracer. **Advisory** calls Tracer and never blocks a Transaction. **Enforce** lets Tracer refuse a Transaction. | Choose **Advisory** or **Enforce** when this Ledger uses Tracer. | | Tracer **Fail Posture** | With **Enforce**, when Tracer does not answer in time, **Open** records the Transaction without the check, and **Closed** refuses it. | Choose **Closed** when no Transaction may be recorded without the check. | | Tracer **Timeout (ms)** | The longest the Ledger waits for Tracer on each Transaction, from 1 to 30000 ms. | | | **Allow Tracer skip** | Lets a Transaction ask to skip the Tracer check. | | > [!WARNING] > > Do not enable **Validate Routes** before your Accounting Routes exist. A Transaction that does not match a route fails validation. # Managing the Metadata Index Source: https://docs.lerian.studio/en/products/midaz/console/managing-metadata-index Manage the Metadata Index from the Lerian Console: list, create, and remove indexed metadata keys to speed up searches across your Midaz entities. Use the **Midaz Module** to manage the **Metadata Index**. Metadata indexes let you efficiently query entities by the custom key/value metadata you attach to organizations, ledgers, accounts, transactions, and other resources. ## What you can do * **List indexes** to see which metadata keys have an index. * **Create an index** on a metadata key to speed up lookups and filters on that key. * **Remove an index** when you no longer query that metadata key. To open the page, select **Metadata Indexes** in the **Settings** section of the left sidebar menu. To create an index, choose an **Entity Name** and enter a **Metadata Key**. **Unique** is off by default. **Sparse** is on by default. Keep the index focused on the keys you query. This keeps search fast and predictable. # Managing Operation Routes Source: https://docs.lerian.studio/en/products/midaz/console/managing-operation-routes Manage Operation Routes in the Console: list, create, edit, and delete the rules that select the accounts on each side of a transaction. Use the **Midaz Module** to manage the **Operation Routes** of the current Ledger. An operation route is a rule for one side of a transaction. It sets which accounts can take part in that side. You can also create operation routes inside an Accounting Route. For the full routing model, refer to [Managing Accounting Routes](/en/products/midaz/console/managing-accounting-routes) and [Accounting Routes entities](/en/products/midaz/transaction-routing-entities). ## Accessing the Operation Routes page *** > [!NOTE] > > The **Accounting** section of the sidebar appears only when you enable the **Validate Routes** setting for the current Ledger. To enable it, select **Edit** for the Ledger, go to the **Settings** tab, and toggle the **Validate Routes** switch. To open the page, select **Operation Routes** in the **Accounting** section of the left sidebar menu. > [!WARNING] > > **Operation Routes validation disabled**. If you open this page by URL while **Validate Routes** is off, a banner appears at the top of the screen. The Ledger does not process the operation routes registered here. Entries follow these rules only after you enable **Validate Routes** in the Ledger settings. The page lists the operation routes of the current Ledger in a table: | Column | Content | | - | - | | **Title** | The name of the operation route. | | **Description** | The description of the operation route. | | **Operation Type** | The side of the transaction that the route validates. | | **Rule Type** | The validation rule. Hover over the value to see the alias or the Account Types that the rule accepts. | | **Metadata** | The metadata of the operation route. | | **Actions** | The menu with the **Details** and **Delete** options. | If the Ledger has no operation routes, the page shows the message **You haven't created any Operation Routes yet.** and a **New Operation Route** button. ## Creating an operation route *** **1. Open the form** Select **New Operation Route**. A side panel opens with two tabs: **Operation Route Details** and **Metadata**. **2. Fill in the details** On the **Operation Route Details** tab, fill in the fields in the table below. **3. Add metadata (optional)** On the **Metadata** tab, add key-value pairs. **4. Save the route** Select **Save**. A message confirms that the Console created the operation route. | Field | Required | Description | | - | - | - | | **Operation Route Name** | Yes | The title of the operation route. | | **Description** | No | A description of the operation route. | | **Operation Type** | Yes | **Source** or **Destination**. You cannot change it after you create the route. | | **Rule Type** | Yes | **Alias** or **Account Type**. | | **Account Alias** | Yes, for the **Alias** rule | Search for the account by its alias and select it. | | **Account Types** | Yes, for the **Account Type** rule | Select one or more Account Types of the Ledger. | | **Code** | No | A code for the operation route. | > [!NOTE] > > This form has no **Bidirectional** option and no accounting scenarios. To set them, use the wizard in [Creating an Accounting Route](/en/products/midaz/console/creating-an-accounting-route). ## Editing an operation route *** **1. Open the route** In the row of the operation route, click the three dots () and select **Details**. The edit panel opens with the current values. **2. Change the fields** Change the fields on the **Operation Route Details** and **Metadata** tabs. You cannot change the **Operation Type** field. **3. Save the changes** Select **Save**. A message confirms that the Console updated the operation route. ## Deleting an operation route *** **1. Select Delete** In the row of the operation route, click the three dots () and select **Delete**. **2. Confirm the deletion** In the confirmation dialog, select **Confirm**. A message confirms that the Console deleted the operation route. ## Permissions *** With Access Manager, this page needs the read permission on operation routes. To create, edit, or delete an operation route, you need the create, update, or delete permission on operation routes. # Viewing Operations Source: https://docs.lerian.studio/en/products/midaz/console/managing-operations View the Operations that make up a Transaction in the Lerian Console: inspect each balance movement per account and its metadata. Use the **Midaz Module** to review the **Operations** that compose each Transaction. Operations are individual balance movements. Depending on the transaction lifecycle, their type can be `DEBIT`, `CREDIT`, `ON_HOLD`, `RELEASE`, `OVERDRAFT`, `BLOCK`, `UNBLOCK`, `FEE_SETTLEMENT` (a fee debt settled), or `FEE_REFUND` (a fee debt refunded by a reversal). ## What you can do * **View operation details** to see the type, direction, asset, amount, status, balance key, and accounting route. The details also show the balance before and after the operation, along with any metadata. > [!NOTE] > > You cannot edit the operation details sheet. To update operation metadata, use the update-operation API. Operations always belong to a parent Transaction. You open them from the transaction detail view or from the **Operations Statement** section on the account details page. # Managing Organizations Source: https://docs.lerian.studio/en/products/midaz/console/managing-organizations Manage Organizations in the Midaz Module: create, edit, delete, and switch between the top-level entities that own your Ledgers and Accounts. The Midaz module lets you manage your Organizations directly. You can create, edit, delete, and switch between them. ## Accessing the Organizations page *** To open the **Organizations** page, click the **Organizations** option in the **Foundation** section of the left sidebar menu. The **Organizations** page lists all your Organizations. ### Available actions From the **Organizations** page, you can: > [card] [Create an Organization](/en/products/midaz/console/creating-an-organization) > [card] [Edit an Existing Organization](/en/products/midaz/console/editing-an-organization) > [card] [Delete an Organization](/en/products/midaz/console/deleting-an-organization) ## Multiple Organizations *** You can also open the **Organizations** page from the navigation bar. Click the Organization icon in the left navigation bar. Then select **Organizations** in the pop-up window (*Figure 1*). ![Alternative way to open the Organizations page, using the organization icon in the left navigation bar](https://mintcdn.com/lerian-49cb71fc/yneNeAhnXdrrmE3_/images/en/console/organizations_menu_alt.png?fit=max\&auto=format\&n=yneNeAhnXdrrmE3_\&q=85\&s=a4af7abcf3575db2fe6517eb995ff14a) Figure 1. Alternative options to open the Organizations page for multiple Organizations. ### Changing Organizations To work on a different Organization, use the same pop-up window. It lists up to three other Organizations that you can select directly. To see all of them, select the cog icon (). The **Organizations** page opens. Find the Organization you want. Click the three dots () in the **Actions** column. Then select **Switch to this organization**. # Managing Portfolios Source: https://docs.lerian.studio/en/products/midaz/console/managing-portfolios Manage Portfolios from the Lerian Console: create, edit, and delete the containers that group related Accounts under a customer or business unit. Use **Midaz Module** to manage **Portfolios** that group your accounts. A Portfolio gives your accounts a higher-level structure. You manage a set of accounts as a single unit. ## What are Portfolios? *** A **Portfolio** is a container that groups related accounts within a ledger. In Midaz Module, portfolios enable you to: * **Group related accounts** - Organize accounts that belong together logically or operationally * **Associate with external entities** - Link portfolios to external system identifiers via Entity ID * **Simplify account management** - Manage multiple accounts as a single unit * **Add custom context** - Store additional information through metadata for integration and reporting Portfolios are ledger-specific. Each ledger has its own set of portfolios. For technical details about portfolios in Midaz, refer to the [Portfolios documentation](/en/products/midaz/portfolios). ## Accessing the Portfolios page *** To open the **Portfolios** page, select the **Portfolios** option from the Accounts section of the left-side menu. The **Portfolios** page displays a table of all Portfolios in your Ledger. > [!NOTE] > > If you have no Portfolios, the list is empty and shows a prompt to create your first Portfolio. ### Available actions From the **Portfolios** page, you can: > [card] [Create a Portfolio](/en/products/midaz/console/creating-a-portfolio) > > Add a new portfolio to group your accounts > [card] [Edit a Portfolio](/en/products/midaz/console/editing-portfolio-information) > > Update portfolio name and metadata > [card] [Delete a Portfolio](/en/products/midaz/console/deleting-a-portfolio) > > Remove a portfolio from your ledger ## Common use cases *** > [accordion] Customer account grouping > > Create portfolios to group all accounts belonging to a single customer: > > * Portfolio: `Customer-12345` with Entity ID linking to your CRM > * Contains: Checking account, savings account, investment accounts > * Use metadata for customer tier, relationship manager, onboarding date > [accordion] Product-based organization > > Organize accounts by financial product: > > * `Checking Accounts Portfolio` - All customer checking accounts > * `Savings Accounts Portfolio` - All customer savings accounts > * `Business Accounts Portfolio` - All commercial/business accounts > * `Investment Accounts Portfolio` - All investment-related accounts > [accordion] Institutional portfolios > > Group accounts by institution or partner: > > * `Partner Bank A` - Accounts related to Partner Bank A operations > * `Partner Bank B` - Accounts for Partner Bank B integration > * Use Entity ID to link to partner identifiers in your system > [accordion] Operational grouping > > Create portfolios for operational purposes: > > * `Treasury Operations` - Internal treasury and liquidity accounts > * `Settlement Accounts` - Accounts used for settlement operations > * `Suspense Accounts` - Temporary holding accounts for reconciliation > * `Fee Collection` - Accounts for collecting and managing fees ## Best practices *** **1. Plan your portfolio structure** Design your portfolio structure before you create accounts. Decide how to group the accounts and which Entity IDs to use for external systems. **2. Use Entity ID for integration** Set the Entity ID during creation when a portfolio links to an external system (CRM, core banking). External systems can then match the portfolio to their own records. **3. Choose meaningful names** Use portfolio names that clearly indicate the purpose or contents of the portfolio. **4. Use metadata for context** Use the Metadata tab to store extra details. Add business unit codes, cost centers, or integration references that do not fit in the standard fields. **5. Keep portfolios focused** Each portfolio should have a clear purpose. Do not create catch-all portfolios. Instead, create a specific portfolio for each use case. ## Portfolios vs Segments *** Both Portfolios and Segments help organize accounts, but they serve different purposes: | Feature | Portfolio | Segment | | - | - | - | | **Purpose** | Group related accounts as a unit | Classify accounts by category | | **Entity ID** | Yes - links to external entities | No | | **Use Case** | Customer accounts, product grouping | Departmental, regional classification | | **Relationship** | One-to-many (portfolio contains accounts) | One-to-many (segment classifies accounts) | You can use portfolios and segments together to organize accounts. For example, accounts in a customer portfolio can also belong to a segment (checking, savings, investment). # Managing Segments Source: https://docs.lerian.studio/en/products/midaz/console/managing-segments Manage Segments from the Console: create, edit, and delete the classifications used to group Accounts by department, region, or business function. Use **Midaz Module** to manage **Segments** that help you organize and categorize your accounts. Segments group accounts by business purpose, department, region, or any other classification relevant to your organization. ## What are Segments? *** A **Segment** is an organizational unit that helps you classify and group accounts within a ledger. In Midaz Module, segments enable you to: * **Organize accounts by purpose** - Group accounts by business function, department, or product line * **Apply business classifications** - Use segments to filter and analyze accounts by classification * **Maintain flexibility** - Add custom metadata for integration and business-specific needs Segments are ledger-specific. Each ledger can have its own set of segments. For technical details about segments in Midaz, refer to the [Segments documentation](/en/products/midaz/segments). ## Accessing the Segments page *** To open the **Segments** page, select the **Segments** option on the Accounts section of the left-side menu. The **Segments** page displays a table listing all Segments in your Ledger. > [!NOTE] > > If you do not have any Segments, the list will appear empty with a prompt to create your first segment. ### Available actions From the **Segments** page, you can: > [card] [Create a Segment](/en/products/midaz/console/creating-a-segment) > > Add a new segment to organize your accounts > [card] [Edit a Segment](/en/products/midaz/console/editing-segment-information) > > Update segment name and metadata > [card] [Delete a Segment](/en/products/midaz/console/deleting-a-segment) > > Remove a segment from your ledger ## Common use cases *** > [accordion] Departmental organization > > Create segments to represent different departments or cost centers: > > * `Finance` - For treasury and financial operations accounts > * `Operations` - For operational and transactional accounts > * `HR` - For payroll and employee-related accounts > * `Sales` - For revenue and customer-related accounts > [accordion] Product line separation > > Organize accounts by product or service offering: > > * `Checking Products` - All checking account-related segments > * `Savings Products` - Savings and investment account segments > * `Loans` - Credit and lending product segments > * `Cards` - Credit and debit card operation segments > [accordion] Regional organization > > Group accounts by geographic region: > > * `North Region` - Accounts for northern operations > * `South Region` - Accounts for southern operations > * `International` - Cross-border and international accounts > [accordion] Compliance and reporting > > Create segments for regulatory and reporting purposes: > > * `Regulatory Reserve` - Accounts subject to reserve requirements > * `Audit Trail` - Accounts requiring special audit tracking > * `Tax Reporting` - Accounts with specific tax reporting needs ## Best practices *** **1. Plan your segment structure** Plan your segments before you create accounts. **2. Use clear, descriptive names** Choose segment names that clearly indicate their purpose. **3. Add metadata for context** Use the Metadata tab to store additional information like cost center codes, department IDs, or integration references. **4. Keep segments consistent across ledgers** If you have multiple ledgers, consider using consistent segment naming conventions for easier cross-ledger reporting. **5. Review segments regularly** Periodically review your segment structure to ensure it still aligns with your organizational needs. ## Segments and transaction rules *** Segments classify accounts for organization, filtering, and reporting. Fee packages and Tracer limits can use a segment as a scope. Route validation in [Accounting Routes](/en/products/midaz/console/managing-accounting-routes) supports only account types and aliases. There is no segment-based routing. Use segments to keep your account structure organized and to slice reports by department, region, or product line. # Managing Transactions Source: https://docs.lerian.studio/en/products/midaz/console/managing-transactions Manage Transactions from the Midaz Module: create new Transactions between Accounts and inspect approved or canceled records in your Ledger. Use the **Midaz Module** to view, create, and monitor **Transactions** in a visual interface. The Transactions page shows every financial movement in your Ledger. You can track balances, review operations, and create transactions without writing code. > [!NOTE] > > See the [Transactions](/en/products/midaz/transactions) reference documentation for transaction structures, double-entry accounting, N:N transactions, and API integration. ## Accessing the Transactions page *** Select the **Transactions** option in the left-side menu to open the **Transactions** page. The **Transactions** page shows a table of all Transactions in your Ledger. > [!NOTE] > > If your Ledger has no Transactions, the list is empty and shows a prompt to create your first transaction. ### Available actions From the **Transactions** page, you can: > [card] [Create a Transaction](/en/products/midaz/console/creating-a-transaction) > > Record a new asset movement between accounts > [card] [Check Transaction details](/en/products/midaz/console/checking-transaction-details) > > See complete transaction information and operations ## Transaction status *** Transactions in Midaz have the following statuses: * **CREATED** - Only the create response carries this status. Midaz stores the transaction as `APPROVED` * **PENDING** - A two-step transaction holding funds, awaiting commit or cancel * **APPROVED** - Midaz posted the transaction * **CANCELED** - Midaz canceled the transaction * **NOTED** - An annotation-only transaction with no balance changes. Its operations remain with all balance fields zeroed > [!NOTE] > > After Midaz approves a transaction, you cannot edit its operations or amounts, and you cannot delete it. To reverse it, create a reversal transaction. This protects the integrity of your financial records. ## Common use cases *** > [accordion] Simple transfer between two accounts > > A basic transaction moving funds from one account to another: > > * **Source**: Customer checking account (debit \$100) > * **Destination**: Merchant account (credit \$100) > * Single source, single destination, equal amounts > [accordion] Payment with fees > > A transaction that splits funds between multiple destinations: > > * **Source**: Customer account (debit \$103) > * **Destinations**: > * Merchant account (credit \$100) > * Fee collection account (credit \$3) > * Single source, multiple destinations > [accordion] Consolidated payment > > Multiple sources funding a single destination: > > * **Sources**: > * Primary account (debit \$500) > * Secondary account (debit \$300) > * **Destination**: Vendor account (credit \$800) > * Multiple sources, single destination > [accordion] Complex multi-party transaction > > Multiple sources and destinations in a single transaction: > > * **Sources**: > * Customer A (debit \$200) > * Customer B (debit \$300) > * **Destinations**: > * Vendor account (credit \$450) > * Tax account (credit \$50) > * Multiple sources, multiple destinations ## Best practices *** **1. Write clear transaction descriptions** Include a clear description of the purpose of each transaction. **2. Verify account balances before transacting** Make sure the source account has enough balance before you create a transaction. This avoids rejections. **3. Use metadata for integration context** Store external reference IDs, order numbers, or other system identifiers in the transaction metadata for traceability. **4. Group related operations logically** When possible, combine related transfers into one transaction instead of several separate transactions. **5. Review transactions before confirming** Double-check the source accounts, destination accounts, and amounts before you submit. After you create a transaction, you can edit only its description and metadata. ## Accounting Routes integration *** Midaz can validate Transactions against [Accounting Routes](/en/products/midaz/console/managing-accounting-routes) before it processes them. Accounting Routes define which accounts can transact with each other. # Accounting rules Source: https://docs.lerian.studio/en/products/midaz/console/mc-accounting Learn how Accounting Routes decide which Accounts join a transaction and how debit and credit entries are posted for each transaction type in Midaz. The **Accounting** section is where you define optional rules for transactions. The sidebar shows the **Accounting** section only when the current Ledger has **Validate Routes** on. While **Validate Routes** is off, open **Accounting Routes** and **Operation Routes** from the page search (**Search pages...**), and create the routes before you turn validation on. You do this through **Accounting Routes**. An Accounting Route is a reusable rule for one kind of transaction, such as a *Pix transfer*, a *card purchase*, or a *fee charge*. Each route answers three questions: * Which accounts can act on the source side? * Which accounts can act on the destination side? * Which debit and credit entries does the route post when the transaction runs? **Example.** A `Pix transfer` route can require a `customer` account on the source side and a `merchant` account on the destination side. The route then defines direct debit-and-credit entries between them. When you enable route validation, a Pix transaction that references the route validates the accounts and applies the configured rules. Accounting Routes provide optional route validation. Midaz enforces them only when you enable the Ledger setting `accounting.validateRoutes` (default `false`). When enabled, transactions must reference valid routes and operations must match configured rules. Routes are easier to model when you already know which accounts represent customers, treasury, fees, settlement, revenue, and expenses. ## How the pieces fit together *** ![How accounts, account types, and accounting routes fit together so a transaction request is validated and posted as debit-and-credit entries](https://mintcdn.com/lerian-49cb71fc/SFzzdxyH5SN7w_fC/images/en/d2/accounting-route-flow.svg?fit=max\&auto=format\&n=SFzzdxyH5SN7w_fC\&q=85\&s=a504463da029fe875e18198b63546708) | Piece | What it controls | Example | | - | - | - | | Accounting Route | The transaction-level route that groups the operation rules. | `Pix transfer route` | | Operation Route | The account side and validation rule. | `Source must be customer`, `Destination must be merchant` | | Validation rule | How Midaz decides whether an account can be used. | Account Type `customer` or alias `@treasury_main` | | Accounting scenario | Which debit and credit entries are posted for the transaction lifecycle. | Direct, Two-Step, Reversal, Overdraft, Block/Unblock | ## Choosing the operation type *** > [accordion] Use Source when the rule applies only to the sending side > > Use **Source** for accounts where value originates. > > Example: a customer account can send funds in a payment flow. > [accordion] Use Destination when the rule applies only to the receiving side > > Use **Destination** for accounts where value lands. > > Example: a merchant account can receive funds in a payment flow. > [accordion] Use Bidirectional when the same rule applies to both sides > > Use **Bidirectional** when the same account class can send and receive. > > Example: checking accounts can transfer value to other checking accounts. > [!NOTE] > > A route must include a required Source and a required Destination operation route, or at least one required Bidirectional operation route. Other operation routes can be optional: a transaction may leave them unused. ## Choosing the validation rule *** | Validation type | Use when | Example | | - | - | - | | Account Type | Any account in a class should be valid. | Any `customer` account can send. | | Alias | Only one exact account should be valid. | Only `@treasury_main` can send. | Each Operation Route in the Console needs an account rule: registered Account Types or an `@Alias`. Midaz enforces the rule when you enable route validation. Use Account Type validation for scalable flows. Use alias validation for fixed operational accounts, such as treasury, fee, settlement, or suspense accounts. ## Common route patterns *** ### Customer to merchant Use separate Source and Destination routes when each side has a different role. | Operation route | Validation | | - | - | | Source | Account Type `customer` | | Destination | Account Type `merchant` | ### Peer-to-peer transfer Use a Bidirectional route when the same account type can be both source and destination. | Operation route | Validation | | - | - | | Bidirectional | Account Type `customer` | ### Fee collection Use a Destination route with alias validation when fees must always land in one operational account. | Operation route | Validation | | - | - | | Source | Account Type `customer` | | Destination | Alias `@fee_revenue` | ## Accounting scenarios *** | Scenario | Use when | What the user configures | | - | - | - | | Direct Transaction | The movement is executed in one step. | Debit and credit entries for immediate posting. | | Two-Step Transaction | The movement has hold, commit, and cancel phases. | Entries for reservation, confirmation, and cancellation. | | Reversal | A completed transaction may need to be reversed. | Debit and credit entries for the reversal event. | | Overdraft | A debit may exceed the account's available funds, drawing on an overdraft line. | Debit and credit entries for the overdraft draw and later repayment. | | Block/Unblock | Funds need to be held and later released on the account's balance. Available for all route types (tab label "Block"). | Entries for the block (hold) and unblock (release) events. | > [!WARNING] > > Do not enable route validation in Ledger settings until the required routes exist. If you enable it without matching routes, transactions fail validation. ## Available pages *** > [card] [Setting up accounting in the Console](/en/products/midaz/console/accounting-setup-in-console) > > A step-by-step, Console-first guide to building your accounting model, from chart of accounts to a working Pix payment. No API calls required. > [card] [Manage Accounting Routes](/en/products/midaz/console/managing-accounting-routes) > > Configure accounting routes with operation rules and accounting scenarios in one wizard. # Account management Source: https://docs.lerian.studio/en/products/midaz/console/mc-accounts Explore how Accounts, Holders, Aliases, Segments, and Portfolios work together in the Midaz Module to organize your financial structure and ownership. The **Accounts** section is where you open the accounts that hold balances, identify who owns them, and group them for reporting and control. Accounts can be linked to a Holder, Segment, and Portfolio. These persisted relationships support ownership, grouping, fee resolution, and scoped rules. You will work with the following here: * **Account**: the record that holds a balance of one asset and can send or receive that asset through transactions (for example, a customer's BRL account). * **Holder**: the individual or entity that owns one or more accounts (for example, a customer or a merchant registered in CRM). * **Alias Account**: an optional CRM Instrument linked to a Holder and an existing ledger Account. It stores banking details. This is different from the account's own **alias** field. The **alias** is a friendly identifier on the account itself. It lets you refer to the account by name instead of by ID (for example, `@treasury_main`). * **Segment**: an optional ledger-scoped grouping for Accounts that can scope fee selection and Tracer limits. * **Portfolio**: a ledger-scoped grouping of Accounts with an optional external `entityId`. It is not a direct Holder relationship. ## Available pages *** > [card] [Manage Accounts](/en/products/midaz/console/managing-accounts) > > Create and configure the accounts that hold and move assets within your ledgers. > [card] [Manage Holders](/en/products/midaz/console/managing-crm-holders) > > Register the individuals or entities that own accounts in your system. > [card] [Manage Alias Accounts](/en/products/midaz/console/managing-crm-alias-accounts) > > Link holders to ledger accounts with banking details. > [card] [Manage Segments](/en/products/midaz/console/managing-segments) > > Organize accounts into logical groupings for reporting and control. > [card] [Manage Portfolios](/en/products/midaz/console/managing-portfolios) > > Group accounts into portfolios for consolidated management. # Foundation elements Source: https://docs.lerian.studio/en/products/midaz/console/mc-foundation Set up the Foundation of the Midaz Module: Organizations, Ledgers, Assets, and Account Types that every downstream Account and transaction depends on. The **Foundation** section is the structure that the rest of Midaz builds on. Set up an Organization, Ledger, and Asset before opening an Account. Define Account Types when your configuration needs them. You can create and update Foundation resources, and delete Organizations, Ledgers, and Assets. You will work with four elements here: * **Organization**: The top-level entity that owns one or more ledgers. Usually represents your company or business unit (for example, *Acme Bank*). * **Ledger**: The isolated book of records where accounts, balances, and transactions live. Use one or more ledgers according to your product and operational needs. * **Asset**: A currency or instrument that accounts can hold and move, identified by a code (for example, `BRL`, `USD`, or `USDC`). Each account holds one asset. * **Account Type**: A registered classification for accounts (for example, `customer`, `treasury`, `fee`, or `revenue`). Registering Account Types is optional, but every account has a type. ## Available pages *** > [card] [Manage Organizations](/en/products/midaz/console/managing-organizations) > > Create and configure the top-level entities that group your ledgers. > [card] [Manage Ledgers](/en/products/midaz/console/managing-ledgers-via-console) > > Set up ledgers to organize and track your financial operations. > [card] [Manage Assets](/en/products/midaz/console/managing-assets) > > Register the currencies and instruments used across your ledgers. > [card] [Manage Account Types](/en/products/midaz/console/managing-account-types) > > Define the categories that classify your accounts within each ledger. # Transaction basics Source: https://docs.lerian.studio/en/products/midaz/console/mc-transactions Use the Midaz Module to record Transactions that move Assets between Accounts with double-entry accounting, N:N support, and a full audit trail. Use **Midaz Module** to manage **Transactions** that record the movement of assets between accounts. They record every financial movement in your system. ## What are Transactions? *** A **Transaction** represents the transfer of assets from one or more source accounts to one or more destination accounts. In Midaz Module, transactions: * **Move assets between accounts** - Record value movements through one or more Operations * **Support multiple sources and destinations** - Handle complex transactions with multiple parties * **Track status** - Midaz stores each transaction as `PENDING`, `APPROVED`, `CANCELED`, or `NOTED`. Only the create response carries `CREATED` * **Maintain audit trail** - Record complete history with timestamps and metadata * **Support accounting controls** - When enabled, Accounting Routes validate configured rules for the Transaction A transaction is immutable. Once Midaz records the movement, you cannot change or delete it. You can still update the transaction description and metadata, or view it at any time. To commit or cancel a pending transaction, use the API. For technical details about transactions in Midaz, refer to the [Transactions documentation](/en/products/midaz/transactions). ## Available pages *** > [card] [Manage Transactions](/en/products/midaz/console/managing-transactions) > > Create Transactions and inspect their details after processing. # Concepts map Source: https://docs.lerian.studio/en/products/midaz/console/midaz-console-concepts-map Understand how Organizations, Ledgers, Assets, Accounts, Routes, and Transactions depend on each other before you start configuring the Midaz Module. The Midaz Module uses a small set of core objects with explicit dependencies. Organization, Ledger, Assets, and Accounts are the core setup. You configure Account Types, CRM records, Portfolios, Segments, and Accounting Routes when the workflow needs them. ## Core hierarchy *** ![Core Midaz Module hierarchy, from Organization and Ledger down through Assets, Accounts, Routes, and Transactions](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/midaz-core-hierarchy.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=5f6cfdcad7c59f335dbac4f8f622b953) ### What each object means *** | Object | What it represents | Why it exists first or later | | - | - | - | | `Organization` | The legal or operational owner of the setup | It is the top-level boundary. Nothing below exists without it. | | `Ledger` | The accounting environment where balances and movements are recorded | It groups the structure that a team will operate day to day. | | `Asset` | The unit of value moved in the ledger, such as `BRL` or `USD` | Accounts and transactions depend on it. | | `Account` | A balance container that can send or receive value | Transactions happen between accounts. | | `Account Type` | A registered classification such as `checking`, `treasury`, or `expense`. Registering one is optional, but every account has a type | Use it when configured account or route rules need it. | | `Portfolio` | A grouping of accounts, often by customer or wallet structure | Useful for reporting and organization, but not a prerequisite for every account. | | `Segment` | A ledger-scoped persisted grouping of accounts, such as by department, region, or tier | Useful when the business needs slicing or policy grouping. | | `Holder` | The person or entity that owns accounts in CRM flows | Needed when account ownership matters operationally. | | `Alias` | A human-readable identifier used to find or refer to an account | Especially important in transaction creation. | | `Accounting Route` | An optional rule set for transaction participants and posting behavior | Midaz applies configured route rules when route validation is enabled. | | `Transaction` | The balance movement recorded in the ledger | It is the output of the whole setup. | ## How a transaction depends on prior setup *** ![How creating a transaction depends on the prior setup of organization, ledger, assets, accounts, and accounting routes](https://mintcdn.com/lerian-49cb71fc/SEOef3JqTInYAAau/images/en/d2/midaz-transaction-dependency.svg?fit=max\&auto=format\&n=SEOef3JqTInYAAau\&q=85\&s=9e9a12efb097f1569985402ec9b9b31c) The required prerequisites depend on the Transaction and Ledger settings. A transaction requires Assets and Accounts. It requires an Accounting Route only when route validation is on. ## Practical reading of the UI *** Use this interpretation when you guide users: • `Foundation` defines where the system lives: Organization, Ledger, Asset, Account Types. • `Accounting` defines optional participation and posting rules: Accounting Routes and Operation Routes. • `Accounts` defines who holds balances and how you classify them: Accounts, Holders, Aliases, Segments, Portfolios. • `Transactions` exercises the configured structure. • `Plugins` extend the model after the core behavior already works. ## When users usually get lost *** > [accordion] Account vs Holder vs Alias > > The Account is the balance container. The Holder is the CRM identity. An Alias Account is an optional CRM Instrument linked to a Holder and an existing Ledger Account. The Account's own `alias` is its human-friendly identifier. > [accordion] Account Type vs Segment vs Portfolio > > Account Type is a registered classification, and registering one is optional. Segment and Portfolio are ledger-scoped persisted groupings of Accounts. They are not merely labels or direct Holder relationships. > [accordion] Accounting Route vs Transaction > > The Route is an optional reusable rule. The Transaction is the individual movement. Midaz checks it against configured route rules only when route validation is on. > [accordion] Why the ledger matters so early > > Almost every object below it is ledger-scoped. Users who treat the ledger as a cosmetic container usually misconfigure accounts and routes later. > [!TIP] > > Pair this page with [Setup path](/en/products/midaz/console/midaz-console-setup-path) when you onboard new users. This page explains the model. Setup path explains the order. # Onboarding Source: https://docs.lerian.studio/en/products/midaz/console/midaz-console-onboarding Follow the Midaz Module guided onboarding to create your first Organization and Ledger in a few minutes, with fields explained at every step. The Midaz Module guides you through a step-by-step onboarding flow. It helps you set up your Organization and create your first Ledger. ## Onboarding process *** The onboarding starts automatically when you have no Organization. This happens when you never created one, or when you deleted all your Organizations. At each step, you see where you are and why the step matters. In a few minutes, your Organization and your first Ledger are ready. You need both to access the full platform. ### Starting the process Click the **Let's go** button on the first-steps window. ## Part 1: Creating your Organization *** The first part of onboarding creates your Organization in three steps. ### Step 1 – Set up your Organization details You enter the key details of your Organization. **Required fields:** * **Legal Name** – Your company's official registered name. * **Document** – A registration number such as a CNPJ or EIN. The step also has a **Trade Name** (DBA) field. > [!WARNING] > > The **Document** is permanent. After you submit it, you cannot change it. You can still edit the Legal Name and Trade Name later in the Organization settings. Click **Next** at the bottom of the screen. ### Step 2 – Add your Organization's address This step adds the registered address of your Organization. **Fields:** * **Address** – Street address (line 1) * **Complement** – Additional address information (optional) * **Country** – Select from the dropdown * **State** – Select from the dropdown, based on country (optional) * **City** – Your city name * **ZIP Code** – Postal code, numbers only > [!TIP] > > You can update your address at any time in the Organization settings. Click **Next** at the bottom of the screen. ### Step 3 – Add a theme (optional) Upload your Organization's **Icon** to personalize the Midaz Module. **Icon format:** * PNG or JPEG file, up to 2 MB * 256x256 px When you submit this step, Midaz creates your Organization and returns a unique `organizationId`. > [!TIP] > > You can skip this step and add the icon later. A confirmation dialog asks if you want to finish without a theme. Click **Finish** to continue. ### Organization created Your Organization is ready. You see a confirmation dialog. Click **Continue** to create your first Ledger. ## Part 2: Creating your first Ledger *** After Midaz creates your Organization, the flow guides you to create your first Ledger. The Ledger is a core part of Midaz. It is where you manage Accounts, balances, and Transactions. Create Assets separately in the Ledger, then use them when you create Accounts. **Required field:** * **Ledger Name** – A unique name for your Ledger. You can also turn on **Validate Account Type** and **Validate Routes** in this step. > [!NOTE] > > You can configure additional metadata later. An alert on the page reminds you of this option. Enter a name for your Ledger. Click **Finish** to complete the setup. ## What's next? *** With onboarding complete, you can configure the rest of the Midaz Module: > [card] [Manage Organizations](/en/products/midaz/console/managing-organizations) > > Edit your Organization settings and create additional Organizations. > [card] [Manage Ledgers](/en/products/midaz/console/managing-ledgers-via-console) > > Configure your Ledger and create new ones. > [card] [Create Assets](/en/products/midaz/console/creating-an-asset) > > Define the currencies and tokens for your Ledger. > [card] [Create Accounts](/en/products/midaz/console/creating-an-account) > > Set up accounts to start managing balances. # Setup path Source: https://docs.lerian.studio/en/products/midaz/console/midaz-console-setup-path Follow the recommended setup order for the Midaz Module so each Console screen has the Organization, Ledger, Assets, and Accounts it depends on. The Midaz Module is easier to configure when you follow the dependency order the product expects. Most user confusion comes from trying to create Accounts, Routes, or Transactions before the structural pieces already exist. ## Recommended order *** **1. Create your Organization** Start with the legal and operational owner of the environment. Use [Midaz Module onboarding](/en/products/midaz/console/midaz-console-onboarding) if this is your first setup. If the organization already exists and you want to add another, go directly to [Creating an Organization](/en/products/midaz/console/creating-an-organization). **2. Create your first Ledger** The Ledger is the workspace that scopes balances, Accounts, and Transactions. Go to [Creating a new Ledger](/en/products/midaz/console/creating-a-new-ledger). **3. Review Ledger settings** Decide whether to enable Accounting Route validation before users start creating Transactions. This setting is optional and defaults to `false`. You can configure these settings while creating the Ledger in [Creating a new Ledger](/en/products/midaz/console/creating-a-new-ledger#ledger-settings), or update them later from [Managing Ledgers](/en/products/midaz/console/managing-ledgers-via-console#ledger-settings). **4. Create Assets** Assets define a unit of value for the Ledger, such as `BRL`, `USD`, or a custom token. Accounts reference an Asset when you create them. Go to [Creating an Asset](/en/products/midaz/console/creating-an-asset). **5. Create Account Types** Define Account Types when your configured Account or Route rules need those classifications. Go to [Creating an Account Type](/en/products/midaz/console/creating-an-account-type). **6. Create Accounts** Accounts hold balances and are the source or destination of transactions. Go to [Creating an Account](/en/products/midaz/console/creating-an-account). **7. Add Portfolios, Segments, Holders, and Aliases when needed** These are persisted support structures. Configure them when your workflow needs ownership context, grouping, fee resolution, or scoped rules. Use: * [Creating a Portfolio](/en/products/midaz/console/creating-a-portfolio) * [Creating a Segment](/en/products/midaz/console/creating-a-segment) * [Creating a Holder](/en/products/midaz/console/crm-creating-a-holder) * [Creating an Alias Account](/en/products/midaz/console/crm-creating-alias-account) **8. Create Accounting Routes** Accounting Routes define optional participant and posting rules. Midaz applies them when route validation is on. Go to [Creating an Accounting Route](/en/products/midaz/console/creating-an-accounting-route). **9. Create Transactions** Create Transactions after the Ledger has an Asset and the required Accounts. You need a matching Accounting Route only when route validation is on. Go to [Creating a Transaction](/en/products/midaz/console/creating-a-transaction). **10. Configure Fees Engine after core setup is stable** Fees Engine is part of Midaz, but it is optional. Enable it under **Settings > Plugins**, then configure its fee packages after the base ledger model is already clear. Go to [Midaz module settings](/en/platform/console/plugin-settings). ## Fast path by goal *** > [card] [I need my first working ledger](/en/products/midaz/console/midaz-console-onboarding) > > Use onboarding, then create at least one Asset and one Account. > [card] [I need to model account structure](/en/products/midaz/console/creating-an-account-type) > > Start with Ledger settings, Account Types, Accounts, and Segments. > [card] [I need to control how money moves](/en/products/midaz/console/creating-an-accounting-route) > > Create the accounts first, then define Accounting Routes and test with a transaction. > [card] [I need to estimate fees](/en/products/midaz/fees/console/managing-fee-calculations) > > Enable Fees Engine under **Settings > Plugins**, then configure it after the core ledger structure is already in place. ## Common sequencing mistakes *** > [accordion] Creating an Account before creating an Asset > > You must link every Account to an Asset. If the Asset does not exist yet, account creation stalls immediately. > [accordion] Enabling Account Type validation before defining Account Types > > The Type field then lists only registered Account Types, so the list is empty. Create the Account Types first or disable validation until they are ready. > [accordion] Designing Accounting Routes before knowing the real accounts > > Users often try to model routes too early. Route rules are easier to define after the treasury, customer, fee, and settlement accounts already exist. > [accordion] Trying to create Transactions before aliases or accounts are ready > > Transaction creation depends on accounts being searchable and structurally valid. If operators cannot identify the source and destination accounts quickly, stop and fix the account model first. > [!NOTE] > > When you document the setup or train a client team, teach this order first. The CRUD pages become much easier once the dependency chain is explicit. # Troubleshooting Source: https://docs.lerian.studio/en/products/midaz/console/midaz-console-troubleshooting Fix common Midaz Module issues in Lerian Console: missing menus, empty dropdowns, blocked transactions, and Ledger validation setting mismatches. Use this page when the Console does not show an option you expected, or when you cannot complete a form. Also use it when a transaction does not behave as you expect. Most issues come from missing prerequisites, or from Ledger settings you enabled before the supporting configuration existed. ## First checks *** Before you troubleshoot a specific screen, confirm these basics: * You selected the correct **Organization** and **Ledger**. * The Ledger already has the required **Assets**. * The Ledger settings match the workflow you want to use. * The required **Account Types**, **Accounts**, and **Accounting Routes** exist before you create transactions. * You use each account alias exactly as registered, including any `@` prefix. > [card] [Setup path](/en/products/midaz/console/midaz-console-setup-path) > > Review the recommended setup order before you change individual screens. ## Common issues *** > [accordion] I cannot see the Account Types menu > > The **Account Types** menu appears when you enable **Validate Account Type** in the current Ledger settings. > > To fix it: > > 1. Open **Foundation > Ledgers**. > > 2. Select **Edit** for the target Ledger. > > 3. Go to the **Settings** tab. > > 4. Enable **Validate Account Type**. > > 5. Return to the sidebar and open **Foundation > Account Types**. > > > [!WARNING] > > > > After you enable this setting, new Accounts must use a valid Account Type. Create the required types before you ask operators to create accounts. > [accordion] I cannot create an Account because the Asset field is empty > > Each Account must link to an existing Asset. If no Asset exists in the selected Ledger, you cannot complete the Account form. > > Create the Asset first in [Creating an Asset](/en/products/midaz/console/creating-an-asset), then return to [Creating an Account](/en/products/midaz/console/creating-an-account). > [accordion] The Account Type dropdown is empty > > This usually means you enabled **Validate Account Type** but created no Account Types for the selected Ledger. > > Create at least one Account Type in [Creating an Account Type](/en/products/midaz/console/creating-an-account-type). If your workflow does not need type validation, disable **Validate Account Type** in Ledger settings. > [accordion] I cannot find an Account when creating a Transaction > > Transaction creation searches accounts by alias. Confirm that: > > * The account exists in the selected Ledger. > * The alias matches the registered alias, including any `@` prefix. > * The account allows the expected direction: source accounts can send, destination accounts can receive. > * The account Asset matches the Asset you selected for the Transaction. > > If the alias is wrong or does not exist, open the account details from [Managing Accounts](/en/products/midaz/console/managing-accounts). > [accordion] My Transaction fails route validation > > The **Validate Routes** setting controls route validation. When you enable it, transactions must match an existing Accounting Route. > > Check that: > > * The Accounting Route exists in the selected Ledger. > * The route has at least one required source and one required destination operation route, or one required bidirectional route. Optional routes do not count. > * Account Type or alias validation matches the accounts used in the transaction. > * The transaction type matches the accounting scenario configured in the route. > * Every required operation route with Direct entries is selected on a leg of its side. The error message names each unused route. > > Start with [Managing Accounting Routes](/en/products/midaz/console/managing-accounting-routes) and then review [Creating an Accounting Route](/en/products/midaz/console/creating-an-accounting-route). > [accordion] The Ledger refuses my Accounting Route > > When the Ledger refuses a save and names an operation route, the wizard returns to that card and shows the refusal on it. Not every refusal names a route. Then read the error message. > [accordion] My Transaction amounts do not balance > > For complex transactions, the total you debit from source accounts must equal the total you credit to destination accounts. > > Review every operation before you send the transaction. To model fees, include the fee account as an additional destination so the total credits match the total debits. > [accordion] I cannot delete an entity > > You cannot delete some entities after downstream records use them. For example, treat an Asset that Accounts use, or an Account that Transactions use, as part of the ledger history. > > Instead, edit optional metadata, disable future use where the Console supports it, or create a replacement entity for new operations. > [accordion] Balances do not look right after a Transaction > > Start from the transaction details page and check: > > * The source and destination accounts. > * The Asset used in the transaction. > * Each debit and credit operation. > * The transaction status: `APPROVED`, `PENDING`, `CANCELED`, or `NOTED` (an annotation with no balance change). A reversal is a separate transaction. The original stays `APPROVED`. > > Then open the account balance and operation history for the accounts involved. ## API references *** When a Console issue needs deeper inspection, use the corresponding API references: > [card] [List Accounts](/en/reference/products/midaz/v2/list-accounts) > > Confirm whether the account exists in the selected Ledger. > [card] [Retrieve an Account](/en/reference/products/midaz/v2/get-account-by-id) > > Inspect account details such as type, asset, and metadata. > [card] [List Transactions](/en/reference/products/midaz/v2/get-all-transactions) > > Review transaction history for a Ledger. > [card] [Retrieve a Transaction](/en/reference/products/midaz/v2/get-transaction) > > Inspect transaction status and operation details. # About Midaz module Source: https://docs.lerian.studio/en/products/midaz/console/midaz-module Use the Midaz Module in Lerian Console to manage Organizations, Ledgers, Accounts, Assets, and Transactions from a single visual interface. **Midaz** is a module inside the [Lerian Console](/en/platform/console/about-lerian-console) that provides a visual interface for managing ledger infrastructure. From a single screen, you create organizations and ledgers, register assets (such as BRL or USD), and open accounts. You define the rules that govern how money moves, and record transactions, all without writing API calls. Use the Midaz Module for day-to-day operations: open an account, run a transaction, or check balances. You can also configure how the ledger validates and posts transactions. > [!NOTE] > > Midaz Console is now part of Lerian Console as the **Midaz Module**. All existing functionality remains available, along with new integrations and platform features. ## Start here first *** Start with these pages if you are new to Midaz. They show what to create and in which order. They also show how the main components work together. > [card] [Setup path](/en/products/midaz/console/midaz-console-setup-path) > > Follow the recommended setup order for Organizations, Ledgers, Assets, Accounts, Routes, and Transactions. > [card] [Midaz Console concepts map](/en/products/midaz/console/midaz-console-concepts-map) > > Learn how Midaz components connect and how they support financial operations. > [card] [Midaz Console troubleshooting](/en/products/midaz/console/midaz-console-troubleshooting) > > Resolve common issues related to configuration, routes, permissions, and transactions. ## What you can do *** From the Midaz Module, you can: * **Manage organizations and ledgers**: Create the operational structure used by your financial environment * **Configure assets**: Define currencies, tokens, and other asset types used across ledgers * **Set up accounts**: Create accounts with account types, portfolios, and segments * **Configure accounting routes**: Define how operations and transactions move assets between accounts * **Monitor transactions**: Track financial movements across organizations and ledgers * **Manage Holders and Alias Accounts**: Use the integrated CRM to register account owners and link them to ledger accounts * **Configure Fees Engine**: Fees Engine is integrated into Midaz, but it is optional. Enable it from the [Settings > Plugins](/en/platform/console/plugin-settings) page before you configure it ## Recommended setup order *** For a new environment, we recommend configuring Midaz in the following order: **1. Create an Organization** Define the top-level structure that groups your ledgers and operations. **2. Create a Ledger** Create the ledger that will store balances, accounts, and transactions. **3. Configure Ledger settings** Adjust operational and accounting settings for the ledger. **4. Create Assets** Define the currencies or asset types that will circulate in the ledger. **5. Configure Account Types** Define how accounts behave within the financial structure. **6. Create Accounts** Create the accounts that will hold balances and participate in transactions. **7. Configure Portfolios and Segments** Organize accounts based on business or operational needs. **8. Create Accounting Routes** Define how transactions move assets between accounts. **9. Create Transactions** Start recording and monitoring financial operations. **10. Configure Fees Engine** Fees Engine is integrated into Midaz, but it is optional. Enable it under **Settings > Plugins**, then configure its fee packages after the core ledger structure is in place. For a more detailed explanation of each step, see [Setup path](/en/products/midaz/console/midaz-console-setup-path). ## Accessing Midaz *** To open Midaz, select the **Midaz Module** from the Lerian Console product launcher (*Figure 1*). ![The Midaz Module card in the Lerian Console product launcher, used to open Midaz](https://mintcdn.com/lerian-49cb71fc/yneNeAhnXdrrmE3_/images/en/console/midaz_button.png?fit=max\&auto=format\&n=yneNeAhnXdrrmE3_\&q=85\&s=237682e7534e9c4fe11cefe3379e2437) Figure 1. The card used to access the Midaz Module. ## Ledger activity *** The Midaz home page shows a **Ledger activity** section for the current Ledger. Select the period at the top of the section: **Last 7 days**, **Last 30 days**, or **Last 90 days**. The default is the last 30 days. The section has three cards and a chart: * **Transactions in period**: the number of transactions in the period, split by status. * **Settled volume**: the settled amount of each asset, with its number of transactions. When an asset has reversals, a line shows their amount. * **Current position**: the available amount of each asset, the number of accounts that hold it, and the amount on hold. The period does not change this card. * **Transactions per Day**: a chart of the number of transactions on each day of the period. With Access Manager, this section needs the read permission on the Midaz dashboard resource. ## Available features *** The sidebar follows the order in which most teams build their environment. You start with **Foundation**, then move to **Accounting**, **Accounts**, **Transactions**, and finally **Settings**, which holds **Plugins** and **Metadata indexes**. > [card] [Foundation](/en/products/midaz/console/mc-foundation) > > Configure Organizations, Ledgers, Assets, and Account Types that support your financial structure. > [card] [Accounting](/en/products/midaz/console/mc-accounting) > > Configure Accounting Routes that control how assets move through the system. > [card] [Accounts](/en/products/midaz/console/mc-accounts) > > Manage Accounts, Holders, Aliases, Segments, and Portfolios. > [card] [Transactions](/en/products/midaz/console/mc-transactions) > > Create and monitor transactions that transfer assets between accounts. > [card] [Plugins](/en/platform/console/mc-console-plugins) > > Manage optional platform plugins available from Lerian Console. ## Migrating from Midaz Console *** If you're currently using the standalone **Midaz Console**, here's what changes when moving to Lerian Console. > [!WARNING] > > Midaz v3.5.0 and later releases do not include the standalone Midaz Console. > > We recommend migrating to Lerian Console to access the latest platform capabilities and integrations. ### Why migrate to Lerian Console? * **Unified platform**: Access Midaz and other Lerian products from a single interface * **New platform features**: Lerian releases new improvements and capabilities only in Lerian Console * **Integrated workflows**: Connect Midaz with plugins and other platform modules * **Simplified navigation**: Work with a consistent operational experience across products ### What stays the same? * All core Midaz capabilities remain available * Existing data and configurations continue to work * Operational workflows remain familiar for current users # Instruments Source: https://docs.lerian.studio/en/products/midaz/crm/alias-accounts Associate Holders with Ledger Accounts and store banking, regulatory, metadata, and related-party information. An **Instrument** is the CRM record that associates a [Holder](/en/products/midaz/crm/holders) with a Ledger Account in Midaz. It stores the `ledgerId` and `accountId` for that association, together with banking details, regulatory fields, metadata, and related parties. Instruments keep CRM context separate from the transactional Ledger. The Ledger remains the balance and movement record. The Instrument holds the context associated with a Holder and its Ledger Account. ## Create an Instrument Create an Instrument in the scope of a Holder. The creation input requires `ledgerId` and `accountId` for the associated Ledger Account. The ledger and the account must exist in the organization. An Account has at most one Instrument that is not deleted. Midaz refuses a second Instrument for the same `accountId` with `409` (`CRM-0013`). To record more people on an Account, add them as related parties. The `bankingDetails` object can contain `branch`, `account`, `type`, `openingDate`, `closingDate`, `iban`, `countryCode`, and `bankId`. Its individual fields are optional. Midaz rejects banking details whose `bankId`, `branch`, and `account` another Instrument in the organization already holds. An Instrument response includes its `id`, `holderId`, `ledgerId`, `accountId`, `document`, `type`, timestamps, and any configured banking, regulatory, metadata, or related-party data. To open the Ledger Account and its Instrument in one call, use `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/holders/{holder_id}/accounts`. The Holder in the path owns the new Account. The body takes the Account fields and, optionally, `bankingDetails`, `regulatoryFields`, and `relatedParties`. When the body has none of these three, Midaz creates only the Account. A `201` response carries `account` and `instrument`. When Midaz creates the Account but cannot write the Instrument, `instrument` is `null` and `instrumentError` carries `status` and `reason`. The Account stays, and you can create its Instrument separately. Send `X-Idempotency` to retry this call safely. A retry with the same key returns the first `201`, a partial one included, with `X-Idempotency-Replayed: true`. After a `5xx` answer, the Account may already exist, so a retry with the same key returns `409` with `0084` until the key expires. `X-TTL` sets that time in seconds (default `300`). ## Regulatory fields and related parties Use `regulatoryFields.participantDocument` to store the participant document when it applies. `regulatoryFields.accountType` accepts `DEPOSIT`, `SAVINGS`, `INVESTMENT`, `OTHER_FINANCIAL_INVESTMENTS`, `NON_RESIDENT`, or `PAYMENT`. An Instrument can include related parties. Each related party requires `document`, `name`, `role`, and `startDate`. The `role` is `PRIMARY_HOLDER`, `LEGAL_REPRESENTATIVE`, or `RESPONSIBLE_PARTY`. The `id` and `endDate` fields are optional, and `endDate` must not be before `startDate`. ## Manage Instruments The Midaz API lets you: * List Instruments for an organization. * Create an Instrument for a Holder. * Retrieve, update, or delete an Instrument in the scope of its Holder. * Delete a related party from an Instrument. Use the [Midaz API reference](/en/reference/products/midaz/v2/list-instruments) for the current request and response schema. ## Next steps > [card] [Holders](/en/products/midaz/crm/holders) > > Learn about the Holder associated with an Instrument. > [card] [Accounts](/en/products/midaz/accounts) > > Learn how Midaz Ledger Accounts hold balances and movements. # Best practices Source: https://docs.lerian.studio/en/products/midaz/crm/crm-best-practices Follow CRM production best practices covering integration flow, encryption key management, metadata safeguards, and safe operational workflows. CRM manages sensitive, identity-related data. These practices help you integrate CRM correctly, protect that data, and run it safely in production. These recommendations complement the [CRM data security](/en/products/midaz/crm/crm-data-security) guide, which covers encryption, hashing, and key management in detail. ## 1. Follow the correct integration flow *** CRM relies on a specific order to create entities. If you skip steps or create entities out of order, you can break integrations and lose data downstream. The expected flow is: 1. **Create the holder**: the individual or the organization. 2. **Link the holder to a Midaz ledger account**: associate the holder with an account that already exists in the ledger. 3. **Make sure both exist** before you start any downstream flow. > [!WARNING] > > Make sure your identifiers are correct before you create or link records. CRM checks that the `ledgerId` and `accountId` of an Instrument exist in the organization. ## 2. Protect your encryption keys *** CRM encrypts and hashes sensitive fields before it stores them. The security of this data depends entirely on how you manage your keys. * **Generate unique keys** for `LCRYPTO_HASH_SECRET_KEY` and `LCRYPTO_ENCRYPT_SECRET_KEY` with `openssl rand -hex 32`. * **Store keys in a secret manager** (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault, or equivalent). Never hardcode them in configuration files, source code, or version control. * **Pass the keys to the deployment from your secret vault.** To configure them on a Midaz deployment, see the [Midaz chart README](https://github.com/LerianStudio/helm/tree/main/charts/midaz). For the full list of protected fields and encryption strategies, see [CRM data security](/en/products/midaz/crm/crm-data-security). ## 3. Never store sensitive data in metadata *** The `metadata` object in CRM entities is **not encrypted**. CRM stores it in plain text for non-sensitive, auxiliary information only. Do not use metadata for: * Personal identification numbers (CPF, SSN, passport) * Financial account details * Contact information (email, phone) * Any data subject to LGPD, GDPR, or similar regulations If you need to store a sensitive attribute that is not in the [protected fields list](/en/products/midaz/crm/crm-data-security#protected-fields), contact your Lerian representative to discuss options. ## 4. Do not expose CRM directly on edge layers *** CRM runs inside the Midaz ledger and exposes an internal API. If you expose it directly through API gateways, load balancers, or frontend applications, you increase your attack surface. Instead: * Route CRM traffic through your **backend services** or an internal API layer. * Use [Access Manager](/en/platform/access-manager) to enforce authentication and authorization if you need fine-grained control. * Restrict network access to the ledger pods with Kubernetes NetworkPolicies or your cloud provider's security groups. ## 5. Use soft delete as the default *** CRM supports both **soft delete** and **hard delete**: * **Soft delete** (default): CRM marks the record with a `deletedAt` timestamp. The record drops out of standard queries but stays in the database for audit and recovery. * **Hard delete** (`hard_delete=true`): CRM removes the record from its database. For most cases, soft delete is the safer choice. It preserves audit trails. Reserve hard delete for cases where regulations demand complete removal (for example, GDPR right-to-erasure requests). > [!NOTE] > > Confirm your retention and legal-hold policy before you run a hard delete. The GDPR right to erasure (Article 17) is not absolute. Where legal, regulatory, audit, or record-keeping obligations require data retention, they can take precedence and restrict erasure. ## 6. Validate data before sending it to CRM *** CRM is a **neutral, persistent data layer**. It does not validate document formats or check KYC compliance. Data integrity is your responsibility. Before you create or update a record: * Validate document formats (CPF, CNPJ, passport numbers) on your application layer. * Sanitize inputs so you do not store malformed or inconsistent data. ## 7. Keep CRM and Midaz versions aligned *** CRM ships inside the Midaz ledger binary, so it shares the Midaz version. Before you upgrade: * Check the [version compatibility table](/en/products/midaz/midaz-version-compatibility) to confirm your target version. * Test the upgrade in a staging environment before you apply it to production. * Back up your MongoDB data and your deployment configuration before any major upgrade. For upgrade procedures, see the [Helm upgrade guide](https://github.com/LerianStudio/helm/tree/main/charts/midaz). ## 8. Monitor database health and performance *** CRM uses MongoDB for data storage. In production: * **Monitor connection pool usage.** Size `MONGO_CRM_MAX_POOL_SIZE` for your traffic patterns and replica count. * **Set up alerts** for MongoDB disk usage, replication lag, and connection saturation. * **Enable backups.** Whether you use the bundled Bitnami MongoDB or an external instance, run automated backups and test them regularly. * **Enable OpenTelemetry** (`ENABLE_TELEMETRY: true`) to collect traces and metrics from CRM. Integrate with your observability stack for end-to-end visibility. ## 9. Review the security recommendations *** CRM handles personal and sensitive data. Beyond CRM-specific practices, make sure your deployment follows the platform-wide [Security recommendations](/en/products/midaz/security-recommendations), which cover: * Network segmentation and Zero Trust Architecture * TLS 1.2+ enforcement for all communications * IAM and RBAC configuration * Incident response planning * Patch management and vulnerability scanning # Core Concepts Source: https://docs.lerian.studio/en/products/midaz/crm/crm-core-concepts-overview Meet the two CRM entities that connect customer identity to Midaz Ledger accounts: Holders that carry identity and Instruments that link them to accounts. The CRM core concepts define the entities that connect real-world identities to your Midaz ledger accounts. They provide the business context that the ledger's transactional layer doesn't manage. ## Content *** Here, you'll find: * [**Holders**](/en/products/midaz/crm/holders): The core entity for an individual (`NATURAL_PERSON`) or an organization (`LEGAL_PERSON`) behind a ledger account. A Holder stores identity attributes such as name, document number, contact details, and addresses. * [**Instruments**](/en/products/midaz/crm/alias-accounts): The link between a Holder and a specific ledger account. Instruments let one Holder associate accounts in different ledgers. Each one keeps banking details and metadata in one place. # CRM data security Source: https://docs.lerian.studio/en/products/midaz/crm/crm-data-security Secure CRM personal data with HTTPS/TLS in transit, field-level encryption and hashing at rest, and controls aligned with GDPR and LGPD requirements. ### Personal data under GDPR and LGPD Every regulation, from GDPR to LGPD, shares one principle: you use personal data only for the purpose the user agreed to. The **CRM** is part of the Midaz ledger. It handles transactional and non-transactional flows, so it must protect the sensitive data these flows carry. Although Lerian doesn't offer cybersecurity services, we follow strict information security practices in all software we ship. ## Security responsibilities *** Lerian does not oversee or enforce our clients' cybersecurity policies. We respect the trust-based relationship each institution has with its end users. We assume that each client follows the LGPD and any other data protection regulation that applies to its region or industry. The split of security work between Lerian and you depends on your deployment model. See the [shared responsibility model](/en/products/midaz/security). Still, Lerian delivers technology that follows strong, market-aligned security practices. These practices protect sensitive CRM data as follows: ### In transit The Midaz ledger serves plain HTTP. Terminate TLS in front of it, at your ingress or service mesh, to protect the data you exchange with the CRM. The CRM encrypts sensitive fields *before* it writes them to the database. This applies to every request that creates or updates a holder or an instrument. ### At rest In BYOC, disk and volume encryption is your responsibility. We strongly recommend it. It adds another layer of protection. ## How we protect data *** The CRM uses different protection methods. The method depends on the type of data and its intended use. * **Encryption** protects values that the system might need to read again, such as names or contact information. * **Hashing** creates a search token for some encrypted fields, such as the Holder `document`, so the CRM can find a record by that value. The field itself stays encrypted. > [!WARNING] > > The CRM writes the protected fields to the database only in encrypted form. ### Encryption and hashing strategies The CRM combines several cryptographic techniques. These techniques protect sensitive data and still support the application. #### Encryption The system must read or show some fields again, such as personal names or emails. The CRM encrypts each of these values with strong, symmetric encryption. Even if someone reads the database directly, the original values stay unreadable without the encryption key. Encryption also adds a random component, so identical values never produce the same encrypted output. #### Hashing The CRM hashes certain fields to allow secure filtering without exposure of the original value. It stores these hashes in a separate internal structure for fast, secure lookups. ### Key management The CRM uses encryption keys and hashing keys, in one of two modes that `KMS_VENDOR` selects. `LCRYPTO_ENCRYPT_SECRET_KEY` and `LCRYPTO_HASH_SECRET_KEY` are required in both modes. When `KMS_VENDOR` is unset or `none`, the CRM encrypts and hashes with these keys. When `KMS_VENDOR` is `hashicorp-vault`, the CRM generates keys for each Organization and wraps them with a HashiCorp Vault Transit key that you operate, and it keeps these two keys to read the data written before. Keep their values unchanged. Never hardcode a key or expose it in source code or version control. With `hashicorp-vault`, the CRM uses the Vault Transit engine mounted at `transit-st`. Each Organization has its own Transit key, named `org-`. Midaz signs in to Vault with AppRole: set `KMS_VAULT_AUTH_METHOD` to `approle`, and set `KMS_VAULT_ROLE_ID` and `KMS_VAULT_SECRET_ID`. Give that AppRole the `create` and `update` capabilities on `transit-st/encrypt/org-*` and `update` on `transit-st/decrypt/org-*`. Midaz creates the Transit key of an Organization on its first encryption. Midaz provisions the CRM keys of an Organization when the Organization first needs them. To provision them in advance, call `POST /v2/organizations/{organization_id}/encryption/provision`. To check them, call `GET /v2/organizations/{organization_id}/encryption/status`. > [!CAUTION] > > Protect your keys with a dedicated secret manager or secure storage. ### Protected fields The CRM protects the fields listed below. You do not need to know how this protection works. Do not enter sensitive data in any field that this list does not include. > [!CAUTION] > > Never store sensitive information in the `metadata` object. #### Holder * `name` * `document` * `contact.primaryEmail` * `contact.secondaryEmail` * `contact.mobilePhone` * `contact.otherPhone` * `naturalPerson.motherName` * `naturalPerson.fatherName` * `naturalPerson.monthlyGrossIncome.value` * `legalPerson.representative.name` * `legalPerson.representative.document` * `legalPerson.representative.email` #### Instrument * `document` * `bankingDetails.account` * `bankingDetails.iban` * `regulatoryFields.participantDocument` * `relatedParties.document` ## Best practices & recommendations *** Data encryption in the CRM adds a strong security layer. Even if an attacker compromises the database, the protected fields stay unreadable in their original form. The CRM decrypts data only with a valid key, or through authenticated and authorized service calls. Key security is therefore critical. If a key leaks, the application cannot protect your data on its own. To keep your environment safe, we strongly recommend: * **Do not expose the Midaz API** directly on edge layers such as gateways or frontend apps. * **Never store sensitive data in metadata fields.** The CRM does not encrypt them. * **Enforce governance** over access to the production environment and related tools. * **Use secure key managers** with strict access controls to safeguard your secrets. * **Encrypt disks or volumes** to protect data at rest. > [!WARNING] > > Data security is a shared responsibility. The CRM gives you the building blocks. Make sure your deployment uses them well. # Getting started with CRM Source: https://docs.lerian.studio/en/products/midaz/crm/crm-getting-started Follow this guide to register Holders in CRM and link them to ledger accounts with Instruments through the Midaz REST API. This guide shows how to create and manage **Holders**, the customers or companies behind your accounts. It also links each holder to a ledger account with an **Instrument**. By the end, you have a holder registered in CRM and linked to a ledger account. ## Prerequisites *** Before you begin, make sure you meet the following requirements: * You completed the [Midaz setup](/en/products/midaz/midaz-setup) guide and all services run. * At least one **Organization**, **Ledger**, and **Account** already exist, as created in the [Midaz Getting Started](/en/products/midaz/midaz-getting-started) guide. * The Midaz ledger serves the holder and instrument endpoints. In Midaz v4, CRM is part of the ledger binary, so it needs no separate service or port. > [!NOTE] > > Replace the placeholder IDs in the examples below with the real IDs from your environment. ## CRM components *** The CRM (Customer Relationship Management) component lets you register the people and companies behind your ledger accounts. It manages two core entities: * **Holders**: Individuals (`NATURAL_PERSON`) or companies (`LEGAL_PERSON`) that own accounts. * **Instruments**: The link between a holder and a specific ledger account, with optional banking details. This model lets one holder own many accounts across different ledgers. It keeps identity and contact information in one place. ## Step 1: Create a holder *** A **Holder** represents a person or company in your system. Create holders for individuals (`NATURAL_PERSON`) or companies (`LEGAL_PERSON`). Send a `POST` request with the holder's type, name, document, contact, and address. For the full request and response schema, see [Create a holder](/en/reference/products/midaz/v2/create-holder). > [accordion] Individual holder example > > ```bash theme={null} > curl -X POST http://localhost:3002/v2/organizations/{organization_id}/holders \ > -H "Content-Type: application/json" \ > -d '{ > "type": "NATURAL_PERSON", > "name": "Jane Smith", > "document": "12345678900", > "contact": { > "primaryEmail": "jane.smith@example.com", > "mobilePhone": "+15551234567" > }, > "addresses": { > "primary": { > "line1": "123 Main Street", > "line2": "Apt 4B", > "city": "New York", > "state": "NY", > "zipCode": "10001", > "country": "US", > "description": "Home address" > } > }, > "naturalPerson": { > "favoriteName": "Jane", > "birthDate": "1990-05-15", > "nationality": "American" > }, > "metadata": { > "segment": "premium", > "source": "onboarding" > } > }' > ``` > [accordion] Company holder example > > To register a company instead of an individual, set the type to `LEGAL_PERSON`: > > ```bash theme={null} > curl -X POST http://localhost:3002/v2/organizations/{organization_id}/holders \ > -H "Content-Type: application/json" \ > -d '{ > "type": "LEGAL_PERSON", > "name": "Acme Corp Ltd", > "document": "12345678000199", > "contact": { > "primaryEmail": "finance@acmecorp.com", > "mobilePhone": "+15559876543" > }, > "legalPerson": { > "tradeName": "Acme Corp", > "activity": "Financial services", > "type": "Limited Liability", > "foundingDate": "2015-03-20", > "size": "Medium", > "status": "Active", > "representative": { > "name": "Bob Johnson", > "document": "98765432100", > "email": "bob@acmecorp.com", > "role": "CFO" > } > } > }' > ``` > [!TIP] > > Save the `id` from the response. You use it when you create instruments. ## Step 2: Link a holder to an account *** Once the holder exists, link it to a ledger account with an **Instrument**. An instrument connects a holder to one account inside a ledger, with optional banking details. For the full request and response schema, see [Create an instrument](/en/reference/products/midaz/v2/create-instrument). > [accordion] Example request > > ```bash theme={null} > curl -X POST http://localhost:3002/v2/organizations/{organization_id}/holders/{holder_id}/instruments \ > -H "Content-Type: application/json" \ > -d '{ > "ledgerId": "{ledger_id}", > "accountId": "{account_id}", > "bankingDetails": { > "branch": "0001", > "account": "123450", > "type": "CACC", > "openingDate": "2025-01-15", > "countryCode": "US", > "bankId": "12345" > }, > "metadata": { > "isPrimary": "true" > } > }' > ``` ## Step 3: Query and update your data *** Once holders and instruments exist, you can retrieve, list, and update them. | Operation | Endpoint | API reference | | - | - | - | | Retrieve a holder | `GET /v2/organizations/{organization_id}/holders/{holder_id}` | [Retrieve a holder](/en/reference/products/midaz/v2/get-holder-by-id) | | List all holders | `GET /v2/organizations/{organization_id}/holders?limit=10&page=1` | [List holders](/en/reference/products/midaz/v2/list-holders) | | List instruments for a holder | `GET /v2/organizations/{organization_id}/instruments?holder_id={holder_id}` | [List instruments](/en/reference/products/midaz/v2/list-instruments) | | Retrieve a specific instrument | `GET /v2/organizations/{organization_id}/holders/{holder_id}/instruments/{instrument_id}` | [Retrieve an instrument](/en/reference/products/midaz/v2/get-instrument-by-id) | | Update a holder | `PATCH /v2/organizations/{organization_id}/holders/{holder_id}` | [Update a holder](/en/reference/products/midaz/v2/update-holder) | > [accordion] Update holder example > > ```bash theme={null} > curl -X PATCH http://localhost:3002/v2/organizations/{organization_id}/holders/{holder_id} \ > -H "Content-Type: application/json" \ > -d '{ > "contact": { > "primaryEmail": "jane.new-email@example.com", > "mobilePhone": "+15559999999" > }, > "metadata": { > "segment": "vip", > "source": "onboarding" > } > }' > ``` ## Step 4: Clean up *** To remove resources, delete instruments first, then holders. Midaz refuses to delete a holder that still has instruments or accounts that carry its ID. | Operation | Endpoint | API reference | | - | - | - | | Delete an instrument | `DELETE /v2/organizations/{organization_id}/holders/{holder_id}/instruments/{instrument_id}` | [Delete an instrument](/en/reference/products/midaz/v2/delete-instrument) | | Delete a holder | `DELETE /v2/organizations/{organization_id}/holders/{holder_id}` | [Delete a holder](/en/reference/products/midaz/v2/delete-holder) | > [accordion] Example requests > > Delete an instrument: > > ```bash theme={null} > curl -X DELETE http://localhost:3002/v2/organizations/{organization_id}/holders/{holder_id}/instruments/{instrument_id} > ``` > > Delete a holder: > > ```bash theme={null} > curl -X DELETE http://localhost:3002/v2/organizations/{organization_id}/holders/{holder_id} > ``` ## Next steps *** > [card] [CRM API reference](/en/reference/products/midaz/v2/create-holder) > > Explore advanced filtering, metadata queries, and all available endpoints. > [card] [Using CRM with Midaz Console](/en/products/midaz/crm/using-crm-with-midaz-console) > > Manage holders through a graphical interface. # CRM migration history Source: https://docs.lerian.studio/en/products/midaz/crm/crm-migration-guide Historical context for moving standalone CRM data to the Midaz v4 Ledger. > [!WARNING] > > This page documents a legacy topology. Do not use it as a deployment guide for Midaz v4. Earlier installations could run CRM separately. Midaz v4 embeds CRM in the Ledger: use Holder and Instrument endpoints only through `/v2/organizations/{organization_id}/...`. The Ledger is the current deployment unit. CRM is not a plugin, standalone service, or separate v4 release. ## What a v4 installation does not use Do not use the standalone CRM service, port `4003`, the `X-Organization-Id` header, or the legacy CRM v1 alias endpoints in a v4 installation. Fees in Midaz v4 runs in the Ledger and is available only on `/v2`. If you retire an older standalone CRM deployment, retain its MongoDB backup and release values. Then reconcile Holder and Instrument records through the Ledger `/v2` API before you decommission the old workload. Preserve that release record. To move the CRM routes and permissions of an integration to `/v2`, see [Migrate from API v1 to API v2](/en/products/midaz/migrating-to-api-v2). See [CRM getting started](/en/products/midaz/crm/crm-getting-started) and the [Midaz chart README](https://github.com/LerianStudio/helm/tree/main/charts/midaz). # What is CRM? Source: https://docs.lerian.studio/en/products/midaz/crm/crm-overview The optional CRM layer adds customer identity, contact details, and business context to Midaz Ledger accounts, outside the ledger. CRM is not part of the ledger's transactional domain. It adds business attributes to ledger accounts. CRM is where user metadata lives. It does not hold balances, transfers, or fees. It records who is behind an account and what you need to run your business. ## Current API *** CRM is served by the Ledger only on `/v2`, under `/v2/organizations/{organization_id}/...`. `/v1` does not expose CRM. Use the `midaz` authorization namespace with the `holders` and `instruments` resources. > [!TIP] > > **Test CRM locally** > > You can run CRM locally, without Kubernetes, with the Midaz stack from [Getting started](/en/products/midaz/midaz-getting-started). ## Why use the CRM? *** Midaz ledger accounts are generic by design. They are transaction-first and domain-agnostic. CRM adds meaning to those accounts and links each one to a user profile and a business context. You do not have to use CRM. You can adopt it later, only when your use case needs customer or business metadata beyond the ledger. ### Example use cases * **Banking (individuals and businesses)**: CRM stores identifiers like CPF or CNPJ, an address, contact details, or account numbers. Midaz runs the same transaction logic for both customer types. * **Supply chains (supplier, factory, retailer)**: CRM tracks metadata like supplier IDs, warehouse locations, or contract details. This data does not belong in the transaction, but it drives business decisions. > [!TIP] > > CRM ships inside the Midaz ledger, so there is no separate service to deploy. Use it only if your product or regulatory context needs customer or business metadata. ## Entities *** CRM has two core entities: * **[Holder](/en/products/midaz/crm/holders)** – The main entity in CRM. It represents the persona for a Midaz ledger account. It stores identity attributes and individual traits. * **[Instrument](/en/products/midaz/crm/alias-accounts)** – The business context for a [Ledger Account](/en/products/midaz/accounts) in **Midaz Ledger**. It holds financial details such as bank account information. *Figure 1* shows how the CRM entities connect to Midaz. ![How CRM entities, the Holder and the Instrument, connect to accounts in the Midaz ledger](https://mintcdn.com/lerian-49cb71fc/svQbQMf9Iz90q0Cc/images/en/d2/entities-new.svg?fit=max\&auto=format\&n=svQbQMf9Iz90q0Cc\&q=85\&s=87a301718533b124568d374140b17cea) Figure 1. How CRM entities connect to Midaz ## Design principles *** CRM focuses on: * **Separation of concerns**: It keeps user profile data out of transaction logic. * **Simpler deployment**: CRM ships inside the ledger binary, with no separate service to run. * **Clear domain boundaries**: It evolves with Midaz without coupling to ledger internals. > [!CAUTION] > > CRM does not validate compliance processes such as KYC. It is a neutral, persistent data layer. ## API behavior *** CRM runs inside the Midaz ledger binary. It exposes a registry API for non-transactional data linked to Midaz accounts. * It does not enforce validations such as user status, risk profile, or document verification. * It is agnostic to the asset or grouping logic used in Midaz accounts. * It gives consistent access to holder metadata without loading the transaction layer. ## Security & compliance *** In BYOC, you run Midaz and its components in your own infrastructure. You keep control of your infrastructure, compliance policies, and user-data lifecycle. CRM ships with Midaz and follows the same security standards as the rest of the platform: * **Data in transit**: Midaz serves plain HTTP, so terminate TLS at your ingress or service mesh. * **Data at rest**: Midaz encrypts the protected CRM fields before it stores them. > [!CAUTION] > > You own encryption key management. Use a secret-management service to store and control access to keys. You define and enforce your own policies for LGPD, GDPR, and other regional data-protection rules. CRM provides the structure. Review the [Security recommendations](/en/products/midaz/security-recommendations) before you deploy any component into your environment. Apply security best practices to every component: **Access Manager**, **Fees Engine**, **Pix**, and **CRM**. Secure network boundaries, manage secrets, apply patches, and enforce strict access control. ## Data deletion strategies *** CRM gives you full control over how it removes data. It offers two options: * **Soft delete** (default): CRM flags the record as deleted but keeps it in the database. Use it to keep an audit trail or to recover data later. * **Hard delete**: Where your policy permits removal, CRM removes the record from its database. Your policies define the behavior. ## Access control *** To restrict who can access your CRM data, enable our [Access Manager](/en/platform/access-manager). ### Enabling Access Manager First, install **Access Manager**. Then open the Midaz ledger `.env` file and set these environment variables: ```text Text theme={null} ## AUTH PLUGIN_AUTH_HOST=http://plugin-auth:4000 PLUGIN_AUTH_ENABLED=true ``` After you enable it, CRM enforces access permissions from your authentication setup. > [!TIP] > > To evaluate Access Manager, [contact our team](https://lerian.studio/contact). > [!TIP] > > See [Getting started with CRM](/en/products/midaz/crm/crm-getting-started) for a step-by-step guide. ## Next steps *** > [card] [Core concepts](/en/products/midaz/crm/crm-core-concepts-overview) > > Understand the key entities managed by CRM: Holders and Instruments. > [card] [Explore the CRM API](/en/reference/products/midaz/v2/create-holder) > > Browse endpoints for holders, instruments, and related parties. > [card] [Using CRM](/en/products/midaz/crm/crm-using-overview) > > Learn how to register holders and link them to ledger accounts. # Using CRM Source: https://docs.lerian.studio/en/products/midaz/crm/crm-using-overview Manage Holders and Instruments in CRM day to day through the REST API or the Midaz Module of Lerian Console. This section covers CRM configuration and day-to-day operations through the REST API or the Midaz Module of Lerian Console. ## Content *** Here, you'll find: * [**Using CRM**](/en/products/midaz/crm/crm-getting-started): Manage Holders and Instruments through the REST API. * [**CRM in Lerian Console**](/en/products/midaz/crm/using-crm-with-midaz-console): Manage Holders and Instruments in the Midaz Module of Lerian Console. # Holders Source: https://docs.lerian.studio/en/products/midaz/crm/holders Model the individuals or organizations behind Midaz accounts as Holders, storing names, documents, contacts, and compliance details as Natural or Legal Person. A **Holder** is the core entity in CRM. It represents a real-world individual or organization behind a Midaz ledger account. A Holder stores identity attributes such as the name, document number, contact details, and addresses. [CRM](/en/products/midaz/crm/crm-overview) manages Holders. Holders do not belong to the ledger's transactional domain. They enrich ledger accounts with business data. Each Holder is one of two types: **Natural Person** (individual) or **Legal Person** (company/organization). > [!TIP] > > To create and manage holders step by step, see [Getting started with CRM](/en/products/midaz/crm/crm-getting-started). ## Holder types *** You choose the type at creation. You cannot change it later. ### Natural Person The Natural Person type represents an individual customer. It supports personal attributes such as the name, gender, birth date, civil status, nationality, and family information. Use this type for: * Individual bank account holders * Personal wallet owners * Freelancers or sole proprietors ### Legal Person The Legal Person type represents a company or organization. It supports business attributes such as the trade name, activity type, founding date, company size, and legal representative details. Use this type for: * Corporate treasury accounts * Business partners and suppliers * Institutional clients > [!TIP] > > Choose the holder type carefully at creation. You cannot change it later. To use a different type, create a new Holder. ## Holder fields *** ### Core fields | Field | Type | Required | Description | | :- | :- | :- | :- | | **id** | `uuid` | System-generated | Unique identifier of the Holder. | | **type** | `enum` | Yes | `NATURAL_PERSON` or `LEGAL_PERSON`. | | **name** | `string` | Yes | Full name of the individual or legal name of the company. | | **document** | `string` | Yes | Identification document number (e.g., CPF, CNPJ, passport). | | **externalId** | `string` | No | Optional identifier to map the Holder to an external system. | | **metadata** | `object` | No | Key-value pairs for custom, non-sensitive data. Keys are limited to 100 characters and values to 2000 characters. | | **createdAt** | `datetime` | System-generated | Timestamp of creation (RFC 3339). | | **updatedAt** | `datetime` | System-generated | Timestamp of last update (RFC 3339). | | **deletedAt** | `datetime` | System-generated | Timestamp of soft deletion, if applicable (RFC 3339). | ### Address fields The `addresses` object supports up to three addresses: `primary`, `additional1`, and `additional2`. Each address contains: | Field | Type | Required | Description | | :- | :- | :- | :- | | **line1** | `string` | No | Primary address line (street, number). Max 256 characters. | | **line2** | `string` | No | Secondary address line (apartment, suite). Max 256 characters. | | **zipCode** | `string` | No | Postal or ZIP code. Max 20 characters. | | **city** | `string` | No | City name. Max 100 characters. | | **state** | `string` | No | State or province code. Max 100 characters. | | **country** | `string` | No | ISO 3166-1 alpha-2 country code (e.g., `US`, `BR`). | | **description** | `string` | No | A descriptive label for the address (for example, Home, Office, or Billing). Max 100 characters. | ### Contact fields | Field | Type | Required | Description | | :- | :- | :- | :- | | **primaryEmail** | `string` | No | Primary email address. | | **secondaryEmail** | `string` | No | Secondary email address. | | **mobilePhone** | `string` | No | Mobile phone number with country code (e.g., `+5511999999999`). | | **otherPhone** | `string` | No | Alternative phone number. | ### Natural Person fields | Field | Type | Required | Description | | :- | :- | :- | :- | | **favoriteName** | `string` | No | Preferred name or nickname. | | **socialName** | `string` | No | Social name (name the person identifies with). | | **gender** | `string` | No | Gender identity. | | **birthDate** | `string` | No | Date of birth in `YYYY-MM-DD` format. | | **civilStatus** | `string` | No | Marital status (e.g., Single, Married, Divorced). | | **nationality** | `string` | No | Nationality (e.g., Brazilian, American). | | **motherName** | `string` | No | Mother's full name. | | **fatherName** | `string` | No | Father's full name. | | **monthlyGrossIncome** | `object` | No | Monthly gross income, with `value`, `currency`, and `referenceDate`. All three are required inside the object. | | **status** | `string` | No | Lifecycle status (e.g., `Active`, `Inactive`, `Suspended`, `Closed`). | ### Legal Person fields | Field | Type | Required | Description | | :- | :- | :- | :- | | **tradeName** | `string` | No | Trade or doing-business-as name. | | **activity** | `string` | No | Primary business activity. | | **type** | `string` | No | Legal structure (e.g., LLC, Corporation). | | **foundingDate** | `string` | No | Date the company was founded in `YYYY-MM-DD` format. | | **size** | `string` | No | Company size classification (e.g., Small, Medium, Large). | | **annualGrossRevenue** | `object` | No | Annual gross revenue, with `value`, `currency`, and `referenceDate`. All three are required inside the object. | | **totalAssets** | `object` | No | Total assets, with `value`, `currency`, and `referenceDate`. All three are required inside the object. | | **status** | `string` | No | Lifecycle status (e.g., `Active`, `Inactive`, `Suspended`, `Closed`). | #### Representative The `representative` object within `legalPerson` stores the details of the company's legal representative: | Field | Type | Required | Description | | :- | :- | :- | :- | | **name** | `string` | No | Full name of the legal representative. | | **document** | `string` | No | Document number of the representative. | | **email** | `string` | No | Email address of the representative. | | **role** | `string` | No | Role within the company (e.g., CEO, CFO). | ## Data security *** Midaz encrypts several Holder fields at rest, including the `name`, the `document`, and the contact fields. This protects the data even if someone gains access to the storage. > [!WARNING] > > Never store sensitive information in the `metadata` object. Midaz does not encrypt metadata and stores it in plain text. For the full list of protected fields and encryption strategies, see [CRM data security](/en/products/midaz/crm/crm-data-security). ## Managing Holders *** ### Via API Use the CRM API to manage Holders programmatically: * [Create a Holder](/en/reference/products/midaz/v2/create-holder): Register a new Holder in the system. * [List Holders](/en/reference/products/midaz/v2/list-holders): View all Holders with pagination and filters. * [Retrieve a Holder](/en/reference/products/midaz/v2/get-holder-by-id): Get the details of a specific Holder. * [Update a Holder](/en/reference/products/midaz/v2/update-holder): Edit an existing Holder's data. * [Delete a Holder](/en/reference/products/midaz/v2/delete-holder): Soft-delete or permanently remove a Holder. Midaz refuses while the Holder still has Instruments or accounts that carry its ID. > [!NOTE] > > Every CRM API request includes the organization ID in the URL path, for example `/organizations/{organization_id}/holders`. If you enable [Access Manager](/en/platform/access-manager), add an `Authorization` header with a Bearer token. ### Via Lerian Console You can manage Holders through the **Holders** page in the Midaz Module of [Lerian Console](/en/platform/console/about-lerian-console). The console lets you create, view, edit, and delete Holders without code. [**Learn more in the Managing Holders guide.**](/en/products/midaz/console/managing-crm-holders) ## Next steps *** > [card] [Instruments](/en/products/midaz/crm/alias-accounts) > > Learn how Instruments link Holders to Midaz ledger accounts. > [card] [Using CRM](/en/products/midaz/crm/crm-using-overview) > > Follow the step-by-step guide to register Holders and create Instruments. # CRM in Lerian Console Source: https://docs.lerian.studio/en/products/midaz/crm/using-crm-with-midaz-console Manage CRM Holders and Alias Accounts visually inside the Midaz Module of Lerian Console, without writing API calls. The **CRM** interface is part of the **Midaz Module** in [Lerian Console](/en/platform/console/about-lerian-console). Use it to manage core entities such as Holders and Alias Accounts. ## Accessing CRM features *** CRM features are in the **Midaz Module** of Lerian Console. To open them: 1. Open **Lerian Console** and go to the **Midaz Module** 2. In the left-side menu, find the CRM entities in the **Accounts** section: * **Holders** - Manage individuals and companies * **Alias** - Link holders to ledger accounts on the **Alias Accounts** page ### Available actions From the Midaz Module, you can: > [card] [Manage Holders](/en/products/midaz/console/managing-crm-holders) > > Create and manage individuals or companies associated with your accounts > [card] [Manage Alias Accounts](/en/products/midaz/console/managing-crm-alias-accounts) > > Link holders to Midaz ledger accounts with business context # Database migrations Source: https://docs.lerian.studio/en/products/midaz/database-migrations Run Midaz Ledger and Tracer PostgreSQL schema migrations with dedicated runner images so applications boot against an already-migrated database. Midaz applies PostgreSQL schema migrations through dedicated migration-runner images (one for the Ledger, one for Tracer), decoupled from the application binaries. The apps do not migrate at startup. They boot against a schema that the runner has already migrated. ## Why a dedicated runner *** The dedicated runner has these properties: * Migrations run once, as a separate step. * The app image does not bundle migration SQL and does not change the schema. * The runner image runs under a hardened security context (see [Security posture](#security-posture)). ## Runner images *** Each release ships two images: | Image | Applies | Databases | | - | - | - | | `midaz-ledger-migrations` | Ledger onboarding + transaction migrations | Two: `onboarding`, `transaction` | | `midaz-tracer-migrations` | Tracer schema | One | Both images share the same shape: * Base: `alpine`, with the [`migrate`](https://github.com/golang-migrate/migrate) CLI copied from a pinned `migrate/migrate` image. * Runs as `USER 65532:65532` (non-root, UID-agnostic). * POSIX shell entrypoint that assembles a DSN from environment variables, runs `migrate ... up`, and exits. * Writes nothing to disk. Postgres tracks migration progress in the `schema_migrations` table, so `readOnlyRootFilesystem: true` is safe. The Ledger runner applies onboarding first, then transaction, in a single invocation. The Tracer runner applies its single database in one pass. ## Environment contract *** Each entrypoint accepts either a prebuilt URL override or the individual `DB_*` variables. The URL override takes precedence when set. ### Ledger runner | Database | URL override | Assembled from | | - | - | - | | onboarding | `ONBOARDING_DATABASE_URL` | `DB_ONBOARDING_HOST`, `DB_ONBOARDING_PORT` (default `5432`), `DB_ONBOARDING_USER`, `DB_ONBOARDING_PASSWORD`, `DB_ONBOARDING_NAME`, `DB_ONBOARDING_SSLMODE` (default `disable`) | | transaction | `TRANSACTION_DATABASE_URL` | `DB_TRANSACTION_*` (same shape) | ### Tracer runner | URL override | Assembled from | | - | - | | `DATABASE_URL` | `DB_HOST`, `DB_PORT` (default `5432`), `DB_USER`, `DB_PASSWORD`, `DB_NAME`, `DB_SSL_MODE` (default `disable`) | ### DSN shape When the entrypoint assembles the DSN from `DB_*` variables, it produces: ```text theme={null} postgres://:@:/?sslmode= ``` The password is percent-encoded so URI-reserved characters (`% @ : / ? # & + space [ ]`) do not break the DSN. `%` is encoded first so already-inserted escapes are not double-encoded. The entrypoint prints phase markers (`applying onboarding migrations`, `applying transaction migrations`, `applying tracer migrations`, `migrations complete`). ## Run the Ledger runner manually *** The Helm chart runs the runner for you. To run it by hand, point it at your databases via `DB_*` (or `*_DATABASE_URL`) and run it once before the ledger starts: ```bash theme={null} docker run --rm \ -e DB_ONBOARDING_HOST="postgres.example.com" \ -e DB_ONBOARDING_PORT=5432 \ -e DB_ONBOARDING_USER=midaz \ -e DB_ONBOARDING_PASSWORD="change-me" \ -e DB_ONBOARDING_NAME=onboarding \ -e DB_ONBOARDING_SSLMODE=disable \ -e DB_TRANSACTION_HOST="postgres.example.com" \ -e DB_TRANSACTION_PORT=5432 \ -e DB_TRANSACTION_USER=midaz \ -e DB_TRANSACTION_PASSWORD="change-me" \ -e DB_TRANSACTION_NAME=transaction \ -e DB_TRANSACTION_SSLMODE=disable \ lerianstudio/midaz-ledger-migrations:4.4.1 ``` The runner exits `0` on success (including the idempotent no-op case) and non-zero on failure. ## Kubernetes deployment *** In production, run each migration runner as a Kubernetes Job (typically an Argo CD PreSync Job or a Helm hook) that completes before the app rollout. The Helm chart wires this up for you. The sections below cover the properties that matter if you author your own manifests. > [!NOTE] > > The runner migrates the databases pointed at by its environment, once. ### Security posture The runner works under a hardened pod security context: * **Non-root**: the image sets `USER 65532:65532`. * **UID-agnostic**: migration files are root-owned and world-readable, so any UID can read them. * **`readOnlyRootFilesystem`-safe**: `migrate` writes no filesystem state. The same image runs cleanly under `runAsNonRoot: true`, `readOnlyRootFilesystem: true`, and `capabilities: drop [ALL]`. ### TLS The entrypoints honor `sslmode` from the environment (`DB_ONBOARDING_SSLMODE`, `DB_TRANSACTION_SSLMODE`, or `DB_SSL_MODE`), defaulting to `disable`. Production deployments should set `require` (or stricter). The shell runner does not reproduce the in-code TLS enforcement, error classification, or telemetry that the apps use for their own connections. You control TLS for migrations through `sslmode` alone, in exchange for a minimal, dependency-free runner. ## Conventions and idempotency *** * **Paired up/down**: every migration has a `.up.sql` and a `.down.sql` file. * **Idempotent**: running `migrate up` when the schema is already at the latest version is a no-op. Re-running the runner after a partial or complete apply is safe. * **Pinned CLI**: the runner images use a pinned `golang-migrate` version. ## Upgrading from earlier versions *** To adopt the new model: 1. Pull the release that ships the runner images. 2. In Kubernetes, add the `midaz-ledger-migrations` and `midaz-tracer-migrations` Jobs to your deploy pipeline so they run before the app rollout. If you use the official Helm chart, this is done for you. ## Related pages *** * [Installing Midaz](/en/products/midaz/midaz-setup): the Midaz images and Helm chart. * [Updating Midaz](/en/products/midaz/updating-midaz): upgrade rules. * [Deployment strategies](/en/products/midaz/deployment): BYOC deployment overview. * [Tracer environment variables](/en/products/tracer/tracer-environment-variables): full Tracer configuration reference. # Deployment strategies Source: https://docs.lerian.studio/en/products/midaz/deployment Choose the right deployment strategy for Midaz under BYOC: Kubernetes with Helm, Terraform foundations, and infrastructure prerequisites. This section covers deployment strategies for running Midaz in your own infrastructure under the **BYOC (Bring Your Own Cloud)** model. If you're using the **SaaS** model, Lerian manages deployment for you. Skip ahead to [Getting started](/en/start-here/getting-started) to begin configuring your platform. > [!NOTE] > > Not sure which model fits? See [Deployment models](/en/start-here/evaluate-and-deploy/deployment-models) for a full comparison of SaaS and BYOC. Set up your environment, meet the prerequisites, and follow our best practices. > [!TIP] > > Before you deploy, check out the [Midaz Architecture Overview](/en/products/midaz/architecture). ### Content * [Midaz Terraform Foundation](/en/products/midaz/midaz-terraform-foundation): Ready-made Terraform examples for provisioning the cloud infrastructure Midaz runs on (AWS, GCP, or Azure). To install, configure, and upgrade Midaz with its chart, see the [Midaz chart README](https://github.com/LerianStudio/helm/tree/main/charts/midaz). ## Deployment strategies *** Under BYOC, you manage the infrastructure. We strongly recommend using Kubernetes with our Helm Charts. This approach simplifies deployment and scaling. You can choose the deployment strategy that fits your needs. ### Deploying with Kubernetes We recommend our official Helm Charts. They install Midaz in a Kubernetes environment. You can either plug Midaz into your existing databases and services or use the default components provided in the Helm chart. This setup adapts to different infrastructure needs. For the step-by-step installation, see the [Midaz chart README](https://github.com/LerianStudio/helm/tree/main/charts/midaz). ### Self-managed deployment If you prefer full control, you can deploy Midaz manually. Midaz ships as public container images on Docker Hub. You can run them on your own infrastructure, with a different orchestrator or directly on virtual machines or bare metal. For instructions, check the [Installing Midaz](/en/products/midaz/midaz-setup) page. ## Platform requirements *** If you bring your own infrastructure components, make sure you meet the minimum supported versions: | Service | Minimum Supported Version | Notes | | :- | :- | :- | | PostgreSQL | 17 | Primary database | | MongoDB | 8.x | Document storage | | RabbitMQ | 4.x | Message broker | | Valkey | 8.x | Live balances (Redis fork) | Midaz needs these minimum versions for a stable, performant platform. ## Best practices *** ### Access to the infrastructure * Use least privilege policies when connecting to databases. * Block direct access to databases by default. Only allow it in exceptional cases with approval. * Store secrets securely using tools like HashiCorp Vault. * Use dedicated tools for safe access to production data. ### Redundancy and high availability * Enable replication and backups for both Midaz and your databases. * Use load balancers to route traffic across services evenly. ### Network security * Run your services inside VPCs to isolate critical components. * Use NAT gateways or proxies for outbound connections. * Apply security groups or firewall rules to restrict access to required ports and IPs. ### Data persistence and storage * Use replicated databases to support high availability and recovery. * Choose scalable storage solutions that match your data growth. * Use Valkey (Redis fork), which holds the live balances. ### Observability * Integrate tools that monitor logs, traces, and metrics. * Midaz supports observability through OpenTelemetry. ## Shared responsibilities *** Under the BYOC model, Lerian and your team share responsibility for running Midaz. For a detailed breakdown of who secures what (including how responsibilities differ between BYOC and SaaS), see the [Security](/en/products/midaz/security) page. > [!TIP] > > For guidance on securing your environment before deployment, check the [Security Recommendations](/en/products/midaz/security-recommendations) documentation. # Account plans Source: https://docs.lerian.studio/en/products/midaz/fees/account-plans Assign a fee plan to an account, with a free quota per fee and calendar month, and charge its service fees. An **account plan** is a set of fees that you assign to an account. Each fee has a free quota: a number of units in each calendar month that cost nothing. An account plan has two kinds of fees: * **Transaction fees** apply to the `/v2` transactions that the account sends. * **Service fees** apply when you charge a service to the account, for example a paper statement. You charge them with a [fee charge](#service-fees-and-fee-charges). You create account plans and assign them through the API or in [Lerian Console](/en/products/midaz/fees/console/managing-account-plans). Each account has at most one active account plan. ## Account plans and fee packages *** An account plan and a [fee package](/en/products/midaz/fees/fees-engine-overview#fee-packages) are different entities. * An account with an active account plan pays the fees of its plan on the `/v2` transactions it sends. On those transactions, a fee package never charges that account, also when no fee of the plan matches. Then the account pays no fee. * A fee package does not charge the fee legs that an account plan adds. | | Fee packages | Account plans | | - | - | - | | **Selects** | Transactions, by route, segment, metadata, and amount | The accounts that you assign to the plan | | **Free quota** | No | Yes, per fee and calendar month | | **Service fees** | No | Yes, through fee charges | | **Deductible fees** | Yes (`isDeductibleFrom`) | No | | **Deferrable fees** | Yes (`deferrable`) | No | | **Rounding** | Yes (`rounding`) | No | ## Create an account plan *** Create a plan with [Create an account plan](/en/reference/products/midaz/v2/create-an-account-plan). The plan has these fields: * `label`: the name of the plan. Two plans of a ledger that are not deleted cannot have the same label (`0543`). * `description`: optional. * `enable`: `true` lets you assign the plan to accounts. * `timezone`: the IANA timezone that the plan counts its months in. The default is `America/Sao_Paulo`. * `fees`: at least one fee, by fee key. A fee key starts with a lowercase letter, followed by ASCII letters and digits only (`^[a-z][a-zA-Z0-9]*$`). Each fee has these fields: * `feeLabel`: the name of the fee. * `trigger`: what makes the fee apply. See [Triggers](#triggers). * `calculationModel`: `flatFee`, `percentual`, or `maxBetweenTypes`, as in a [fee package](/en/products/midaz/fees/fee-engine-calculation#fee-calculation-rules). A service fee accepts only `flatFee` (`0555`). * `creditAccount`: the alias of the ledger account that receives the fee. Midaz checks that the account exists when you create or update the plan. * `accounting`: the `transactionRoute`, `operationRouteFrom`, and `operationRouteTo` of the fee. See [Accounting routes](#accounting-routes). * `freeQuota`: the number of free units per month. The default is `0`. * `period`: only `monthly`, the default. * `referenceAmount`: only `originalAmount`, the default. ### Triggers A trigger with `type: transaction` takes these fields: * `direction`: required. The only value is `sent`: the fee applies to the account that sends the transaction. * `schemes`: the transaction schemes that the fee matches, for example `TED` or `PIX`. * `metadata`: optional pairs that the transaction metadata must all carry. A pair matches only a string metadata value that is equal to it. A trigger with `type: service` takes only `serviceCode`, for example `PAPER_STATEMENT`. Midaz stores schemes and service codes trimmed and in upper case. Each one has 1 to 50 letters, digits, underscores, or hyphens. One code cannot be the scheme of a fee and the service code of another fee of the plan (`0558`). ### Accounting routes The rules depend on whether the ledger validates accounting routes (`accounting.validateRoutes` in the [ledger settings](/en/products/midaz/ledgers)): | Rule | Ledger without route validation | Ledger with route validation | | - | - | - | | Transaction fee | Lists at least one scheme (`0556`). | A fee without schemes matches every scheme of its transaction route. | | `accounting` | Optional. | Required on every fee, with a `transactionRoute` (`0547`) that exists (`0105`) and both operation routes (`0557`). | | Operation routes | Not checked. | Both are linked to the transaction route of the fee. On a transaction fee, both are optional links (`optionalOperationRoutes`) (`0557`). | Two transaction fees of a plan with the same `metadata` cannot select the same transactions (`0544`). On a ledger without route validation, they cannot share a scheme. On a ledger with route validation, they cannot share a transaction route and a scheme, and a fee without schemes takes every scheme of its route. Two service fees cannot share a service code (`0544`). If you turn on route validation after you create a plan, give every fee a transaction route and both operation routes first. A fee without a transaction route refuses each transaction that it would match with `0547`, and each fee charge that names it. ## Versions *** The fees of a plan live in versions. A version never changes. * The create makes version 1, in effect from the instant of the create. * An [update](/en/reference/products/midaz/v2/update-an-account-plan) that sends `fees` makes a new version with the full resulting set of fees. * `effectiveFrom` sets the instant that the new version applies from, in RFC 3339. The default is the instant of the request. It cannot be before the `effectiveFrom` of the latest version (`0553`). Send it only with `fees`. * `label`, `description`, `enable`, and `timezone` change the plan, not a version. In the `fees` of an update: * An entry with the key of a stored fee changes the fields it sends and keeps the others. `trigger`, `calculationModel`, and `accounting` change as a whole. * An empty entry (`{}`) deletes that fee. * An entry with a new key adds a fee, with every required field. * The new version starts from the fees of the latest version. It keeps at least one fee. When two updates create a version of the same plan at the same time, one of them gets `0559` and creates no version. Read the plan again and send the update again. [Get an account plan](/en/reference/products/midaz/v2/get-an-account-plan) returns the version in effect at the instant of the request. `currentVersion` is the highest version created, which can start later. [List the versions of an account plan](/en/reference/products/midaz/v2/list-the-versions-of-an-account-plan) returns every version. ## Assign a plan to an account *** [Assign an account plan to an account](/en/reference/products/midaz/v2/assign-an-account-plan-to-an-account) sends the `accountPlanId` of the plan. * The plan must belong to the ledger, exist, and be enabled (`0545`). * If the account has an active assignment of another plan, it ends at the instant that the new assignment starts, in one step. * If the account already has the same plan, Midaz returns the active assignment and changes nothing. * When another assignment of the same account runs at the same time, Midaz can answer `0560` and change nothing. Send the request again. [Get the account plan assignment of an account](/en/reference/products/midaz/v2/get-the-account-plan-assignment-of-an-account) returns the active assignment, or `null`, and the history of the account. [List the accounts assigned to an account plan](/en/reference/products/midaz/v2/list-the-accounts-assigned-to-an-account-plan) returns the active assignments of a plan. [End the account plan assignment of an account](/en/reference/products/midaz/v2/end-the-account-plan-assignment-of-an-account) ends the active assignment. The fee packages then apply to the account again. An account without an active assignment answers `0554`. ### Disable or delete a plan * A disabled plan (`enable: false`) cannot be assigned. It keeps charging the accounts that it already has. * Midaz refuses to delete a plan that is assigned to an account (`0546`). End its assignments first. * When you delete an account, Midaz ends its active assignment. The history of the account stays readable. ## How a plan charges a transaction *** Midaz applies account plans to these `/v2` transactions: direct, hold, block, unblock, and each item of a batch. A `/v1` transaction, an annotation, a revert, and a transaction that skips fees with `skip.fees` do not use account plans. Midaz takes one decision for each source account of the transaction that has an active plan, except `@external` accounts. It takes one decision per account, also when the account sends from several balances. ### Matching The fees of the version in effect are matched against the transaction: * On a ledger without route validation, a transaction fee matches when its `schemes` contain the `scheme` of the transaction. A transaction without `scheme` matches no fee. * On a ledger with route validation, a transaction fee matches when its `transactionRoute` is the `routeId` of the transaction and its `schemes` are empty or contain the `scheme` of the transaction. * In both cases, the transaction metadata must carry every `metadata` pair of the fee. * When several fees match, the fee with the most `metadata` pairs applies. When two or more fees have that number of pairs, Midaz refuses the transaction with `0548`. ### Outcome The decision has one of these outcomes: | Outcome | What happens | | - | - | | `quota` | A fee matched, and the unit is inside the free quota. The account pays no fee. | | `charged` | A fee matched, and the unit is past the free quota. Midaz adds the fee on top of what the account sends and credits it to `creditAccount`. | | `no_match` | No fee matched. The account pays no fee, and no unit is counted. | Midaz calculates a charged fee on the amount that the account sends in the transaction. On a ledger with route validation, the fee legs use the operation routes of the fee. The create response has `accountPlanFees`, with one item for each account that has an active plan: `accountId`, `accountAlias`, `accountPlanId`, `accountPlanVersion`, `feeKey`, `outcome`, `unit`, `freeQuota`, and `amount`. Only the create responses return it. Reads, commits, cancels, and reverts do not. The transaction metadata keys `packageAppliedID`, `feeApplied`, and `feeExemption` describe fee packages only. ### Holds, cancels, and reverts * A hold counts the unit when you create it. The commit counts nothing. * A cancel or a revert gives the unit back only in the same month of the plan. The revert also reverses the fee legs. ## Free quota *** A unit is one decision with the outcome `quota` or `charged`, or one service code of a fee charge with the same outcomes. * Midaz counts units per account, fee key, and calendar month in the plan timezone. * The count belongs to the account and the fee key, not to the plan. An account that moves to another plan with the same fee key keeps its count for the month. * A transaction fee counts each scheme separately. On a ledger with route validation, a fee without schemes has one count for every scheme of its route. A service fee has one count. * When you change a fee, its count stays. A fee with a new key starts at zero. * The month is the month in which Midaz processes the transaction, not its `transactionDate`. ## Service fees and fee charges *** [Charge service fees to an account](/en/reference/products/midaz/v2/charge-service-fees-to-an-account) sends `serviceCodes`, with 1 to 100 codes, and an optional `description` and `metadata`. The request needs the `X-Idempotency` header (`0552`). Each code in the list is one unit. Its outcome is one of these: * `quota`: the unit is inside the free quota of its fee. It costs nothing. * `charged`: the unit is past the free quota. It costs the flat amount of the fee. * `not_covered`: the plan of the account has no service fee for the code, or the account has no active plan. It costs nothing and counts no unit. Midaz refuses the request before it charges anything when: * No account plan of the ledger has a service fee for a code (`0549`). * A code belongs only to transaction fees (`0550`). * On a ledger with route validation, the fees of the codes have different transaction routes (`0551`), or a fee has no transaction route (`0547`). Midaz posts the charged units as one fee transaction in the asset of the account. It debits the account and credits the `creditAccount` of each fee. On a ledger with route validation, the transaction uses the transaction route and the operation routes of the fees. The `description` and `metadata` of the charge go to the fee transaction. No fee package, account plan, or Tracer validation applies to the fee transaction. When Midaz refuses the fee transaction, for example for insufficient funds, it refuses the charge with the same error and counts no unit. A charge without a charged unit has no fee transaction, and its `feeTransactionIds` is empty. Nothing undoes that charge, and its units stay counted. * A retry with the same key and the same body returns the recorded charge with the `X-Idempotency-Replayed` header. A different body with the same key answers `0084`. Keys are unique per account. * To undo a charge, revert its fee transaction. A revert in the same month gives back every unit of the charge. * The fee transaction has no reference to its charge. `feeTransactionIds` on the charge links them. [List the fee charges of an account](/en/reference/products/midaz/v2/list-the-fee-charges-of-an-account) returns the newest charge first, and `period` (`YYYY-MM`) filters it. [Get a fee charge of an account](/en/reference/products/midaz/v2/get-a-fee-charge-of-an-account) returns one charge. ## Usage *** [Get the account plan usage of an account](/en/reference/products/midaz/v2/get-the-account-plan-usage-of-an-account) returns the units of the account in one month. `period` (`YYYY-MM`, in the plan timezone) selects the month. The default is the current month. A future or malformed `period` answers `0082`, and an account without an active plan answers `0554`. The response has one item for each count of each fee: `feeKey`, `trigger`, `period`, `freeQuota`, `used`, `remaining`, and `charged`. `trigger` is a key for the count: read `feeKey` instead of parsing it. `remaining` is never negative. The usage lists the fees and free quotas of the version in effect now, also for a past month. For reconciliation, use the `accountPlanFees` of the create responses and the fee charges. ## Estimates and events *** * A [fee estimate](/en/reference/products/midaz/v2/estimate-fee-calculation) prices the fee package that you name. It does not read account plan assignments. * The `fee_charge.applied` event covers fee packages only. An account plan fee or a fee charge does not emit it. ## Permissions *** The routes use these Midaz permission resources: | Resource | Action | Use | | - | - | - | | `account-plans` | `get` | Read plans, versions, assigned accounts, assignments, and usage. | | `account-plans` | `post` | Create a plan. | | `account-plans` | `patch` | Update a plan. | | `account-plans` | `put` | Assign a plan to an account. | | `account-plans` | `delete` | Delete a plan, or end the assignment of an account. | | `fee-charges` | `get` | Read fee charges. | | `fee-charges` | `post` | Charge service fees. | The Access Manager seed gives these permissions to the Midaz roles. The viewer role holds both `get` permissions. The contributor role holds `get`, `post`, `put`, and `patch` on `account-plans`, and `get` and `post` on `fee-charges`. The editor role holds the same permissions and also `delete` on `account-plans`. ## Next steps *** > [card] [Using account plans](/en/products/midaz/fees/using-account-plans) > > Create a plan, assign it, and charge fees step by step. > [card] [Midaz error list](/en/reference/products/midaz/error-list) > > See the codes from `0543` to `0560`. # Fees Engine billing package examples Source: https://docs.lerian.studio/en/products/midaz/fees/billing-package-examples Walk through end-to-end billing package examples for boleto tiered pricing, volume discounts, and account maintenance charges with full JSON configuration. > [!TIP] > > This page is business-oriented. It focuses on *what* each billing model solves and *how* to configure it. For field-level details, see the [Billing Packages overview](/en/products/midaz/fees/fees-engine-overview#billing-packages) and the [API reference](/en/reference/products/midaz/v2/create-billing-package). ## Volume billing: boleto issuance with tiered pricing *** ### The business need A fintech offers boleto issuance to its business clients. Pricing is volume-based: the more boletos a client issues each month, the lower the unit cost. The first 50 boletos each month are free. Clients that issue 1,000 or more boletos receive an extra 5% discount. At 3,000 boletos or more, the discount increases to 10%. ### Pricing structure | Range | Unit price | | - | - | | 1–500 | R\$ 1.20 | | 501–2,000 | R\$ 0.80 | | 2,001+ | R\$ 0.45 | ### Package configuration ```json theme={null} POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages Body: { "label": "Boleto Issuance — Tiered", "description": "Monthly volume billing for boleto issuance with progressive tiers", "type": "volume", "enable": true, "eventFilter": { "transactionRoute": "boleto-issuance", "status": "APPROVED" }, "pricingModel": "tiered", "tiers": [ { "minQuantity": 1, "maxQuantity": 500, "unitPrice": "1.20" }, { "minQuantity": 501, "maxQuantity": 2000, "unitPrice": "0.80" }, { "minQuantity": 2001, "unitPrice": "0.45" } ], "freeQuota": 50, "discountTiers": [ { "minQuantity": 1000, "discountPercentage": "5.00" }, { "minQuantity": 3000, "discountPercentage": "10.00" } ], "countMode": "perRoute", "assetCode": "BRL", "debitAccountAlias": "client-operating", "creditAccountAlias": "fees-boleto-revenue" } ``` ### How the calculation works At month-end, the orchestrator calls `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing/calculate` with the billing period. The engine counts approved boleto transactions on the route, subtracts the free quota, applies tiered pricing, and applies the matching discount. Tiered pricing is **volume pricing**: the engine picks the single tier the billable count lands in and charges every billable unit at that tier's price. It does not bill each tier's slice separately. **Example result** for a client that issued 1,800 boletos in March: | Step | Detail | Amount | | - | - | - | | Total issued | 1,800 boletos | — | | Free quota | 50 exempt | — | | Billable | 1,750 boletos | — | | Matching tier | 501–2,000 → R\$ 0.80 | — | | Gross | 1,750 × R\$ 0.80 | R\$ 1,400.00 | | Discount | 5% (total count ≥ 1,000) | −R\$ 70.00 | | **Net total** | — | **R\$ 1,330.00** | The engine returns a transaction payload that debits `client-operating` by R\$ 1,330.00 and credits `fees-boleto-revenue`. ## Maintenance billing: monthly account fee (*PF*) *** ### The business need A digital bank charges a fixed monthly maintenance fee for active personal (PF) accounts. The fee is R\$ 9.90 per account. The engine keeps only accounts whose status code is `active` and excludes every other status. You do not filter them by hand. Midaz organizes accounts by segment. A PF segment groups all personal accounts. ### Package configuration ```json theme={null} POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages Body: { "label": "PF Account Maintenance", "description": "Monthly maintenance fee for active personal accounts", "type": "maintenance", "enable": true, "feeAmount": "9.90", "assetCode": "BRL", "maintenanceCreditAccount": "fees-maintenance-pf", "accountTarget": { "segmentId": "0198e5f4-7b2a-7c3d-9e1f-2a3b4c5d6e7f" } } ``` ### How the calculation works The engine resolves all accounts in the PF segment and filters for active status. It generates one N:1 transaction: it debits R\$ 9.90 from each active account and sends the full total to `fees-maintenance-pf`. **Example result** for 8,000 active PF accounts: | Detail | Value | | :- | :- | | Active accounts | 8,000 | | Fee per account | R\$ 9.90 | | Transaction entries (source) | 8,000 debit entries | | Transaction entries (destination) | 1 credit entry | | **Total revenue** | **R\$ 79,200.00** | ## Volume billing: fixed-price Pix *** ### The business need A fintech charges R\$ 0.10 per Pix sent (flat rate, no tiers). ### Package configuration ```json theme={null} POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages Body: { "label": "Pix Send — Standard", "description": "Flat-rate billing per Pix sent", "type": "volume", "enable": true, "eventFilter": { "transactionRoute": "pix-send", "status": "APPROVED" }, "pricingModel": "fixed", "tiers": [ { "minQuantity": 1, "unitPrice": "0.10" } ], "freeQuota": 0, "countMode": "perRoute", "assetCode": "BRL", "debitAccountAlias": "client-wallet", "creditAccountAlias": "fees-pix-revenue" } ``` ### How the calculation works **Example result** for 5,000 Pix transactions: | Detail | Value | | :- | :- | | Total Pix sent | 5,000 | | Unit price | R\$ 0.10 | | **Total** | **R\$ 500.00** | ## Maintenance billing: PJ portfolios with different rates *** ### The business need A financial institution manages multiple business (PJ) account portfolios: PME (small and medium enterprises) and Corporate. Each portfolio has a different monthly maintenance fee. The institution wants to calculate both in a single billing run. ### Package configuration **PME portfolio (R\$ 29.90/month):** ```json theme={null} POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages Body: { "label": "PJ Maintenance — PME", "description": "Monthly maintenance for PME business accounts", "type": "maintenance", "enable": true, "feeAmount": "29.90", "assetCode": "BRL", "maintenanceCreditAccount": "fees-maintenance-pj", "accountTarget": { "portfolioId": "0198e5f4-8c1d-7a2b-9f3e-4d5c6b7a8e9f" } } ``` **Corporate portfolio (R\$ 89.90/month):** ```json theme={null} POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages Body: { "label": "PJ Maintenance — Corporate", "description": "Monthly maintenance for Corporate business accounts", "type": "maintenance", "enable": true, "feeAmount": "89.90", "assetCode": "BRL", "maintenanceCreditAccount": "fees-maintenance-pj", "accountTarget": { "portfolioId": "0198e5f4-9d2e-7b3c-8a4f-5e6d7c8b9a0e" } } ``` ### How the calculation works A single call to `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing/calculate` with `"type": "maintenance"` processes both packages. The response includes one result per package and a consolidated summary. **Example result** for 500 PME accounts + 50 Corporate accounts: | Portfolio | Active accounts | Fee | Total | | - | - | - | - | | PME | 500 | R\$ 29.90 | R\$ 14,950.00 | | Corporate | 50 | R\$ 89.90 | R\$ 4,495.00 | | **Consolidated** | **550** | — | **R\$ 19,445.00** | Both results credit the same `fees-maintenance-pj` account, so revenue stays consolidated. The orchestrator sends each transaction payload to Midaz independently. ## Next steps *** > [card] [Create a billing package](/en/reference/products/midaz/v2/create-billing-package) > > API reference for creating volume and maintenance billing packages. > [card] [Calculate billing](/en/reference/products/midaz/v2/calculate-billing) > > Trigger billing calculations for a period and retrieve transaction payloads. > [card] [Billing calculations](/en/products/midaz/fees/fee-engine-calculation#billing-calculations) > > Detailed mechanics of tiered pricing, free quotas, and maintenance billing. > [card] [Best practices](/en/products/midaz/fees/fees-engine-best-practices) > > Operational guidance for billing packages in production. # Connect the Fees Engine to Midaz Source: https://docs.lerian.studio/en/products/midaz/fees/connecting-fees-to-midaz Configure the embedded Fees Engine with the Midaz ledger. Fees runs inside the unified Midaz ledger process. Configure it in the ledger deployment. It is neither a separate service nor a plugin. ## Configuration *** Configure its MongoDB storage with `MONGO_FEES_*` settings in the Midaz deployment. Each fee request must provide `send.asset`. Midaz rejects an empty value instead of using a fallback currency. See [Midaz environment variables](/en/products/midaz/midaz-environment-variables) for ledger configuration. ## See it in Lerian *** * The full integration journey across the pieces: [Building a complete core banking](/en/products/building-a-complete-core-banking) * What the Fees Engine does: [What is Fees Engine?](/en/products/midaz/fees/fees-engine-overview) * Deploy the stack: [Helm charts](https://github.com/LerianStudio/helm) # Creating a Fee Package Source: https://docs.lerian.studio/en/products/midaz/fees/console/fe-creating-a-package Build a new Fee Package in the Midaz Module by configuring basic info, amount ranges, flat or percentage fee rules, waivers, and priorities from the Console UI. A Fee Package groups fee rules and defines when they apply to Transactions. ## Before you start *** * Enable the **Fees Engine** in [Midaz module settings](/en/platform/console/plugin-settings). * You need an existing Ledger and at least one Account that can receive fee amounts. * If the package should apply only to a specific route or segment, create those records first. ## Create the Fee Package *** **Step 1** Go to the **Fee Packages** page and click the **New Package** button. **Step 2** The **New Fee Package** form will open with multiple sections to configure. > [!TIP] > > Check the field guide for more information about the fields in the form. **Step 1** Fill in the **Basic Information** section **Step 2** Set **Minimum Amount** and **Maximum Amount** in the same section. > [!NOTE] > > Transactions outside this range will not have fees applied from this package. **Step 3** Click the **Next** button. **Step 4** Select one of the options in the **Add Fee** section: * **Flat Fee** - Fixed amount regardless of transaction value. * **Percentage Fee** - Percentage of the transaction amount. * **Max between types** - Higher value between flat and percentage. **Step 5** Add Fee information. **Step 6** (Optional) You can add another fee rule if needed. To do so, select a new fee type and fill the information. **Step 7** Click the **Next** button. **Step 8** (Optional) Configure **Account Waivers** section: * Add account aliases that should be exempt from fees in this package * Click **Add** to add each waived account **Step 9** Click the **Next** button. **Step 10** Review the information and confirm that everything is correct. **Step 11** Click the **Create Package** button. If successful, the Console shows a confirmation message and opens the Fee Packages list. ## Field guide *** ### Basic Information | Field | Description | Example | | - | - | - | | Fee Package Name | Required package name. Use a name that describes the charge model. | `Standard Transfer Fee` | | Description | An explanation of when and why the package applies. | `Fixed fee for standard transfers` | | Transaction Route | Optional route filter for the package. | `Pix Transfer Route` | | Segment | Optional segment filter for targeted fees. | `Retail Customers` | | Minimum Amount | Lowest transaction amount eligible for the package. | `10.00` | | Maximum Amount | Highest transaction amount eligible for the package. | `500.00` | | Rounding | Optional. **None** keeps the exact calculated amount. **Round down** and **Round half up** round every fee that the package charges. When you select a mode, set **Decimal places to keep** from `0` to `18`. It starts at `2`. | `Round down`, `2` | | Metadata selector | Optional metadata pairs. The package applies only to transactions whose metadata carries every pair with the same text value. You cannot change the pairs after you create the package. To price a TED or Pix by a label, see [fee context](/en/products/midaz/fees/using-fee-engine#price-a-ted-or-pix-by-a-fee-context). | `feeContext` = `ted_salario` | ### Fee Rules Every fee inside a package has a **Priority** (1 = applied first). The fee with priority `1` must use **Original Amount** as Reference Amount. #### Flat Fee A fixed amount applied to the Transaction regardless of its value. | Field | Description | Example | | - | - | - | | Amount | The fixed amount charged for this fee. Must be a positive number. | `5.00` | | Fee Name | Unique identifier for this fee, used as the JSON object key. **Must start with a lowercase letter** and contain only letters and numbers. | `taxaAdm` | | Reference Amount | Base used by the calculation: **Original Amount** (transaction value as sent) or **After Fees Amount** (value after previous fees in the package). | `Original Amount` | | Credit Account ID | Alias of the account that receives the fee amount. | `@fees_transfers` | | Route From | Optional. The source operation route of this fee, chosen from the routes of the transaction route. | `payments_in` | | Route To | Optional. The destination operation route of this fee, chosen from the routes of the transaction route. | `fees_revenue` | | Deductible from transaction? | When enabled, the fee is deducted from the transaction amount (recipient pays); when disabled, the fee is added on top (sender pays). A deductible flat amount cannot be greater than the package **Minimum Amount**. | Off | | Deferrable | When enabled, the share of this fee that the payer cannot cover can become a [fee debt](/en/products/midaz/fees/fee-debt). Disabled while **Deductible from transaction?** is enabled. | Off | > [!NOTE] > > When you enable **Deductible from transaction?**, the form forces **Reference Amount** to **Original Amount** and disables the **After Fees Amount** option. #### Percentage Fee A percentage of the Transaction amount. | Field | Description | Example | | - | - | - | | Percentage | Percentage rate applied to the reference amount. Must be greater than `0` and less than or equal to `100`. | `2.5` | | Fee Name | Unique identifier for this fee, used as the JSON object key. Must start with a lowercase letter and contain only letters and numbers. | `processingFee` | | Reference Amount | **Original Amount** to charge on the transaction value as sent, or **After Fees Amount** to charge on the value after previous fees in the package. | `Original Amount` | | Credit Account ID | Alias of the account that receives the fee amount. | `@fees_revenue` | | Route From | Optional. The source operation route of this fee, chosen from the routes of the transaction route. | `payments_in` | | Route To | Optional. The destination operation route of this fee, chosen from the routes of the transaction route. | `fees_revenue` | | Deductible from transaction? | Enable so the fee is deducted from the transaction amount; disable to add the fee on top of the transaction. | Off | | Deferrable | When enabled, the share of this fee that the payer cannot cover can become a [fee debt](/en/products/midaz/fees/fee-debt). Disabled while **Deductible from transaction?** is enabled. | Off | #### Max Between Types Calculates a flat amount **and** a percentage, then applies the highest result. The form requires both calculations. | Field | Description | Example | | - | - | - | | Flat Fee (Calculations) | First calculation row. Fixed amount candidate. Must be a positive number. | `1.00` | | Percentage Fee (Calculations) | Second calculation row. Percentage candidate; must be greater than `0` and less than or equal to `100`. | `2.0` | | Fee Name | Unique identifier for this fee, used as the JSON object key. Must start with a lowercase letter and contain only letters and numbers. | `guaranteeFee` | | Reference Amount | Base used to calculate the percentage candidate before the comparison. | `Original Amount` | | Credit Account | Alias of the account that receives the resulting (highest) fee amount. | `@fees_guarantee` | | Route From | Optional. The source operation route of this fee, chosen from the routes of the transaction route. | `payments_in` | | Route To | Optional. The destination operation route of this fee, chosen from the routes of the transaction route. | `fees_revenue` | | Deductible from transaction? | When enabled, the higher of the two results is deducted from the transaction amount; when disabled, it is added on top. A deductible flat amount cannot be greater than the package **Minimum Amount**. | Off | | Deferrable | When enabled, the share of this fee that the payer cannot cover can become a [fee debt](/en/products/midaz/fees/fee-debt). Disabled while **Deductible from transaction?** is enabled. | Off | ### Account Waivers | Field | Description | Example | | - | - | - | | Account Alias | The alias of the account that will be waived. | `@customer_john_checking` | ## Priority, ranges and waived accounts *** ### Fee priority ordering When a package contains multiple fees, Midaz applies them in priority order (lowest number first). With **After Fees Amount** as the reference, earlier fees affect the calculation base for later fees. **Example**: * Fee A (Priority 1): 1% on original amount, not deductible * Fee B (Priority 2): 0.5% on after fees amount On a \$100 transaction: * Fee A = \$1.00 (1% of \$100) * Fee B = \$0.505 (0.5% of \$101) ### Amount range considerations * Midaz rejects a package whose range overlaps another package with the same transaction route, segment and metadata selector * Use `0.01` as minimum for packages that should apply to all transactions * Use a high maximum (e.g., `999999999.99`) for no upper limit * The range includes Transactions exactly at the min or max values ### Waived accounts behavior * A waived account bypasses all fees in the package, not just specific fees * Use account aliases (not IDs) when adding waived accounts * When every source account is waived, the package charges no fee. Otherwise, the fee is split among the accounts that the waiver does not cover: sources for a fee added on top, destinations for a deductible fee. ## What to do next *** The Console creates the Fee Package enabled, so Midaz can apply it to the Transactions it matches as soon as you create it. Run a test calculation in [Running a Fee Estimation](/en/products/midaz/fees/console/fe-fee-simulation) right away, and disable the package on the Fee Packages page if a result is wrong. > [card] API equivalent > > [Create Package endpoint](/en/reference/products/midaz/v2/create-package) # Deleting a Fee Package Source: https://docs.lerian.studio/en/products/midaz/fees/console/fe-deleting-a-package Delete a Fee Package from the Midaz Module when it is no longer needed, keeping in mind data retention, audit, and compliance rules for regulated deployments. > [!CAUTION] > > If you only need to stop a package temporarily, disable it instead of deleting it. A deleted Fee Package no longer appears in active listings. Your deployment's data retention and compliance policies still apply to the record. In regulated environments, your deployment can keep the record for audit, regulatory, or reporting purposes. ## Delete a package **Step 1** On the **Fee Packages** page, click the three dots () in the **Actions** column for the package you want to delete. **Step 2** Select **Delete**. **Step 3** Review the confirmation dialog. **Step 4** Click **Confirm** to finalize the deletion. # Editing a Fee Package Source: https://docs.lerian.studio/en/products/midaz/fees/console/fe-editing-a-package Edit a saved Fee Package in the Midaz Console to adjust its name, amount range, fee rules, or waived accounts without recalculating fees already applied to past Transactions. Edit a Fee Package to change its name, amount range, fee rules, or waived accounts. You cannot change its metadata selector. You can add or change its rounding, but you cannot remove a rounding that the package already stores. Your changes apply to new fee calculations. Midaz does not recalculate fees already applied to past Transactions. ## Edit a package **Step 1** On the **Fee Packages** page, find the package you want to edit. **Step 2** Click the three dots () in the **Actions** column and select **Edit**. **Step 3** The creation wizard opens with the current values. **Step 4** Make your changes and click **Save**. **Step 5** A confirmation toast appears and the updated package returns to the list. # Running a Fee Estimation Source: https://docs.lerian.studio/en/products/midaz/fees/console/fe-fee-simulation Run a fee estimation with the Console Fee Calculator to preview charges on sample amounts, accounts, and assets before creating any real Ledger Transaction. Use the **Fee Calculator** in the Midaz Module to estimate fees before you process a real Transaction. The Fee Calculator is read-only. It does not create a Transaction or change any Ledger balance. ## Before you start *** * Enable the **Fees Engine** in [Midaz module settings](/en/platform/console/plugin-settings). * You need at least one [Fee Package](/en/products/midaz/fees/console/fe-creating-a-package) saved. * You need the source and destination Account aliases you want to test against. ## Running an estimation *** **Step 1** In the Midaz Module sidebar, expand **Fees Engine** and click **Calculator**. **Step 2** Fill in the estimated transaction. See the [Field guide](#field-guide) below for each input. **Step 3** Click **Calculate Fees** to run the estimation. **Step 4** Review the results displayed below the form. ## Field guide *** | Field | What to enter | Example | | - | - | - | | Transaction Amount | Total value to estimate fees against. | `100.00` | | Asset | One of the assets of the current ledger. Select it in the list. | `BRL` | | Fee Package | Fee Package to test. | `Standard Transfer Fee` | | From Account | Account alias that would be debited. | `@customer_123` | | To Account | Account alias that would be credited. | `@merchant_456` | | Description | Optional description for the estimation. | `Pix transfer test` | > [!NOTE] > > The Fee Calculator is a read-only tool. It does not affect the ledger or create any transactions. You can run as many estimations as needed safely. ## Understanding the results *** After you run an estimation, the Fee Calculator shows a detailed breakdown of the calculation: ### Totals * **Payer paid** - The amount the source sends, including fees added on top * **Total fees** - The sum of all fees for the transaction * **Recipient received** - **Payer paid** minus **Total fees** ### Fee breakdown For each fee rule applied, you'll see: | Field | Description | | - | - | | **Fee Label** | Name identifying the fee | | **Source Pays** or **Destination Pays** | Who pays the fee. The source pays a fee added on top. The destination pays a deductible fee. | | **Calculation Type** | **Flat**, **Percentage**, or **Max Between** | | **Calculated Amount** | The actual fee value | ## Estimation examples *** > [accordion] Simple flat fee estimation > > **Scenario**: Test a \$2.00 flat fee on a \$100 transfer > > **Input**: > > * Fee Package: `Standard Transfer Fee` > * Asset: `USD` > * Amount: `100.00` > * Source: `@customer_checking` > * Destination: `@merchant_revenue` > > **Expected Result**: > > * Total fees: \$2.00 > * Recipient received: \$98.00 if the fee is deductible. If it is not deductible, Payer paid is \$102.00 and Recipient received is \$100.00. > [accordion] Percentage fee estimation > > **Scenario**: Test a 1.5% fee on a \$500 transfer > > **Input**: > > * Fee Package: `Percentage Transaction Fee` > * Asset: `USD` > * Amount: `500.00` > * Source: `@customer_savings` > * Destination: `@vendor_payments` > > **Expected Result**: > > * Total fees: \$7.50 (1.5% of \$500) > * Calculation: 500 × 0.015 = 7.50 > [accordion] Combined fee estimation > > **Scenario**: Test max(flat, percentage) fee on different amounts > > **Test 1** - Small transaction (\$30): > > * Flat: \$1.00 > * Percentage: 2% = \$0.60 > * Result: \$1.00 (flat is higher) > > **Test 2** - Large transaction (\$200): > > * Flat: \$1.00 > * Percentage: 2% = \$4.00 > * Result: \$4.00 (percentage is higher) > [accordion] Multiple fees estimation > > **Scenario**: Package with two fees applied in priority order > > **Fee A** (Priority 1): 1% on original amount, not deductible > **Fee B** (Priority 2): 0.5% on after fees amount > > **Input**: \$1000 transaction > > **Expected Result**: > > * Fee A: \$10.00 (1% of \$1000) > * Fee B: \$5.05 (0.5% of \$1010) > * Total fees: \$15.05 ## Use cases for fee estimation *** ### Validate new fee packages Right after you create a fee package, run estimations at various transaction amounts. Make sure the fees are correct across the full amount range. ### Test edge cases Estimate transactions at minimum and maximum amount boundaries to verify fee behavior at the limits of your configured ranges. ### Compare fee structures Run the same transaction through different fee packages to compare outcomes and choose the best structure for your use case. ### Document expected fees Use estimation results to create documentation for your finance team or customers about expected fee amounts. ### Debug fee issues If a transaction shows unexpected fees, use the Fee Calculator to reproduce the scenario and understand the calculation breakdown. ## Best practices *** * **Test full amount ranges** - Do not test only one amount. Estimate transactions at the minimum, the maximum, and several points in between. * **Verify priority ordering** - When packages have multiple fees, confirm they apply in the expected order. * **Check waived accounts** - Test with accounts that the fee package waives. Confirm the results exclude them from fees. * **Document your tests** - Keep a record of estimation results for audit and compliance purposes. * **Share with stakeholders** - Use estimation breakdowns to align with finance teams on expected fee outcomes before going live. ## What to do next *** After validating the fee result, adjust the Fee Package if needed in [Editing a Fee Package](/en/products/midaz/fees/console/fe-editing-a-package), or create a real Transaction in [Creating a Transaction](/en/products/midaz/console/creating-a-transaction). > [card] API equivalent > > [Estimate Fees endpoint](/en/reference/products/midaz/v2/estimate-fee-calculation) # Fees Engine in Lerian Console Source: https://docs.lerian.studio/en/products/midaz/fees/console/fees-engine-overview Explore the Fees Engine in the Midaz Module: enable it, manage Fee Packages, and estimate charges from the Console using Ledgers, segments, and routes. The **Fees Engine** is an optional capability of the Midaz Module that lets operators model transaction fees from the Console. Once enabled, it adds six pages to the Midaz Module sidebar: * **Fee Packages**: create and edit packages and their rules. * [**Account plans**](/en/products/midaz/fees/console/managing-account-plans): create plans and publish new versions, and assign a plan to an account. * **Calculator**: estimate what a package would charge before you apply it to a real Transaction. * [**Billing Packages**](/en/products/midaz/fees/console/managing-billing-packages): create maintenance billing packages, and edit volume and maintenance packages. * **Billing Runs**: preview the billing for a period. * [**Fee Debts**](/en/products/midaz/fees/console/fee-debts): list the [fee debts](/en/products/midaz/fees/fee-debt) of the ledger and collect open debt. The Fees Engine builds on the same Ledgers, Segments, Transaction Routes, and Accounts already defined in Midaz Core. Packages use that existing structure to set their scope. Midaz applies a package automatically to each Transaction that matches its conditions. ## Key concepts *** * **Fee Package**: Container that groups one or more fee rules and the conditions under which they apply (transaction route, segment, ledger, metadata selector, amount range). * **Fee Rule**: An individual fee inside a package, with its own calculation method. * **Application Rule**: How Midaz calculates a single fee, either **flat**, **percentage**, or **maximum between both**. * **Reference Amount**: Whether a percentage fee applies to the original Transaction amount or to the amount after other fees. * **Priority**: The order in which Midaz applies multiple fees inside the same package. * **Waiver**: An account that a package exempts. When every source is waived, the package charges nothing. Otherwise the fee is split among the accounts that the waiver does not cover: sources for a fee added on top, destinations for a deductible fee. ## Enabling the Fees Engine *** The Fees Engine appears in the sidebar only after you enable it in [Plugin settings](/en/platform/console/plugin-settings). **1. Open Plugin settings** From the Midaz Module sidebar, go to **Settings** > **Plugins**. **2. Enable Fees Engine** Toggle **Fees Engine** on. The **Fees Engine** menu item appears in the sidebar with **Fee Packages**, **Account plans**, **Calculator**, **Billing Packages**, **Billing Runs**, and **Fee Debts** sub-items. > [!NOTE] > > If you disable the Fees Engine later, the Console hides its menu. Midaz keeps your packages and still applies them to matching Transactions. ## Where to go next *** > [card] [Manage Fee Packages](/en/products/midaz/fees/console/managing-fee-packages) > > Create, edit, and delete packages. Define rules, scope by ledger or segment, and set waivers. > [card] [Account plans](/en/products/midaz/fees/console/managing-account-plans) > > Create account plans, publish new versions, and assign a plan to an account. > [card] [Fee Calculator](/en/products/midaz/fees/console/managing-fee-calculations) > > Estimate what a package would charge for a sample Transaction without running a real one. > [card] [Manage Billing Packages](/en/products/midaz/fees/console/managing-billing-packages) > > Create maintenance packages, and turn volume and maintenance packages on or off. > [card] [Billing Runs](/en/products/midaz/fees/console/billing-runs) > > Preview the fees for a period before you apply them. > [card] [Fee Debts](/en/products/midaz/fees/console/fee-debts) > > List the fee debts of a ledger and collect the open debt of a balance. # Fee Calculator Source: https://docs.lerian.studio/en/products/midaz/fees/console/managing-fee-calculations Preview how Fee Packages apply to a sample Transaction using the Console Fee Calculator, with a detailed breakdown of flat, percentage, and deductible fees. The **Fee Calculator** previews how fees apply before you run a real Transaction. It uses an existing [Fee Package](/en/products/midaz/fees/console/managing-fee-packages) to estimate the total fees. It also shows a detailed breakdown of each rule: flat fees, percentages, and deductibles. Use it to test changes and validate logic with business teams. ## Accessing the Fee Calculator *** **Step 1** In the Midaz Module sidebar, expand **Fees Engine**. **Step 2** Click **Calculator** to open the Fee Calculator page. > [!WARNING] > > You need at least one [Fee Package](/en/products/midaz/fees/console/fe-creating-a-package) before using the Calculator. The estimator must run against a saved package. ## Why use the Fee Calculator *** The Fee Calculator is a read-only tool that does not affect the ledger or create any transactions. Use it to: * **Validate new fee packages** right after you create them * **Test edge cases** at minimum and maximum amount boundaries * **Compare fee structures** by running the same transaction through different packages * **Document expected fees** for finance teams or customers * **Debug fee issues** by reproducing scenarios and analyzing calculation breakdowns # Managing Fee Packages Source: https://docs.lerian.studio/en/products/midaz/fees/console/managing-fee-packages Browse, create, edit, and delete Fee Packages from the Midaz Console to control how flat, percentage, and combined charges apply to matching Transactions. **Fee Packages** are the base unit of the [Fees Engine](/en/products/midaz/fees/console/fees-engine-overview). Each package defines a set of fee rules and the conditions under which they apply to Transactions. > [!NOTE] > > Enable the Fees Engine in [Midaz module settings](/en/platform/console/plugin-settings) before you use this page. ## What a Fee Package contains *** A Fee Package lets you: * **Define fee calculation rules**: flat fees, percentage-based fees, or combined calculations. * **Set amount ranges**: apply fees only to transactions within a min/max range. * **Link to transaction routes**: target specific transaction flows. * **Waive fees for specific accounts**: exempt selected source accounts. * **Prioritize fee application**: control the order in which Fees Engine applies multiple fees. Fee Packages combine with [Accounting Routes](/en/products/midaz/console/managing-accounting-routes) and [Segments](/en/products/midaz/console/managing-segments) for granular control. ## Accessing the Fee Packages page *** In the Midaz Module sidebar, expand **Fees Engine**. Select **Fee Packages**. The page lists every configured package. > [!NOTE] > > If you have no Fee Packages, the list is empty and shows a prompt to create your first package. ### Available actions From the Fee Packages page, you can: > [card] [Create a Fee Package](/en/products/midaz/fees/console/fe-creating-a-package) > > Define new fee calculation rules for transactions > [card] [Edit a Fee Package](/en/products/midaz/fees/console/fe-editing-a-package) > > Update fee configurations and rules > [card] [Delete a Fee Package](/en/products/midaz/fees/console/fe-deleting-a-package) > > Delete a fee package from your configuration > [!NOTE] > > Select a package from the list to open its **details view**. There you can review the package's configuration (scope, amount range, and fee rules) before you edit it. Billing Runs preview the volume and maintenance fees of your billing packages for a period. They do not evaluate fee packages. To preview the fees that one transaction pays under a fee package, use [Fee Estimation](/en/products/midaz/fees/console/fe-fee-simulation). ## Understanding Fee Package structure *** When you create or edit a fee package in Midaz Module, you work with these fields: ### Basic information * **Fee Package Name** (required) - A descriptive name for the fee package * **Description** (optional) - Explanation of the package purpose and when it applies * **Transaction Route** (optional) - Link to a specific transaction route. You set it only when you create the package * **Segment** (optional) - Associate with a specific segment. You set it only when you create the package * **Ledger** (required) - The ledger this package applies to * **Metadata selector** (optional) - Metadata pairs that a transaction must carry for the package to apply. You set them only when you create the package ### Amount range * **Minimum Amount** (required) - Lowest transaction amount for fee application * **Maximum Amount** (required) - Highest transaction amount for fee application * **Waived Accounts** (optional) - List of account aliases exempt from these fees * **Rounding** (optional) - How the package rounds every fee it charges: **Round down** or **Round half up**, with 0 to 18 decimal places ### Fee rules Each fee package can contain multiple fee rules with: * The fee name field (placeholder **Display Name**) - Name that identifies this fee * The fee type card - How Fees Engine calculates the fee: * **Flat Fee** - Fixed amount regardless of transaction value * **Percentage Fee** - Percentage of the transaction amount * **Max between types** - Higher value between flat and percentage calculations * **Calculation Type** - `flat` or `percentage` * **Calculation Value** - The fee amount or percentage * **Reference Amount** - Base for percentage calculation: * `originalAmount` - Calculate on the original transaction value * `afterFeesAmount` - Calculate after Fees Engine applies other fees * **Priority** - Order of fee application (lower numbers apply first) * **Deductible from transaction?** - Whether Fees Engine deducts this fee from the transaction * **Deferrable** - Whether the share of this fee that the payer cannot cover can become a [fee debt](/en/products/midaz/fees/fee-debt) * **Credit Account ID** - Account that receives the fee amount ## Common use cases *** > [accordion] Simple flat fee per transaction > > Apply a fixed fee to all transactions within an amount range: > > * Fee type: **Flat Fee** > * **Calculation**: `flat` with value `2.50` > * **Example**: \$2.50 fee on every transaction between \$10 and \$1000 > [accordion] Percentage-based fee > > Charge a percentage of the transaction amount: > > * Fee type: **Percentage Fee** > * **Calculation**: `percentage` with value `1.5` > * **Example**: 1.5% fee on transfers, where \$100 transfer = \$1.50 fee > [accordion] Tiered fee structure > > Create multiple packages with different amount ranges: > > * Package 1: \$0-\$100 → 2% fee > * Package 2: \$100.01-\$1000 → 1.5% fee > * Package 3: \$1000.01-\$1000000 → 1% fee (set the maximum to the highest amount you accept) > * Lower fees for higher-value transactions > [accordion] Combined flat + percentage (maximum) > > Apply whichever is higher between flat and percentage: > > * Fee type: **Max between types** > * **Calculations**: `flat: 1.00` and `percentage: 2.0` > * **Example**: On \$30 transaction: max(\$1.00, \$0.60) = \$1.00 fee > * **Example**: On \$100 transaction: max(\$1.00, \$2.00) = \$2.00 fee > [accordion] Fee waiver for premium accounts > > Exempt specific accounts from fees: > > * Create package with standard fee rules > * Add premium account aliases to **Waived Accounts** list > * These accounts transact without the configured fees ## Best practices *** **1. Plan your fee structure** Design your fee packages before implementation. Consider transaction types, amount ranges, and customer segments that require different fee treatments. **2. Use descriptive labels** Choose clear fee group labels and descriptions that explain when and why fees apply. This helps with auditing and customer communication. **3. Set appropriate amount ranges** Define minimum and maximum amounts carefully to avoid gaps or overlaps in your fee structure. **4. Test fee calculations** Use the [Fee Estimation](/en/products/midaz/fees/console/fe-fee-simulation) feature to check a package's results right after you create it, and disable the package if a result is wrong. **5. Manage priority carefully** When you use multiple fees in a package, set priorities so the fees apply in the correct order. **6. Document waived accounts** Record why you waive fees for certain accounts. This supports audit and compliance. ## Fee calculation flow *** When Fees Engine processes a transaction, it: 1. Finds the enabled packages that match the transaction route, segment, metadata selector, and amount range 2. Keeps the match that carries the most scope constraints: a transaction route, a segment, and one per metadata pair. When two matches tie, Midaz refuses the transaction and names the tied packages. Re-scope one of them 3. Skips the waived accounts 4. Applies fee rules in priority order 5. Calculates each fee based on application rule and reference amount 6. Credits fee amounts to designated accounts > [!NOTE] > > Enable a fee package so it applies to transactions. To pause a package, disable it. A disabled package stays in your configuration. # Fee debt Source: https://docs.lerian.studio/en/products/midaz/fees/fee-debt Keep an unpaid fee as a debt that the payer's next credits can settle, oldest first, instead of refusing the transaction. By default, Midaz refuses a transaction when the payer cannot fund its fees. A **deferrable** fee changes this. The payer pays the part of the fee that its available amount covers. The rest becomes a **fee debt**, and the transaction goes through. Later credits to the payer can settle the debt. Fee debt is off by default. It applies only to fees of a fee package that you mark as deferrable. An [account plan](/en/products/midaz/fees/account-plans) fee is never deferrable. ## Make a fee deferrable *** Set `deferrable: true` on a fee when you [create](/en/reference/products/midaz/v2/create-package) or [update](/en/reference/products/midaz/v2/update-package) its fee package. * Only a fee with `isDeductibleFrom: false` can be deferrable. Midaz refuses a deductible fee that is also deferrable with error `0530`. * A deferrable fee opens a debt only in a `/v2` direct transaction. In a `/v2` hold, Midaz refuses an unfunded fee with error `0018`. * When a balance already has 256 open fee debts, Midaz refuses a new unfunded deferrable fee on it with error `0018`. **Example.** A payer holds 105 and sends 100 with a deferrable fee of 10. The transaction moves 105: the payment of 100 and 5 of the fee. The other 5 becomes a fee debt. The transaction metadata key `feeDebtOpenings` records the debt. ## How a debt is settled *** A credit to the payer's balance through the `/v2` API can settle its open fee debts, oldest first. This includes direct transactions, commits, and reversals. A credit that is smaller than a debt settles part of it. A payer's balance that cannot send funds settles nothing, and settlement stops at the first debt whose fee account cannot receive funds. Each settlement moves the value from the payer's balance to the fee account of the debt. Midaz records these movements as operations of type `FEE_SETTLEMENT`, and the transaction metadata key `feeDebtSettlements` records the settled debts. To settle debts without a credit, use [Collect open fee debts](/en/reference/products/midaz/v2/collect-a-balance-s-open-fee-debts). Send the `accountAlias` of the payer, and optionally a `balanceKey` and a `maxAmount`. * Midaz pays the open debts of that balance from its available amount, oldest first, and charges no fee on the collection. * The response gives the `collected` amount and the `transactionId` of the collection. * When nothing is collected, the response gives `collected: "0"` and Midaz creates no transaction. * You cannot revert a collection. Midaz refuses it with error `0089`. ## Reversals and fee debt *** When you [revert](/en/reference/products/midaz/v2/revert-transaction) the transaction that opened a debt, the payer gets the whole fee back: * The reversal returns the part of the fee that the payer paid in the original transaction. * Midaz cancels the part of the debt that is still open. * Midaz refunds the part that later credits settled. The fee account pays the refund, and Midaz records it as operations of type `FEE_REFUND`. On `/v2`, the refund can then settle the payer's other open debts, oldest first. A revert of a credit that settled a debt can reopen that debt for the settled amount. When the fee-debt record of a transaction is not complete yet, Midaz refuses the revert with error `0529` (HTTP 409) and moves nothing. Try again later. ## Read fee debts *** * [List fee debts](/en/reference/products/midaz/v2/list-the-fee-debts-of-a-ledger-oldest-first) gives the debts of a ledger, oldest first. Filter by `account_alias`, `balance_key`, and `status` (`open` or `settled`). With `account_alias`, the response also gives `openTotal`, the total that the balance owes. * [Retrieve a fee debt](/en/reference/products/midaz/v2/get-a-fee-debt) gives one debt with its `remaining` amount and its history of changes. * In the Console, the [Fee Debts](/en/products/midaz/fees/console/fee-debts) page lists the fee debts of a ledger. Listing and reading fee debts needs the `midaz/fee-debts` permission with `get`. Collecting fee debt needs `post`. Each change has one of these kinds: | Kind | What happened | | - | - | | `opened` | The payer could not fund the fee, and the debt opened. | | `settled` | A credit or a collection paid part or all of the debt. | | `canceled` | A revert of the original transaction canceled the open part. | | `reopened` | A revert took back a settlement, and that amount is owed again. | | `refunded` | A revert of the original transaction returned a settled part to the payer. | ## Accounts and balances with fee debt *** Midaz refuses to delete a balance, or to delete or close its account, when: * The balance owes fee debt (error `0527`). Credit the balance or collect the debt first. * Other balances owe fee debt to the balance (error `0528`), for example a fee account. Credit the balances that owe the debt first. ## Before you enable fee debt *** * Run Midaz v4.2.0 or later on every ledger instance before you set `deferrable` on a fee. An earlier version cannot complete a transaction that carries fee debt. After you set it, do not roll the ledger back to an earlier version. * The ledger keeps open fee debts in Valkey. Valkey must be persistent and keep these keys. See [Configuring dependencies](https://github.com/LerianStudio/helm/blob/main/charts/midaz/README.md#valkey). # Fees Engine calculations Source: https://docs.lerian.studio/en/products/midaz/fees/fee-engine-calculation Learn how the Fees Engine calculates fees, handles decimal precision, splits amounts across accounts, and applies exemptions over daily, weekly, or monthly periods. ## Numeric values (string) *** Express all financial values in **Fees Engine** as a `string` with the `numeric` type. This gives high-precision decimal handling for assets like BRL or BTC. It also prevents rounding errors during calculations, splits, or exemptions. **Example:** ``` "value": "12.50" ``` ## Billing periods *** When triggering a billing calculation, you specify the time window through the `period` field. Fees Engine supports three formats: | Format | Example | Window | | - | - | - | | Daily | `2026-03-15` | Start of that day → start of the next day (UTC) | | Weekly | `2026-W13` | Monday 00:00 UTC of the ISO week → following Monday 00:00 UTC | | Monthly | `2026-03` | First instant of the month → first instant of the next month (UTC) | The engine counts qualifying transactions for volume packages within that window. Maintenance packages charge the accounts that are active when you run the calculation, and the period only labels the result. A window includes its first instant and excludes the first instant of the next window, so a transaction stamped at that instant counts once, in the later window. > [!TIP] > > Weekly periods follow [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Week_dates). Week numbering ranges from `W01` to `W52` (or `W53` in years that have 53 ISO weeks). The week always starts on Monday. Choose the granularity that matches your billing cycle. A prepaid card product billed daily would use `2026-03-15`. A SaaS platform billed monthly would use `2026-03`. A marketplace that settles weekly would use `2026-W13`. ## Fee calculation rules *** Each fee uses an `applicationRule` to define how it's calculated. You can choose from three rule types: * [maxBetweenTypes](#maxbetweentypes) * [flatFee](#flatfee) * [percentual](#percentual) You can combine different rules in a single package to match your use case. Other key fields: * `isDeductibleFrom`: `false` adds the fee on top of what the source sends. `true` deducts it from what the destination receives. The **Result** columns below show that amount. * `referenceAmount`: either `originalAmount` or `afterFeesAmount`. * `priority`: defines the order of application. Priority 1 must always use `originalAmount`. * `deferrable`: `true` keeps the part of the fee that the payer cannot fund as a [fee debt](/en/products/midaz/fees/fee-debt). ### maxBetweenTypes Applies whichever is greater: a flat or percentage-based fee. **Example** * Flat fee value: R\$5. * Percentual fee: 2%. * Reference amount: R\$1,000. ``` rate = 1000 * 0.02 = R$ 20.00 ``` Since **R\$ 20 > R\$ 5**, the engine applies the percentage-based fee. ### flatFee Applies a fixed fee amount. Behavior depends on `isDeductibleFrom`. **Example** * Flat fee: R\$15. * Reference amount: R\$115. | `isDeductibleFrom` | Formula | Result | | :- | :- | :- | | `false` | `referenceAmount + fee` | R\$ 130.00 | | `true` | `referenceAmount - fee` | R\$ 100.00 | ### percentual Applies a fee as a percentage of the reference amount. **Example** * Value: 30%. * Reference amount: R\$ 389.50. | `isDeductibleFrom` | Formula | Result | | :- | :- | :- | | `false` | `referenceAmount + (referenceAmount * value)` | R\$ 506.35 | | `true` | `referenceAmount - (referenceAmount * value)` | R\$ 272.65 | ## Fee splitting *** When a transaction has multiple source accounts, Fees Engine splits fees proportionally. ### Example * Total amount: R\$4,000.00 * Fixed fee: R\$15.00 * Tax: 4% * `isDeductibleFrom: false` ### Participation % > **Formula**: (Account Amount ÷ Total Amount) × 100 | Account | Share | Amount | | :- | :- | :- | | @account1 | 25% | R\$ 1,000 | | @account2 | 25% | R\$ 1,000 | | @account3 | 40% | R\$ 1,600 | | @account4 | 10% | R\$ 400 | ### Fixed fee distribution > **Formula**: `fixed Fee × participation %` | Account | Fee Share | Total | | :- | :- | :- | | @account1 | R\$ 3.75 | R\$ 1,003.75 | | @account2 | R\$ 3.75 | R\$ 1,003.75 | | @account3 | R\$ 6.00 | R\$ 1,606.00 | | @account4 | R\$ 1.50 | R\$ 401.50 | ### Proportional tax > **Formula**: `account amount × tax %` | Account | Tax | Total w/ Tax | | :- | :- | :- | | @account1 | R\$ 40.00 | R\$ 1,040.00 | | @account2 | R\$ 40.00 | R\$ 1,040.00 | | @account3 | R\$ 64.00 | R\$ 1,664.00 | | @account4 | R\$ 16.00 | R\$ 416.00 | ### Final amount per account > **Formula**: `principal + fee + tax` | Account | Fee | Tax | Final Total | | :- | :- | :- | :- | | @account1 | R\$ 3.75 | R\$ 40.00 | R\$ 1,043.75 | | @account2 | R\$ 3.75 | R\$ 40.00 | R\$ 1,043.75 | | @account3 | R\$ 6.00 | R\$ 64.00 | R\$ 1,670.00 | | @account4 | R\$ 1.50 | R\$ 16.00 | R\$ 417.50 | #### Validations * Total shares = 100% * Fee split matches flat fee * Tax split = 4% * Total sent = R\$ 4,175.00 ## Fee exemptions: rules & hierarchy *** ### By transaction amount Use `minimumAmount` and `maximumAmount` to define when **fees should apply**. > For example: If the range is R\$ 0–300, a transaction of R\$ 301 won’t trigger fees. ### By account The system checks `waivedAccounts`. A waived account pays no share of the fee. When every source account is waived, no fee applies. > [!TIP] > > **Hierarchy:** Value range check > then account exemption ## Mixed example: fee exemptions and proportional fee splitting *** This package includes accounts with fee exemptions and requires splitting fees proportionally. ### Scenario We’re processing a transaction of **R\$ 4,000**, which includes: * A **fixed fee** of **R\$ 16**. * Only some accounts are subject to the fixed fee * An **IOF tax** of **6%** to be deducted. #### Split on the source side | Source Account | % | Proportional Value | | :- | - | :- | | @account1 | 15% | R\$ 600 | | @account2 | 35% | R\$ 1,400 | | @account3 | 40% | R\$ 1,600 | | @account4 | 10% | R\$ 400 | The engine applies the fixed fee only to `@account3` and `@account4`. #### Result after Admin Fee (proportional) | Account | Admin Fee | Total | | :- | :- | :- | | @account1 | Exempt | R\$ 600 | | @account2 | Exempt | R\$ 1,400 | | @account3 | R\$ 12.80 | R\$ 1,612.80 | | @account4 | R\$ 3.20 | R\$ 403.20 | Total send value increases to **R\$4,016**. #### IOF deduction (recipient) | Recipient | % | Gross | IOF (6%) | Net | | :- | - | :- | :- | :- | | @donation1 | 25% | R\$ 1,000 | R\$ 60 | R\$ 940 | | @donation2 | 25% | R\$ 1,000 | R\$ 60 | R\$ 940 | | @donation3 | 25% | R\$ 1,000 | R\$ 60 | R\$ 940 | | @donation4 | 25% | R\$ 1,000 | R\$ 60 | R\$ 940 | > [!CAUTION] > > The engine credits fees to the accounts defined in each fee’s `creditAccount`. ## Repeating decimals *** When a package has no `rounding` and a fee split produces a repeating decimal (for example, 0.3333...), Fees Engine keeps every fee leg at full precision. It reconciles the small remainder onto the fee for the account with the largest value. This keeps the total exact, avoids rounding drift, and keeps your ledger consistent. ## Rounding *** A fee package can set `rounding`, with a `scale` from 0 to 18 and a `mode`: * `floor` rounds each fee total down to the scale. * `halfUp` rounds each fee total to the nearest value at the scale, and rounds half away from zero. Each payer's share of the fee rounds toward zero to the same scale. The payer with the largest share takes the remainder, so the shares add up to the fee total. An update replaces `rounding` as a whole, and it cannot remove it. Without `rounding`, the package keeps every fee at full precision. **Example**: `rounding` is `{"scale": 2, "mode": "floor"}`, and a 1% fee applies to R\$ 1,234.56. The fee total is R\$ 12.3456, and the package charges R\$ 12.34. ## Billing calculations *** Billing packages use a different calculation model than fee packages. Instead of evaluating individual transactions, they aggregate data over a billing period and return charge payloads for your orchestrator to execute. Billing supports three period formats: monthly (`YYYY-MM`), weekly (`YYYY-Www`, e.g., `2026-W13`), and daily (`YYYY-MM-DD`). ### Volume billing calculation Volume billing counts transactions matching an `eventFilter` (transaction route + status) within the billing period, then applies pricing based on the configured model. The calculation follows this order: 1. **Count** qualifying transactions in the period. 2. **Subtract** the `freeQuota` from the total count to get the billable count. 3. **Apply pricing** based on the `pricingModel` (`tiered` or `fixed`). 4. **Apply a discount** from `discountTiers`, evaluated against the **total** count (before the free quota was subtracted). The engine keeps amounts at full decimal precision throughout. The engine applies no asset-scale rounding. #### Tiered pricing Tiered pricing is **volume pricing, not graduated pricing**. The engine finds the single tier whose quantity range contains the billable count, then charges **every** billable unit at that tier's unit price. It does not price each unit inside its own range. A tier's range is inclusive on both ends. If you omit the upper bound, the tier is unbounded. The API rejects overlapping tiers. With two or more tiers, it also rejects gaps and requires the last tier to be unbounded. A package holds at most 50 tiers. The engine looks up a tier only when the billable count is positive. If the billable count is positive and no tier covers it, the calculation fails for that package. A billable count of zero skips the tier lookup and produces a zero amount, so your tiers do not need to cover zero. **Example**: A billing package for boleto issuance with three tiers and a free quota of 50: | Range | Unit price | | - | - | | 1–500 | R\$ 1.20 | | 501–2,000 | R\$ 0.80 | | 2,001+ | R\$ 0.45 | For a client that issued 1,800 boletos in the month: * 50 exempt (free quota) → 1,750 billable * 1,750 falls in the 501–2,000 tier, so the engine prices **all** 1,750 units at R\$ 0.80: R\$ 1,400.00 gross * Discount tier applies on the total count of 1,800 (≥ 1,000 → 5%): −R\$ 70.00 * **Net total: R\$ 1,330.00** #### Fixed pricing A single unit price applies to all billable transactions regardless of volume. The engine still subtracts the free quota before calculation. Fixed pricing takes its unit price from the **first tier** in the package. The API requires at least one tier on every volume package. **Example**: R\$ 0.10 per Pix sent, no free quota: * 5,000 Pix transactions × R\$ 0.10 = R\$ 500.00 #### Discount tiers At most **one** discount tier applies: the one with the largest `minQuantity` that the total count meets or exceeds. The engine applies its percentage to the gross amount. The engine evaluates discounts against the total transaction count, not the billable count. #### Count scope Volume calculation counts transactions **per transaction route across the whole ledger**. The free quota, the tiers, and the discount tiers all apply to that route-level total. To count two flows separately, create one package per transaction route. ### Maintenance billing calculation Maintenance billing charges a fixed amount per account that is active when you run the calculation. The engine resolves the target accounts, keeps only the active ones, and generates a single transaction payload. The result is a N:1 transaction: * Each active account appears as a debit entry (`source.from`) for the configured `feeAmount`. * The `maintenanceCreditAccount` receives the full total as a single credit entry (`distribute.to`). The engine keeps only accounts whose status code is `active` and excludes every other status. If no account resolves, the package returns an empty payload (`{}`) instead of a transaction. Midaz refuses a transaction that posts more than 10,000 legs (error `0515`), so it refuses the payload of a package that charges 10,000 or more active accounts. Give each maintenance package a segment or portfolio with fewer than 10,000 active accounts. **Example**: Monthly maintenance of R\$ 9.90 for a segment with 8,000 active PF accounts: * 8,000 entries in `source.from`, each debited R\$ 9.90 * 1 entry in `distribute.to` credited R\$ 79,200.00 ### Zero-amount results When a package's net amount comes out zero (for example the free quota covered every transaction), the engine still returns a result for that package, but with an empty transaction payload (`{}`). Treat that as "processed, nothing to submit". Fully exempt usage reaches this result without a tier lookup. The free quota brings the billable count to zero, the engine skips tier matching, and the amount is zero. A package whose tiers start at 1 is correct for this case. ### All-or-nothing failure policy If any billing package fails during a `/billing/calculate` call, the entire operation fails. The engine returns no partial results. The response includes which package and resource caused the failure, so you can fix and re-execute. ### Audit metadata The metadata of a volume transaction payload includes the billing type, package id and label, period, total and billable event counts, free quota used, pricing model, gross and net amounts, and the discount detail (percentage, amount, and `minQuantity`) when one applied. The metadata of a maintenance transaction payload includes the billing type, package id and label, period, total account count, and the per-account fee amount. # Fees Engine best practices Source: https://docs.lerian.studio/en/products/midaz/fees/fees-engine-best-practices Follow Fees Engine best practices for naming packages, setting fee priorities, segmenting customers, and running production setups with full auditability. Fees Engine controls how you calculate, apply, and track fees. These recommendations complement the [Fees Engine overview](/en/products/midaz/fees/fees-engine-overview) and the [calculation mechanics](/en/products/midaz/fees/fee-engine-calculation) guide. ## 1. Design fee packages with clear naming and segmentation *** A well-organized package structure makes it easier to maintain, debug, and audit your fee configuration over time. * **Use descriptive names** that reflect the business context (e.g., "pix-transfer-standard", "wire-premium-segment"). * **Segment by product and customer group** using `segmentId`. This allows you to apply different fee rules to different customer tiers without creating conflicting packages. * **Keep packages focused**. A package that tries to cover too many scenarios becomes hard to test and maintain. Prefer multiple focused packages over one that does everything. * **Document your package structure** internally. As your package count grows, a clear reference of which package applies where prevents misconfiguration. ## 2. Set fee priorities carefully *** When a package contains multiple fees, the `priority` field determines the order of execution. Getting this wrong can produce incorrect calculations. * **Priority 1 must always use `referenceAmount: originalAmount`**. The engine enforces this. * **Fees with `isDeductibleFrom: true` must also use `referenceAmount: originalAmount`**. Deductible fees then always apply to the full transaction value. * **Priority must be unique within a package**. The engine rejects duplicate priorities. * **Think about fee dependencies**. If one fee adjusts the transaction value and another fee should be calculated on the adjusted value, use `referenceAmount: afterFeesAmount` with a higher priority number. If the second fee should reference the original value, use `originalAmount`. > [!TIP] > > When in doubt, start with a simple configuration (one or two fees per package) and validate the results using the estimate endpoint before adding complexity. ## 3. Always estimate before applying fees in production *** Fees Engine provides an [estimate endpoint](/en/reference/products/midaz/v2/estimate-fee-calculation) that lets you preview fee calculations without writing anything to the ledger. Use estimation to: * **Validate new packages** before activating them. Confirm that the calculated values match your expected results across different transaction amounts. * **Test edge cases**: zero-amount transactions, boundary values at `minimumAmount` and `maximumAmount` thresholds, and exempted accounts. * **Preview fees for users**. If your product shows fees before confirmation, use the estimate endpoint to preview the fee of a package. An estimate does not read account plan assignments, so it does not preview the fee of an account plan. * **Debug unexpected results**. If a calculated fee doesn't match expectations, estimate the same transaction with a specific `packageId` to isolate the issue. > [!NOTE] > > A v2 transaction selects the matching package automatically. The estimate endpoint requires a specific `packageId`, so you choose which package to test. ## 4. Manage exemptions explicitly *** Fees Engine supports two types of exemptions: by **transaction amount range** and by **account**. * **Amount ranges** (`minimumAmount`, `maximumAmount`): Define the transaction value window in which fees apply. Transactions outside this range are exempt. Use this for promotional thresholds or tiered pricing. * **Waived accounts** (`waivedAccounts`): Specific accounts exempt from fees within a package. Use this for internal accounts, employee accounts, or partnership arrangements. Best practices for exemptions: * **Keep waived account lists short and reviewed**. Large lists become hard to audit. Periodically review which accounts are exempted and why. * **Document the business reason** for each exemption in your internal records. * **Test exemption boundaries**. If your range is R\$ 0–300, make sure transactions at exactly R\$ 300 and R\$ 301 behave as expected. ## 5. Use correct numeric values *** Express all financial values in Fees Engine as **strings** using the `numeric` type. This prevents floating-point precision errors that are common with decimal arithmetic. ```json theme={null} "value": "12.50" ``` * Always send values as strings, even whole numbers (e.g., `"100"` not `100`). * Never use floating-point types for monetary calculations in your integration layer. * The engine automatically adjusts fee splits with repeating decimals (e.g., R\$ 10 divided by 3 accounts) to keep ledger totals exact. ## 6. Use soft delete for auditability *** When you delete a fee package, Fees Engine marks it with a `deletedAt` timestamp rather than removing it from the database. This preserves the audit trail for historical transactions that referenced that package. * **Periodically review** deleted packages if your database grows significantly. Archiving strategies can help manage storage without losing audit capability. ## 7. Monitor fee processing in production *** Fees run inside the Midaz ledger process. Use the ledger's shared OpenTelemetry configuration and health endpoints to observe fee processing. See [Environment variables](/en/products/midaz/midaz-environment-variables) for the supported configuration. In production: * **Monitor the ledger health endpoints** and its traces and logs. * **Set up alerts** for sustained high latency or errors in fee calculations. * **Monitor the configured MongoDB deployment**: connection-pool usage, disk space, and replication health. * **Review ledger pod resource usage** against your traffic patterns and autoscaling behavior. ## 8. Keep versions compatible *** Fees runs inside the Midaz ledger process, so it upgrades with Midaz and has the same version. Before you upgrade Midaz: * Check the [version compatibility table](/en/products/midaz/midaz-version-compatibility) for the components you run with Midaz. * Back up your MongoDB data before any major upgrade. * Test the upgrade in a staging environment before applying it to production. For the chart's per-version upgrade notes, see the [Midaz chart upgrade notes](https://github.com/LerianStudio/helm/tree/main/charts/midaz/docs). ## 9. Review the security recommendations *** Fees Engine processes financial data and integrates with Midaz ledger operations. Make sure your deployment follows the platform-wide [Security recommendations](/en/products/midaz/security-recommendations), which cover: * Network segmentation and Zero Trust Architecture * Secret management and rotation (including database credentials) * TLS 1.2+ enforcement for all communications * RBAC configuration via [Access Manager](/en/platform/access-manager) * Patch management and vulnerability scanning ## 10. Design billing packages with clear scope *** Each billing package should represent a single, well-defined charge. Avoid packing unrelated pricing into one package. * **Separate packages per transaction route**. A package for Pix billing and a package for boleto billing are clearer than one package that tries to handle both. * **Use descriptive labels** that include the billing type and target: "Pix Send Monthly Billing (Standard Tier)" is better than "Billing Package 1". * **One `accountTarget` type per maintenance package**. You cannot combine `segmentId`, `portfolioId`, and `aliases` in the same package. If you need different targets, create separate packages. A single `/billing/calculate` call evaluates all active packages. ## 11. Write commercial terms against route volume *** Volume calculation counts transactions per transaction route across the whole ledger. The free quota, the tiers, and the discount tiers all apply to that route-level total. * **State thresholds as route volume.** "The first 100 transactions on the `pix-send` route are free" maps directly onto a package. Write the contract in the same terms the engine bills in. * **Split routes to split counts.** One package per transaction route keeps each flow on its own quota, tiers, and discounts. ## 12. Plan free quotas and discount tiers carefully *** Fees Engine evaluates free quotas and discounts in a specific order: 1. The engine subtracts the free quota from the total count to get the billable count. 2. The engine prices the billable count. For tiered packages it charges every billable unit at the single matching tier's rate (volume pricing, not graduated). 3. The engine applies one discount tier to the gross amount, chosen against the **total** count (before the free quota was subtracted). Design considerations: * **Free quotas reset each billing period**. Set the value based on your commercial agreement per period (monthly, weekly, or daily), not lifetime. * **Tiers are volume brackets, not slices**. A billable count of 1,750 against a 501–2,000 tier prices all 1,750 units at that tier's rate. Crossing a bracket boundary changes the rate for the whole volume, so tier boundaries can move the bill sharply. * **Cover every positive billable count.** If the billable count is positive and no tier's range contains it, the calculation fails for that package. With two or more tiers, the API rejects gaps and requires an open upper bound on the last tier. Start the first tier at 1 (a billable count of zero produces a zero amount and an empty payload without a tier lookup). * **Discount tiers are cumulative thresholds**, not ranges, and only one applies: the highest `minQuantity` the total count reaches. If you define discounts at 200 and 400 transactions, a client with 500 transactions gets the 400+ discount, not both. * **Watch the two different counts.** Pricing uses the billable count (after free quota); the discount uses the total count (before it). > [!TIP] > > Use test calculations with known transaction counts to validate your tier and discount configuration before enabling the package in production. ## 13. Size maintenance account targets appropriately *** Maintenance packages support three target types: | Target type | Use case | | - | - | | `segmentId` | Standard tiers (PF, PJ, premium) | | `portfolioId` | Business portfolios (PME, Corporate, Enterprise) | | `aliases` | Specific named accounts, at most 100 | For more than 100 accounts, use a segment or a portfolio in Midaz with fewer than 10,000 active accounts. ## 14. Handle billing failures with re-execution *** Billing calculation follows an all-or-nothing policy. If any package fails, the engine returns no results. * **Build retry logic** into your orchestrator. The calculation is stateless, so a retry is safe. A retry reflects the ledger at the time it runs. * **Check error responses** for the package that failed. The message names its ID and label. A common cause is a volume package whose tiers do not cover the billable count. * **Separate volume and maintenance calculations** if one type consistently succeeds while the other fails. Call `/billing/calculate` with `"type": "volume"` and `"type": "maintenance"` independently to isolate failures. # What is Fees Engine? Source: https://docs.lerian.studio/en/products/midaz/fees/fees-engine-overview Fees Engine controls how fees and billing are configured, calculated, and tracked across per-transaction and per-period scenarios. Fees is an embedded component of the unified Midaz ledger process. It provides fee and billing configuration and calculations alongside the ledger. Deploy and configure it with Midaz. It is not a separate service or plugin. ## Why use Fees Engine? *** The **Fees Engine** helps you manage complex fee logic. It applies flat rates, distributes fees proportionally, and estimates transactions before you run them. It offers: * **Flexible fee configuration** via fee packages, tailored to account groups or specific ledgers. * **Multiple calculation methods**: flat fees, percentual rates, and "max between types" logic. * **Proportional fee distribution** for marketplace flows and multi-account operations. * **Support for accounting routes** via `transactionRoute`, `routeFrom`, and `routeTo`. * **Estimation tools** to preview calculations before executing transactions. * **Fee exemption logic** by account and transaction value ranges. * **Priority-based application** to control the order of multiple fees. * **Accurate deduction mechanics** with `isDeductibleFrom` support. * **Volume-based billing** via billing packages. Charge based on accumulated transaction counts per period (daily, weekly, or monthly). * **Maintenance billing** for recurring per-account charges, targeting accounts by segment, portfolio, or explicit list. * **Free quotas and progressive discounts** to model tiered pricing and volume incentives. * **Segment-based exemptions** to exempt entire account groups from fee packages without listing individual accounts. * **Fee debt** for deferrable fees: in a `/v2` direct transaction, an unfunded fee becomes a debt that later credits settle. * **[Account plans](/en/products/midaz/fees/account-plans)** that you assign to accounts, with a free quota per fee and calendar month, and service fees that you charge to an account. > [!TIP] > > Fees Engine is a licensed Midaz capability that runs inside the unified ledger process. Deploy and configure it with Midaz. If you'd like to learn more or evaluate it for your use case, [get in touch with our team](https://lerian.studio/contact). ## What are fees? *** Fees are monetary values charged in exchange for services, products, or access to resources. Their purpose depends on the industry. Below are a few examples: ### Finance In the financial sector, fees cover operational costs and support legal compliance. * **Account maintenance fee**: Keeps accounts operational and covers administrative costs. * **Transfer fee:** Applies to transactions like TEDs or international transfers. ### Logistics and transportation In the logistics sector, fees cover transportation and storage services. * **Handling fee**: Applies during storage and physical movement of goods. * **Unloading fee**: Covers unloading operations at delivery points. ### Pharmaceutical and healthcare In the pharmaceutical sector, fees ensure the quality and regulation of services. * **Medication registration fee**: Related to regulatory approvals and market entry. * **Laboratory analysis fee**: Covers testing and quality control costs. ### Agricultural In the agricultural sector, fees cover commercialization and regulatory processes. * **Sanitary inspection fee**: Ensures health compliance for agricultural exports. * **Agricultural export fee**: Covers admin and regulatory export costs. ## Scope *** The unified Midaz service exposes Fees and Billing only on the ledger-scoped v2 surface. The URL is the sole ledger input: a `ledgerId` query parameter is not accepted, and a request body that sends `ledgerId` is rejected as an unknown field. Retrieving, updating, or deleting a package owned by another ledger returns not found. ## Fee Packages *** A **Fee Package** defines how the engine applies fees to a transaction. It groups one or more fee rules. You customize it by segment, ledger, and accounting routes. You can create different packages for different products, transaction types, or customer segments. Each package has its own calculation logic, route configuration, and priority rules. A package includes required fields and can add optional matching or exemption fields: * **Ledger scope** – The v2 URL identifies the ledger that records the transaction and its fees. Do not send `ledgerId` in the request body. * **transactionRoute** – The ID of a transaction route. The package matches a transaction that sends the same `routeId`. * **segmentId** – A segment ID. The package matches when every source account, except `@external` accounts, belongs to this segment. * **metadataSelector** – Metadata pairs that the transaction must all carry for the package to match. A pair matches only a string metadata value that is equal to it. You set it when you create the package. * **waivedAccounts** – Accounts to exempt from fees, when you configure exemptions. * **fees** – A map of individual fee rules, each including: * **priority** – Defines execution order. * **routeFrom** and **routeTo** – Custom accounting routes for the fee. * **isDeductibleFrom** – Whether the engine deducts the fee from what the destination receives, instead of adding it on top. * **referenceAmount** – The base amount for calculations. * **deferrable** – Whether the part of the fee that the payer cannot fund becomes a [fee debt](/en/products/midaz/fees/fee-debt). The default is `false`. * **rounding** – Optional. The `scale` (0 to 18) and `mode` (`floor` or `halfUp`) that every fee of the package is rounded to. See [Rounding](/en/products/midaz/fees/fee-engine-calculation#rounding). ### Validation rules Fees Engine enforces the following rules: * **Fee priority must be unique** within a package. * Fees with `isDeductibleFrom: true` must use `referenceAmount: originalAmount`. * Fees with `priority` 1 must also use `referenceAmount: originalAmount`. * Fees with `deferrable: true` must use `isDeductibleFrom: false`. * Each fee's `creditAccount` must be an account alias that exists in the ledger. Midaz checks it when you create or update the package. * Each fee key starts with a lowercase letter, followed by ASCII letters and digits only (`^[a-z][a-zA-Z0-9]*$`). Midaz stores the key as you send it. An update refuses a new key that matches a stored key except for letter case. * When you delete an account, Midaz removes every fee that credits its alias and removes the alias from `waivedAccounts`. A package left without fees is disabled. * A create or update can return `0086` when another package write of the same ledger runs at the same time. The request changes nothing. Retry it. ### Fee application and estimation Midaz applies fees in-process when it creates a transaction. There is no separate public calculate-fees endpoint. The ledger evaluates the matching package in the transaction flow and applies its rules when one matches. #### [Estimate transaction fees](/en/reference/products/midaz/v2/estimate-fee-calculation) * Estimates fees for a specific package by its `packageId`. * Returns calculated fees only if the amount falls inside the package's amount range. It does not check `transactionRoute`, `segmentId`, or `metadataSelector`. * Does not read account plan assignments. * Useful for testing, debugging, or a preview of fees, without writing to the ledger. > [!NOTE] > > Fee application happens during transaction creation. Use `estimate` when you want to test a specific package without writing to the ledger. ### Segment-based exemptions Fee packages support exempting individual accounts by listing their aliases in `waivedAccounts`. To exempt a whole group at once, add a segment reference to that same list using the `segment:` form, for example `"segment:0198e5f4-7b2a-7c3d-9e1f-2a3b4c5d6e7f"`. > [!WARNING] > > The package's own `segmentId` field is not an exemption. It scopes which package applies to a transaction (segment-level package matching). Use segment-based exemptions when: * A customer tier (such as premium accounts) is universally exempt from a fee. * Internal or partner accounts belong to an existing segment in Midaz. * Maintaining a list of individual account aliases is impractical at scale. > [!TIP] > > Fees Engine resolves segment-based exemptions at calculation time. When accounts join or leave the segment, the change takes effect on the next calculation. You do not update the package. ## Billing Packages *** **Billing Packages** calculate charges from accumulated transaction volume over a period (daily, weekly, or monthly). Fee packages charge per individual transaction. Billing packages count the qualifying transactions and return payloads for your orchestrator to execute. Two types are available: * **Volume**: charges based on the number of transactions matching an event filter in the period. * **Maintenance**: charges a fixed fee per account that is active when you run the calculation. > [!NOTE] > > Billing packages are a calculation engine, not a billing platform. The engine calculates the charges and returns the payloads. Your orchestrator (Flowker, a cron job, or any other caller) runs the actual charges against Midaz. ### Volume packages A volume package counts transactions that match a given `eventFilter` (transaction route + status) within the billing period. It then applies a charge from the configured pricing model. Key fields: * **eventFilter**: Specifies which transactions to count, using `transactionRoute` and `status`. * **pricingModel**: Either `tiered` (unit price varies by quantity range) or `fixed` (single unit price regardless of volume). * **tiers**: Quantity ranges (`minQuantity`, `maxQuantity`) and `unitPrice` per unit within each range. * **freeQuota**: Number of transactions exempt per period. The engine subtracts this count before it applies pricing. * **discountTiers**: Progressive discounts. When total volume meets a threshold, the engine applies the configured discount percentage to the final amount. * **countMode**: Accepts `perRoute` or `perAccount`. Volume calculation counts all matching transactions on the route as a single total. * **debitAccountAlias** / **creditAccountAlias**: The accounts the charge debits and credits. Both must exist in the ledger. ### Maintenance packages A maintenance package applies a fixed fee per account that is active when you run the calculation, regardless of transaction activity. Key fields: * **feeAmount**: Fixed charge per active account. * **assetCode**: Currency for the charge. * **maintenanceCreditAccount**: Account that receives the fee revenue. * **accountTarget**: Defines which accounts to charge. Use exactly one per package: * `segmentId`: All accounts in the segment. * `portfolioId`: All accounts in the portfolio. * `aliases`: Explicit list of account aliases (maximum 100 accounts). > [!WARNING] > > Each maintenance package supports only one `accountTarget` type. You cannot combine `segmentId`, `portfolioId`, and `aliases` in the same package. ### Managing billing packages The following endpoints manage billing packages: * `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages`: Create a billing package. * `GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages`: List all billing packages. * `GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages/{billing_package_id}`: Retrieve a specific billing package. * `PATCH /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages/{billing_package_id}`: Update a billing package (`label`, `description`, `enable`). * `DELETE /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages/{billing_package_id}`: Soft-delete a billing package. * `POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing/calculate`: Calculate billing for a period. When you delete an account, Midaz removes its alias from the billing packages of the ledger. A package whose `debitAccountAlias`, `creditAccountAlias`, or `maintenanceCreditAccount` is that alias is disabled. The alias also leaves `accountTarget.aliases`, and a package left with no target alias is disabled. Creating a billing package, or enabling a disabled one, can return `0086` when another billing package write runs at the same time. Retry the request. Enabling a disabled volume package returns `409` (`0219`) while another enabled package bills the same route. ## Fee Packages vs. Billing Packages *** | | Fee Packages | Billing Packages | | - | - | - | | **Trigger** | Per transaction (synchronous) | Per period (monthly, weekly, or daily) | | **Pricing model** | Flat, percentual, maxBetweenTypes | Tiered or fixed by volume | | **Account exemption** | `waivedAccounts` (aliases or `segment:`) | No (`accountTarget` selects the accounts to charge) | | **Volume discounts** | No | Yes (`discountTiers`) | | **Free quotas** | No | Yes (`freeQuota` per period) | | **Recurring charges** | No | Yes (maintenance type) | | **Output** | Transaction with fees applied | Calculation payloads for the caller to execute | > [!NOTE] > > Fee packages and billing packages operate independently. ## Routing fees *** Every fee can have: * A `routeFrom`, which represents the accounting route for the debit (or source). * A `routeTo`, which represents the accounting route for the credit (or destination). * A `transactionRoute` on its package, which selects the transactions the package applies to. This allows granular tracking of each fee entry in the ledger. ## Deductible fees *** If you flag a fee as deductible ( `isDeductibleFrom: true`), the following logic applies: * The source account sends the full value. * The engine subtracts the fee from the amount the destination account receives. * The `referenceAmount` for calculations must be `originalAmount`. ## Soft delete for safe recordkeeping *** When you delete a resource: * Fees Engine marks it with a `deletedAt` timestamp. * Standard queries exclude it, but the database still stores it for audit and history. ## Integrations *** Use Fees Engine in a Midaz deployment alongside other components in your stack. You can call its capabilities from Lerian plugins or your own implementation to apply fees from your business logic. Use cases include: * Exchange engines * Lending platforms * Bill payment systems * Smart contracts * Pix (Brazil's instant payment platform) ## Security recommendations *** Before you deploy any component, review our [Security Recommendations](/en/products/midaz/security-recommendations). Implement each product and its plugins in line with security best practices, such as: * Securing network boundaries * Managing and rotating secrets * Applying timely patch management * Enforcing strict role-based access controls (RBAC) ## Next steps *** > [card] [Explore the Fees Engine API](/en/reference/products/midaz/v2/create-package) > > Browse endpoints for fee packages, calculations, and estimations. > [card] [Using Fees Engine](/en/products/midaz/fees/using-fee-engine) > > Learn how to create fee packages and apply them to transactions. # Migrate Bank Transfer fees to Midaz Source: https://docs.lerian.studio/en/products/midaz/fees/fees-migration-guide Move fee packages from the standalone plugin-fees to the Midaz Fees Engine, and switch Bank Transfer 3.1.0 or later to Midaz fees without a gap in charging. Bank Transfer 3.0.x charges fees through the standalone Fees plugin, `plugin-fees`. Bank Transfer 3.1.0 and later can charge them through the [Fees Engine](/en/products/midaz/fees/fees-engine-overview) that runs inside Midaz 4.1.0 and later. This page moves your fee packages from plugin-fees to Midaz. It then switches Bank Transfer over in an order that keeps every transfer charged. Follow this page when all of these are true: * You run Bank Transfer 3.0.x. * Your fee packages live in plugin-fees. * You upgrade to Bank Transfer 3.1.0 or later and to Midaz 4.1.0 or later. Bank Transfer uses only the fee packages of plugin-fees. If you also keep billing packages in plugin-fees, recreate them as Midaz [billing packages](/en/products/midaz/fees/using-fee-engine) before you retire plugin-fees. This page does not map them. > [!NOTE] > > The Lerian Console manages Midaz fee packages only. It does not show the packages that live in plugin-fees. See [Console](#console). ## How Bank Transfer chooses who charges the fee *** From 3.1.0, the Bank Transfer variable `MIDAZ_FEE_MODE` decides who calculates and charges the fee of each transfer. | Value | Who charges the fee | Midaz API that Bank Transfer posts on | | - | - | - | | `legacy` | plugin-fees, as in Bank Transfer 3.0.x | `/v1` | | `native` | The Midaz Fees Engine, from the fee packages of the ledger | `/v2` | | `auto` (default) | Bank Transfer reads the Midaz version. It uses `native` on Midaz 4.1.0 or later, and `legacy` on an earlier version. | `/v2` or `/v1` | * Bank Transfer does not start with any other value. * Under `auto`, Bank Transfer reads the Midaz version again every `MIDAZ_FEE_MODE_REFRESH` (default `5m`). When it cannot read the version, it keeps the mode it has, or uses `legacy` if it has none. * Bank Transfer fixes the mode of a P2P transfer or TED OUT at `/initiate`, and of a TED IN when it receives it. Every later step of that transfer uses the same mode: retries, confirmation, cancellation and reconciliation. A change of mode applies to new transfers only. * In `legacy` mode, `BTF_FEE_ENABLED` turns the plugin-fees integration on. With `false`, the default, Bank Transfer does not call plugin-fees, and every transfer runs with fee 0. * Set `native` only on Midaz 4.1.0 or later. Midaz 4.0.x charges fees without marking the fee entries, so Bank Transfer cannot read the fee that it charged. > [!WARNING] > > Do not rely on `auto` during the migration. Under `auto`, Bank Transfer 3.1.0 moves to `native` by itself as soon as it reads Midaz 4.1.0 or later. New transfers then use the Midaz packages. If your packages are still only in plugin-fees, Midaz finds no package, and those transfers carry no fee. > > In Bank Transfer 3.1.0, `BTF_FEE_ENABLED` does not stop Midaz from charging fees in `native` mode. To stop a fee, disable its Midaz package with `enable: false`, or delete the package. ## Before you start *** You need: * Midaz 4.1.0 or later, or a plan to upgrade to it. See [Updating Midaz](/en/products/midaz/updating-midaz). * Bank Transfer 3.1.0 or later, or a plan to upgrade to it. * Access to the plugin-fees API, to read and estimate your packages. * Access to the Midaz fee package API, or to the Console [Fee Packages](/en/products/midaz/fees/console/managing-fee-packages) page. * For each ledger and transfer type, the Midaz transaction route that Bank Transfer posts with. The tenant policy `routing.ledger_bindings` names it. See [Ledger routing](/en/interfaces/ted-jd/ted-configuration#ledger-routing). * Three Midaz permissions for the Midaz credentials of Bank Transfer: the resource `packages` with action `get`, the resource `estimates` with action `post`, and the resource `organizations` with action `get`. In single-tenant mode, these are the credentials of `MIDAZ_CLIENT_ID`. `legacy` mode does not use these permissions. Both modes also use the Midaz `settings` `post` permission described in [Bank Transfer environment variables](/en/interfaces/ted-jd/ted-environment-variables). In `native` mode, without `packages`, every P2P and TED OUT initiation answers `503 BTF-2000`. Without `estimates`, every initiation that matches a package answers `503 BTF-2000`. `organizations` is needed because this page sets `MIDAZ_FEE_MODE=native` explicitly: Bank Transfer then makes one read of the Midaz organization list, to check the `/v2` API, before it first uses a set of credentials. Under `auto`, it does not make this read. Without `organizations`, Bank Transfer in single-tenant mode does not start. The examples below use these shell variables. Every UUID is a placeholder. Use the values from your own environment. Bank Transfer reaches the Midaz ledger at `MIDAZ_TRANSACTION_URL`, or at `MIDAZ_BASE_URL` when that is unset. It strips a trailing `/v1` or `/v2` from that address. Strip it in `MIDAZ_LEDGER_URL` too, because the paths below carry the version. ```bash theme={null} # Addresses, as Bank Transfer has them. FEES_BASE_URL="https://plugin-fees.example.com" # FEES_BASE_URL MIDAZ_LEDGER_URL="https://midaz.example.com" # Two different bearers. They are not interchangeable. FEES_BEARER_TOKEN="..." # for plugin-fees MIDAZ_BEARER_TOKEN="..." # for the ledger MIDAZ_ORGANIZATION_ID="3fa85f64-5717-4562-b3fc-2c963f66afa6" MIDAZ_LEDGER_ID="9c858901-8a57-4791-81fe-4a34d4dd8ab5" ``` ## Map a plugin-fees package to a Midaz package *** Midaz refuses a package whose amount range overlaps another package with the same transaction route, segment and `metadataSelector` (error `0199`). It also refuses an exact copy of a package (error `0184`). Midaz counts disabled packages too, so a disabled copy can block a package that you need. The fee rules keep their field names and their JSON shape. Three things change: where the organization goes, where the ledger goes, and what `transactionRoute` holds. | plugin-fees | Midaz | What to do | | - | - | - | | `X-Organization-Id` header | `{organization_id}` in the URL | Send the organization in the path. | | `ledgerId` in the body | `{ledger_id}` in the URL | Send the ledger in the path. | | `transactionRoute` | `transactionRoute` | Replace the value. See [Transaction route](#transaction-route). | | `feeGroupLabel`, `description` | Same fields | Copy. | | `segmentId` | `segmentId` | Copy it or leave it out, as [Package scope](#package-scope) says. Leave it out of every TED IN package. | | `minimumAmount`, `maximumAmount` | Same fields | Copy. | | `waivedAccounts` | `waivedAccounts` | Copy. Both accept account aliases and the `segment:` form. | | `enable` | `enable` | Migrate only packages with `true`. Create each one with `false`. You enable it when you switch to `native`. | | `feeLabel`, `calculationModel`, `referenceAmount`, `priority`, `isDeductibleFrom` of each fee | Same fields | Copy. | | `creditAccount` of each fee | `creditAccount` | Copy. The account must exist in the ledger. Midaz checks it when you create the package. | | `routeFrom`, `routeTo` of each fee | Same fields | Midaz writes the value as the operation route of the fee entry. Use the ID of a Midaz operation route, or leave the field out. In `legacy` mode, Bank Transfer dropped a value that was not a route ID. | | `id`, `createdAt`, `updatedAt`, `deletedAt` | New values | Leave them out. Midaz assigns a new ID. Keep a record of the plugin-fees package that each Midaz package replaces. | | No equivalent | `metadataSelector` (Midaz 4.2.0 or later) | Leave it out, except on a package that prices a [fee context](/en/products/midaz/fees/using-fee-engine#price-a-ted-or-pix-by-a-fee-context), which needs Bank Transfer 3.4.0 or later. | Midaz rejects a field that it does not know. Send none of `ledgerId`, `id`, `createdAt`, `updatedAt` and `deletedAt`. A TED OUT charges its fee on top of the amount. In both modes, Bank Transfer 3.1.0 or later refuses a TED OUT with `422 BTF-3002` when the package that matches it has a fee with `isDeductibleFrom: true`. ### Transaction route plugin-fees compares `transactionRoute` with a name that Bank Transfer sends: `ted_out`, `ted_in` or `p2p`. Midaz compares it with the `routeId` of the transaction, which is the ID of a Midaz transaction route. Midaz accepts a UUID in this field. For each package, use the transaction route that `routing.ledger_bindings` names for the ledger and the transfer type of the package. > [!WARNING] > > Give each Bank Transfer package its transaction route, and do not use those transaction routes in other products. A Midaz package can charge every `/v2` transaction of its ledger that matches its scope, from any product. A package with a `transactionRoute` matches only transactions posted with that route. A package without one can match a transaction on any route. > > A ledger whose binding uses `mode: omit` has no safe package: the only one that can match its transfers has no route, so it charges every `/v2` transaction of the ledger. Give that binding the Midaz transaction route of each transfer type on the Console [Accounting Routes](/en/interfaces/ted-jd/console/bt-accounting-routes) page, and check **Cutover readiness** there. This changes the accounting of every Bank Transfer posting on that ledger. Do it after step 2, once Midaz runs 4.1.0 or later, and before you switch. ### Package scope plugin-fees and Midaz select the package of a transfer in different ways, so an exact copy can charge a different fee. Apply these rules to the enabled packages of each ledger: * **The ledger has one enabled package.** plugin-fees applies it to every transfer in its amount range, P2P, TED OUT and TED IN alike. It ignores the `transactionRoute` and the `segmentId` of that package. In Midaz, create one copy for each transfer type that it charged, each with the transaction route of that type, and without `segmentId`. * **A route has one package.** When the ledger has more than one enabled package, plugin-fees applies the only package of a route to every transfer on that route, inside its amount range. It ignores the `segmentId` of that package. Create the Midaz package without `segmentId`. * **A route has several packages.** plugin-fees then picks by the segment of the sender. A sender with a segment gets only a package with that segment. A sender with no segment gets only a package with no segment. Keep each `segmentId`. Midaz also applies a package with no segment to a sender who has a segment, when no package of that segment covers the amount. If the route has a package with no segment, decide which behavior you want. * When every fee of that package is charged on top of the amount (`isDeductibleFrom: false`), you can keep the plugin-fees behavior. Add `segment:` to the `waivedAccounts` of that package for every segment of the ledger, and for every segment that you create later. Midaz then charges none of its fees to a sender in those segments. * On a fee taken out of the amount, the waiver also exempts a recipient in those segments, so do not use it there. For such a package, the engines cannot match. Decide whether a sender whose segment has no package of its own for that amount pays it in Midaz, or whether you leave it out, so that a sender with no segment pays none of its fees. * **TED IN.** For a TED IN, Bank Transfer sent plugin-fees the segment of the recipient account. Midaz reads the segment from the source accounts, and it skips the external account, which is the only source of a TED IN. So a Midaz package with a `segmentId` never matches a TED IN. Create every TED IN package without `segmentId`. * If the ledger has more than one TED IN package in plugin-fees, plugin-fees charged a recipient with a segment only a package with that segment, and a recipient with no segment only a package with no segment. Midaz cannot see the segment of the recipient, and it applies the packages with no segment to every recipient. Decide the TED IN price that applies to every recipient. * **A package with no route.** When the ledger has more than one enabled package, plugin-fees never applied a package with no route to a Bank Transfer transfer, because Bank Transfer always sends a route. Leave it out. * **Two packages that match.** Midaz selects the package that matches the most constraints. When two packages match equally, Midaz refuses the transaction with error `0198`. At initiation, Bank Transfer answers `422 BTF-2005`. ## Migrate step by step *** **1. Pin the legacy mode** Set `MIDAZ_FEE_MODE=legacy` in the Bank Transfer environment. Bank Transfer 3.0.x ignores the variable, so you can set it ahead of the upgrade. If you deploy with the Helm chart, follow its [upgrade note](https://github.com/LerianStudio/helm/blob/main/charts/plugin-br-bank-transfer/docs/UPGRADE-2.3.md) to set the value and check it before the rollout. Keep `BTF_FEE_ENABLED=true` and the `FEES_*` variables as they are. **2. Upgrade Bank Transfer, then Midaz** Before you upgrade, make sure that no plugin-fees package that a TED OUT can match has a fee with `isDeductibleFrom: true`. [Package scope](#package-scope) says which packages a TED OUT can match. From 3.1.0, Bank Transfer refuses such a TED OUT with `422 BTF-3002` in `legacy` mode too. Upgrade Bank Transfer to 3.1.0 or later. Wait until every Bank Transfer pod runs 3.1.0 or later. An earlier version cannot settle a transfer that Bank Transfer created in `native` mode. Check the log of every pod for `midaz: fee mode resolved` with `feeMode=legacy` and `source=config`. In single-tenant mode, a pod logs it at boot. `source=config` proves that the pin works. Check it while Midaz still runs a version earlier than 4.1.0. There, `auto` also resolves to `legacy`, so a transfer that pays its plugin-fees fee does not prove the pin. Upgrade Midaz to 4.1.0 or later. Make a small transfer. Check that plugin-fees still charges its fee. **3. Recreate each enabled package in Midaz** List the enabled packages of each ledger in plugin-fees. Each answer holds one page, and its `total` counts the items of that page only. Read the next page until a page returns fewer items than `limit`. The list leaves out deleted packages. ```bash theme={null} curl -s "$FEES_BASE_URL/v1/packages?ledgerId=$MIDAZ_LEDGER_ID&enable=true&limit=100&page=1" \ -H "Authorization: Bearer $FEES_BEARER_TOKEN" \ -H "X-Organization-Id: $MIDAZ_ORGANIZATION_ID" ``` Create each package in Midaz with the mapping and the scope rules above. Each fee key must match `^[a-z][a-zA-Z0-9]*$`, so rename any key that does not. Set `enable` to `false`. Keep a list of the packages that you create: you enable exactly these when you switch. This example recreates a flat TED OUT fee. Its `transactionRoute` is the TED OUT transaction route of the ledger binding. ```bash theme={null} curl -s -X POST "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/packages" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -d '{ "feeGroupLabel": "TED OUT fee", "description": "Fee on outgoing TEDs", "transactionRoute": "0199a5c1-3e2f-7b4d-9a8e-5f6d7c8b9a0e", "minimumAmount": "0.01", "maximumAmount": "1000000.00", "fees": { "tedOutFee": { "feeLabel": "TED OUT fee", "calculationModel": { "applicationRule": "flatFee", "calculations": [{ "type": "flat", "value": "5.00" }] }, "referenceAmount": "originalAmount", "priority": 1, "isDeductibleFrom": false, "creditAccount": "fees-revenue" } }, "enable": false }' # -> {"id": "..."} this is the Midaz package ID ``` You can also create the packages on the Console [Fee Packages](/en/products/midaz/fees/console/managing-fee-packages) page. **4. Compare the fees of both engines** For each package, estimate the same transaction in plugin-fees and in Midaz. Compare the fee amounts. They must be equal. Use amounts at both ends of the range of the package, and one amount in the middle. For a package that carries the segment waivers from [Package scope](#package-scope), use a sender outside those segments. Midaz exempts a sender in them by design, and plugin-fees does not. ```bash theme={null} TRANSACTION='{ "send": { "asset": "BRL", "value": "1500.00", "source": { "from": [{ "accountAlias": "@sender", "amount": { "asset": "BRL", "value": "1500.00" } }] }, "distribute": { "to": [{ "accountAlias": "@external/BRL", "amount": { "asset": "BRL", "value": "1500.00" } }] } } }' # plugin-fees: the plugin-fees package ID, and the ledger in the body curl -s -X POST "$FEES_BASE_URL/v1/estimates" \ -H "Authorization: Bearer $FEES_BEARER_TOKEN" \ -H "X-Organization-Id: $MIDAZ_ORGANIZATION_ID" \ -H 'Content-Type: application/json' \ -d '{ "packageId": "0198f1a2-6c3d-7e4f-8a9b-1c2d3e4f5a6b", "ledgerId": "'"$MIDAZ_LEDGER_ID"'", "transaction": '"$TRANSACTION"' }' # Midaz: the Midaz package ID, and the ledger in the URL curl -s -X POST "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/estimates" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -d '{ "packageId": "0199b7d2-4f5e-7a6b-8c9d-2e3f4a5b6c7d", "transaction": '"$TRANSACTION"' }' ``` In the Midaz answer, each fee entry has `"feeLeg": "true"` in its `metadata`. You can also use the Console [Fee Calculator](/en/products/midaz/fees/console/managing-fee-calculations). An estimate calculates the one package that you name. It does not check `transactionRoute`, `segmentId`, or `metadataSelector`, so it does not show which package a transfer gets. The next step tests that. **5. Rehearse the selection in homologation** Run steps 1 to 4 in homologation first, with the same packages. Then test which package each transfer gets, before you switch production: 1. Under `legacy`, call `POST /v1/transfers/initiate` for each case: P2P and TED OUT, from a sender in each segment of the ledger and from a sender with no segment, with amounts at both ends of the range of each package. Record `feeAmount` and `packageAppliedId` from each answer. Do not process these initiations. An initiation posts nothing to Midaz. It writes a `payment_initiations` row that expires at `expiresAt`, keeps a duplicate fingerprint for 300 seconds by default, and sends a `payment_initiation.created` event to your webhook and event consumers. A TED OUT initiation outside the operating window answers `422 BTF-0010`. 2. Switch homologation to `native`, as in the next step. 3. Repeat the same initiations. Compare each `feeAmount`. `packageAppliedId` now names the Midaz package. Check that it is the package that replaces the plugin-fees one. An identical initiation inside that duplicate window answers `409 BTF-0012`, so wait for it to pass. 4. TED IN has no initiation. Under each mode, receive one small TED IN for a recipient in each segment and for a recipient with no segment. Compare the fees. Expect a difference only where [Package scope](#package-scope) says the engines cannot match, and only the one you chose there. Fix every other difference in the Midaz packages, and repeat the cases. **6. Switch Bank Transfer to native** Before the switch, run the P2P and TED OUT initiation cases of step 5 in production, under `legacy`. Use test accounts of your own, one in each segment and one with no segment. Record each `feeAmount`. Step 5 says what an initiation writes. 1. Give the Midaz credentials of Bank Transfer the `packages` (`get`), `estimates` (`post`) and `organizations` (`get`) permissions. 2. Enable each Midaz package that you created in step 3. Send `"enable": true` with [Update a Package](/en/reference/products/midaz/v2/update-package). No initiation tests a TED IN, so first compare the `transactionRoute` of each TED IN package with the **Transaction route** of the `TED_IN` binding of its ledger, on the Console [Accounting Routes](/en/interfaces/ted-jd/console/bt-accounting-routes) page. 3. Set `MIDAZ_FEE_MODE=native`. 4. Restart every Bank Transfer pod. Right after the restart, run the same cases again, with the same accounts. Compare each `feeAmount`, and check each `packageAppliedId`. Expect a difference only where [Package scope](#package-scope) says the engines cannot match, and only the one you chose there. An identical initiation inside the duplicate window answers `409 BTF-0012`, so wait for the window to pass between the two runs. An initiation posts nothing to Midaz, so these cases show a wrong route or segment ID without moving money. If another difference shows, [roll back](#roll-back). Correct the fees or the amount range of a package with Update a Package. Update a Package cannot change `transactionRoute` or `segmentId`, so for a wrong route or segment, create a corrected package with `enable: false`, and delete the wrong one only after the native transfers that used it have finished. This query lists the transfers created in `native` mode since the restart began. Check the fee of each one by hand. ```sql theme={null} SELECT id, type, status, created_at FROM transfers WHERE ledger_fee_mode = 'native' AND created_at >= '2026-10-09 14:00:00-03'; -- just before the restart began ``` New transfers now use Midaz fees. A P2P transfer or TED OUT initiated before the restart, and a TED IN received before it, keep the `legacy` mode until they finish. **7. Check real transfers** Make a small P2P transfer or TED OUT. Check the fee that Bank Transfer shows at initiation. Check the fee that it records on the transfer. Both must match the fee that plugin-fees charged before, except for a difference that you chose in [Package scope](#package-scope). Check the first TED IN that arrives after the switch the same way. In Midaz, the metadata of a transaction that a package charged or exempted has `packageAppliedID`. It is the ID of that Midaz package. **8. Retire plugin-fees** Keep plugin-fees running while this query returns rows. ```sql theme={null} SELECT id, status FROM transfers WHERE type = 'TED_IN' AND ledger_fee_mode = 'legacy' AND status NOT IN ('COMPLETED', 'REJECTED', 'FAILED', 'CANCELLED'); ``` These are TED INs received before the switch. When Bank Transfer resumes one, it asks plugin-fees for its fee. If plugin-fees is stopped, Bank Transfer credits the recipient with no fee. When `fees.fail_closed_default` is `true`, it returns the TED to the sender instead, unless Bank Transfer cannot read that policy. Then back up the plugin-fees MongoDB database, and stop plugin-fees. After that, you cannot [roll back](#roll-back). Keep `MIDAZ_FEE_MODE=native`. Under `auto`, a pod that cannot read the Midaz version starts in `legacy` mode, and `legacy` needs plugin-fees. ## Roll back *** You can return to plugin-fees while plugin-fees still runs with its packages unchanged: 1. Set `MIDAZ_FEE_MODE=legacy`. 2. Restart every Bank Transfer pod. New transfers then use plugin-fees again. This needs `BTF_FEE_ENABLED=true` and the `FEES_*` variables still in place. Transfers created in `native` mode keep that mode. Bank Transfer finishes them on the Midaz `/v2` API, and Midaz charges their fees when it posts them. Keep the Midaz packages enabled until every native transfer has finished. Keep Bank Transfer on 3.1.0 or later while any transfer created in `native` mode is still open. An earlier version settles that transfer on `/v1`, so its fee is not charged or not recorded. ## Console *** The Fees Engine pages of the Console, [Fee Packages](/en/products/midaz/fees/console/managing-fee-packages) and [Fee Calculator](/en/products/midaz/fees/console/managing-fee-calculations), work on Midaz fee packages only. They do not read plugin-fees. ## See also *** * [What is Fees Engine?](/en/products/midaz/fees/fees-engine-overview) * [Using Fees Engine](/en/products/midaz/fees/using-fee-engine) * [Estimate transaction fees](/en/reference/products/midaz/v2/estimate-fee-calculation) * [Bank Transfer configuration](/en/interfaces/ted-jd/ted-configuration) * [Bank Transfer environment variables](/en/interfaces/ted-jd/ted-environment-variables) # Using account plans Source: https://docs.lerian.studio/en/products/midaz/fees/using-account-plans Create an account plan, assign it to an account, read the fee of each transaction and the usage of the month, and charge service fees. This guide creates an account plan with one transaction fee and one service fee, and uses it on one account. [Account plans](/en/products/midaz/fees/account-plans) gives the rules that the steps follow. ## Before you start *** You need: * A ledger and an account for the customer, here with the alias `@customer_001`. * An account that receives the fees, here with the alias `@fee_revenue`. * The `account-plans` and `fee-charges` permissions on Midaz. See [Permissions](/en/products/midaz/fees/account-plans#permissions). The examples use a ledger without route validation, where a transaction fee selects transactions by `scheme`. On a ledger with route validation, give each fee an `accounting` block too. See [Accounting routes](/en/products/midaz/fees/account-plans#accounting-routes). The examples use these shell variables. Every UUID is a placeholder. Use the values from your own environment. ```bash theme={null} MIDAZ_LEDGER_URL="https://midaz.example.com" MIDAZ_BEARER_TOKEN="..." MIDAZ_ORGANIZATION_ID="3fa85f64-5717-4562-b3fc-2c963f66afa6" MIDAZ_LEDGER_ID="9c858901-8a57-4791-81fe-4a34d4dd8ab5" MIDAZ_ACCOUNT_ID="0199a5c1-3e2f-7b4d-9a8e-5f6d7c8b9a0e" # the account of @customer_001 ``` **1. Create the account plan** Send the plan to [Create an account plan](/en/reference/products/midaz/v2/create-an-account-plan). The fee `tedSent` charges 7.90 for each TED that the account sends, after 2 free TEDs in the month. The fee `paperStatement` charges 3 for each paper statement, after 1 free statement in the month. ```bash theme={null} curl -s -X POST "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/account-plans" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -d '{ "label": "Essential PF", "description": "Essential plan for individuals", "enable": true, "timezone": "America/Sao_Paulo", "fees": { "tedSent": { "feeLabel": "TED sent", "trigger": { "type": "transaction", "schemes": ["TED"], "direction": "sent" }, "calculationModel": { "applicationRule": "flatFee", "calculations": [{ "type": "flat", "value": "7.90" }] }, "creditAccount": "@fee_revenue", "freeQuota": 2 }, "paperStatement": { "feeLabel": "Paper statement", "trigger": { "type": "service", "serviceCode": "PAPER_STATEMENT" }, "calculationModel": { "applicationRule": "flatFee", "calculations": [{ "type": "flat", "value": "3" }] }, "creditAccount": "@fee_revenue", "freeQuota": 1 } } }' ``` Midaz answers `201` with the plan and its version 1. It fills in the defaults `referenceAmount` and `period`: ```json theme={null} { "id": "019a3b2c-1d4e-7f60-8a9b-0c1d2e3f4a5b", "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "ledgerId": "9c858901-8a57-4791-81fe-4a34d4dd8ab5", "label": "Essential PF", "description": "Essential plan for individuals", "enable": true, "timezone": "America/Sao_Paulo", "currentVersion": 1, "version": 1, "effectiveFrom": "2026-10-30T13:00:00Z", "fees": { "paperStatement": { "feeLabel": "Paper statement", "trigger": { "type": "service", "serviceCode": "PAPER_STATEMENT" }, "calculationModel": { "applicationRule": "flatFee", "calculations": [{ "type": "flat", "value": "3" }] }, "referenceAmount": "originalAmount", "creditAccount": "@fee_revenue", "freeQuota": 1, "period": "monthly" }, "tedSent": { "feeLabel": "TED sent", "trigger": { "type": "transaction", "schemes": ["TED"], "direction": "sent" }, "calculationModel": { "applicationRule": "flatFee", "calculations": [{ "type": "flat", "value": "7.90" }] }, "referenceAmount": "originalAmount", "creditAccount": "@fee_revenue", "freeQuota": 2, "period": "monthly" } }, "createdAt": "2026-10-30T13:00:00Z", "updatedAt": "2026-10-30T13:00:00Z" } ``` Keep the `id` of the plan: ```bash theme={null} MIDAZ_ACCOUNT_PLAN_ID="019a3b2c-1d4e-7f60-8a9b-0c1d2e3f4a5b" ``` **2. Assign the plan to the account** Send the plan to [Assign an account plan to an account](/en/reference/products/midaz/v2/assign-an-account-plan-to-an-account): ```bash theme={null} curl -s -X PUT "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/accounts/$MIDAZ_ACCOUNT_ID/account-plan" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -d "{ \"accountPlanId\": \"$MIDAZ_ACCOUNT_PLAN_ID\" }" ``` Midaz answers `200` with the active assignment: ```json theme={null} { "id": "019a3b2d-5e6f-7a80-9b1c-2d3e4f5a6b7c", "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "ledgerId": "9c858901-8a57-4791-81fe-4a34d4dd8ab5", "accountId": "0199a5c1-3e2f-7b4d-9a8e-5f6d7c8b9a0e", "accountAlias": "@customer_001", "accountPlanId": "019a3b2c-1d4e-7f60-8a9b-0c1d2e3f4a5b", "startedAt": "2026-10-30T13:05:00Z", "endedAt": null } ``` From now on, the fee packages of the ledger do not charge `@customer_001` on the `/v2` transactions it sends. **3. Send a transaction and read its fee** Send a TED from the account with [Create a Transaction using the v2 direct model](/en/reference/products/midaz/v2/create-transaction-direct). The `scheme` is `TED`, so the fee `tedSent` matches: ```bash theme={null} curl -s -X POST "$MIDAZ_LEDGER_URL/v2/transactions/direct" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -H 'X-Idempotency: ted-0001' \ -d "{ \"description\": \"TED to another bank\", \"asset\": \"BRL\", \"amount\": \"100\", \"scheme\": \"TED\", \"debits\": [ { \"alias\": \"@customer_001\", \"organizationId\": \"$MIDAZ_ORGANIZATION_ID\", \"ledgerId\": \"$MIDAZ_LEDGER_ID\", \"amount\": \"100\" } ], \"credits\": [ { \"alias\": \"@ted_settlement\", \"organizationId\": \"$MIDAZ_ORGANIZATION_ID\", \"ledgerId\": \"$MIDAZ_LEDGER_ID\", \"amount\": \"100\" } ] }" ``` The `201` response has `accountPlanFees`. The first TED of the month uses a free unit: ```json theme={null} "accountPlanFees": [ { "accountId": "0199a5c1-3e2f-7b4d-9a8e-5f6d7c8b9a0e", "accountAlias": "@customer_001", "accountPlanId": "019a3b2c-1d4e-7f60-8a9b-0c1d2e3f4a5b", "accountPlanVersion": 1, "feeKey": "tedSent", "outcome": "quota", "unit": 1, "freeQuota": 2, "amount": "0" } ] ``` The third TED of the month is past the free quota. Its item has `"outcome": "charged"`, `"unit": 3`, and `"amount": "7.9"`. The account sends 107.9: the 100 of the TED and the fee, which goes to `@fee_revenue`. A transaction with another `scheme`, or without one, gets `"outcome": "no_match"`. The account pays no fee on it. Keep `accountPlanFees` from the create response. The reads of the transaction do not return it. **4. Read the usage of the month** Read the units of the account with [Get the account plan usage of an account](/en/reference/products/midaz/v2/get-the-account-plan-usage-of-an-account): ```bash theme={null} curl -s "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/accounts/$MIDAZ_ACCOUNT_ID/account-plan/usage?period=2026-10" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" ``` After three TEDs, the response is: ```json theme={null} { "accountId": "0199a5c1-3e2f-7b4d-9a8e-5f6d7c8b9a0e", "accountPlanId": "019a3b2c-1d4e-7f60-8a9b-0c1d2e3f4a5b", "accountPlanVersion": 1, "period": { "label": "2026-10", "start": "2026-10-01T03:00:00Z", "end": "2026-11-01T03:00:00Z" }, "items": [ { "feeKey": "paperStatement", "trigger": "fee:paperStatement", "period": { "label": "2026-10", "start": "2026-10-01T03:00:00Z", "end": "2026-11-01T03:00:00Z" }, "freeQuota": 1, "used": 0, "remaining": 1, "charged": 0 }, { "feeKey": "tedSent", "trigger": "fee:tedSent:TED", "period": { "label": "2026-10", "start": "2026-10-01T03:00:00Z", "end": "2026-11-01T03:00:00Z" }, "freeQuota": 2, "used": 3, "remaining": 0, "charged": 1 } ] } ``` `period.start` and `period.end` are the month in the plan timezone, in UTC. **5. Charge service fees** Charge two paper statements with [Charge service fees to an account](/en/reference/products/midaz/v2/charge-service-fees-to-an-account). Send an `X-Idempotency` key, and send the same key when you retry the same charge: ```bash theme={null} curl -s -X POST "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/accounts/$MIDAZ_ACCOUNT_ID/fee-charges" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -H 'X-Idempotency: statements-2026-10' \ -d '{ "serviceCodes": ["PAPER_STATEMENT", "PAPER_STATEMENT"], "description": "Paper statements of October" }' ``` Midaz answers `201`. The first statement uses the free unit, and the second costs 3: ```json theme={null} { "id": "019a3b30-7c8d-7e90-a1b2-c3d4e5f6a7b8", "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "ledgerId": "9c858901-8a57-4791-81fe-4a34d4dd8ab5", "accountId": "0199a5c1-3e2f-7b4d-9a8e-5f6d7c8b9a0e", "accountPlanId": "019a3b2c-1d4e-7f60-8a9b-0c1d2e3f4a5b", "accountPlanVersion": 1, "description": "Paper statements of October", "items": [ { "serviceCode": "PAPER_STATEMENT", "feeKey": "paperStatement", "outcome": "quota", "unit": 1, "freeQuota": 1, "amount": "0" }, { "serviceCode": "PAPER_STATEMENT", "feeKey": "paperStatement", "outcome": "charged", "unit": 2, "freeQuota": 1, "amount": "3" } ], "totalAmount": "3", "assetCode": "BRL", "feeTransactionIds": ["019a3b30-8d9e-7fa0-b2c3-d4e5f6a7b8c9"], "period": "2026-10", "createdAt": "2026-10-30T14:00:00Z" } ``` The fee transaction debits 3 from `@customer_001` and credits it to `@fee_revenue`. To undo the charge in the same month, revert that transaction. **6. Create a new version** Raise the free TEDs to 5 from November. Send only the field that changes to [Update an account plan](/en/reference/products/midaz/v2/update-an-account-plan): ```bash theme={null} curl -s -X PATCH "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/account-plans/$MIDAZ_ACCOUNT_PLAN_ID" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" \ -H 'Content-Type: application/json' \ -d '{ "fees": { "tedSent": { "freeQuota": 5 } }, "effectiveFrom": "2026-11-01T03:00:00Z" }' ``` Midaz creates version 2 with both fees, and `tedSent` has `freeQuota: 5`. Before November 1 in the plan timezone, the response and the transactions use version 1, and `currentVersion` is `2`. **7. End the assignment** To take the account off the plan, use [End the account plan assignment of an account](/en/reference/products/midaz/v2/end-the-account-plan-assignment-of-an-account): ```bash theme={null} curl -s -X DELETE "$MIDAZ_LEDGER_URL/v2/organizations/$MIDAZ_ORGANIZATION_ID/ledgers/$MIDAZ_LEDGER_ID/accounts/$MIDAZ_ACCOUNT_ID/account-plan" \ -H "Authorization: Bearer $MIDAZ_BEARER_TOKEN" ``` Midaz answers `204`. The fee packages of the ledger apply to the account again. # Using Fees Engine Source: https://docs.lerian.studio/en/products/midaz/fees/using-fee-engine Use the Fees Engine to apply per-transaction fee packages and per-period billing packages that match your ledgers, segments, and transaction routes. Fees Engine applies per-transaction fees and calculates periodic billing charges. This guide covers both workflows: fee packages (per-transaction) and billing packages (per-period). > [!TIP] > > Fee packages apply charges at transaction time. Billing packages calculate charges over a period (daily, weekly, or monthly) for your orchestrator to execute. You can use both simultaneously. ## Fee packages: per-transaction workflow *** Fee packages apply charges synchronously when you create a v2 transaction. This section shows the process, from fee setup to results. ### Step 1 - Create your fee packages First, set up **fee packages** that define how the engine applies fees. Use the [Create a Package](/en/reference/products/midaz/v2/create-package) endpoint. Each package contains a set of fee rules and matching criteria. You can tailor packages to different ledgers, segments, and transaction routes with these fields: * **transactionRoute** - The ID of a transaction route, when you need route-level matching. * **segmentId** - The ID of the segment the source accounts belong to, when you need segment-level matching. * **metadataSelector** - Metadata pairs that the transaction must carry, when you need metadata-level matching. * **Ledger scope** - The request URL identifies which ledger records the transaction; do not send `ledgerId` in the package body. * **Minimum** and **maximum** amount - Thresholds for fee application. * **routeFrom** / **routeTo** - Define how each fee moves across accounting flows. These fields let you apply distinct fees per scenario, from account-based setups to value-based. **Managing Packages** The following endpoints are also available for you to manage the packages: * [List Packages](/en/reference/products/midaz/v2/get-all-packages) - List all packages created. * [Retrieve a Package](/en/reference/products/midaz/v2/get-package-by-id) - Retrieve information of a specific package. * [Update a Package](/en/reference/products/midaz/v2/update-package) - Update the information of a specific package. * [Delete a Package](/en/reference/products/midaz/v2/delete-package) - Soft-delete a package. ### (optional) Step 2 - Run an estimation To preview how a fee package behaves before you commit a real transaction, use the [Estimate Transaction Fees](/en/reference/products/midaz/v2/estimate-fee-calculation) endpoint. This estimation helps validate: * Which fee rules apply. * How the package will behave with the given values. * Whether any exemptions apply. ### Step 3 - Create a transaction Once you set the packages, create the transaction through the v2 transaction API, for example with the [Create a Transaction using the v2 direct model](/en/reference/products/midaz/v2/create-transaction-direct) endpoint. Only v2 transactions apply fees, including the direct and hold items of a v2 batch. To match a route-scoped package, send the transaction route ID in `routeId`. Midaz reads the segment from the source accounts. ### Step 4 - Fees Engine evaluates the packages Fees Engine runs in-process when Midaz creates the transaction. It evaluates whether a package applies, based on: * **transactionRoute**, when configured * **segmentId**, when configured * **metadataSelector**, when configured * **Ledger scope from the request URL** * **Minimum** and **maximum** amount * **waivedAccounts**, when configured for fee exemptions > [!NOTE] > > Fees Engine selects at most one package per transaction: the most specific match. Each `metadataSelector` pair makes a package more specific. When two packages match equally, Midaz refuses the transaction with error `0198`. A source account with an active [account plan](/en/products/midaz/fees/account-plans) pays the fees of its plan, and the package does not charge it. ### Step 5 - Check for exemptions The system checks: * If no matching package covers the transaction amount. * If every source account is waived. If either condition is true, Fees Engine applies no fees and the transaction proceeds normally. A fee whose calculation totals zero adds no fee leg, for example a fee set to `0` in a package for an amount range. When a fee set to `0` leaves the transaction with no fee leg, the transaction metadata records `feeExemption` with the reason `zero_fee_amount`, and `packageAppliedID` names the package. The External Account (`@external/`) that Midaz adds to a cross-ledger transaction never pays a fee. ### Step 6 - Fee calculation and application If a package applies, Fees Engine: * Calculates fee values based on the selected `applicationRule`. * Applies fees proportionally across accounts if needed. * Uses `isDeductibleFrom` to set whether it adds or deducts the fee. * Routes fees to the correct `creditAccount` with the configured `routeFrom` and `routeTo`. * Returns the full transaction result along with the `packageAppliedID` in the metadata. ### Step 7 - Ledger updates Once Fees Engine calculates the fees, the **Transactions** component takes over. It processes: * Debits from source accounts * Credits to fee destinations * Fee breakdown per route and account The ledger stores every movement for full traceability and auditability. ### Step 8 - Review and confirm After execution, you can: * Inspect the final transaction and amounts per account. * Confirm which fee package applied. * Verify all fee movements via metadata and ledger records. ## Price a TED or Pix by a fee context *** A fee context is a label that you choose for an outbound transfer, for example `ted_salario`. A fee package that selects on the label prices the transfer. It needs Midaz 4.2.0 or later, with Bank Transfer 3.4.0 or later for TED and Pix JD 1.5.0 or later for Pix. Earlier versions of the two plugins refuse the field with `400`. Send the label in `feeContext`, at the top level of the request body of [POST /v1/transfers/initiate](/en/reference/interfaces/ted-jd/initiate-transfer) for TED and P2P, or of [POST /v1/transactions](/en/reference/interfaces/pix-jd/create-transaction) for Pix. The label is a lowercase letter, then up to 49 lowercase letters, digits or underscores. Never put personal data in it. A read of the transfer returns `feeContext`. ### Create the package for the label Create the package on the ledger of the payer, with `metadataSelector` set to `{"feeContext": "