Blnk Documentation

repository·main·Indexed 19 days ago

https://github.com/blnkfinance/blnk

Blnk is an open-source, double-entry financial ledger for developers building transaction-heavy fintech products such as wallets, banking systems, and lending platforms. It provides core capabilities for ledger management (balance monitoring, historical tracking, and overdrafts), reconciliation of external records, and identity management with PII tokenization. The system includes a tamper-evident hash chain for ledger immutability and a CLI for server management, migrations, and chain verification.

Tokens
23.2K
Snippets
100
Records
125
Agent score
66%

What's inside Blnk

  1. Core capabilities of Blnk

    main

    Blnk provides three primary functional pillars for financial applications:

    Ledger

    An open-source double-entry ledger for managing balances and recording transaction workflows. Key features include:

    • Balance monitoring and snapshots.
    • Historical balance tracking.
    • Inflight transactions and scheduling.
    • Overdraft management.
    • Bulk transaction workflows.

    Reconciliation

    Tools to match external records (e.g., bank statements or payment processor exports) against internal ledger records using custom matching rules and reconciliation strategies.

    Identity Management

    Capabilities to create and manage identities, tokenize PII (Personally Identifiable Information), and link identities directly to balances and transactions.

  2. Common use cases for Blnk

    main

    Developers use Blnk to build various financial workflows, including:

    • Wallet management
    • Deposits and withdrawals
    • Order exchange (e.g., crypto)
    • Lending products
    • Loyalty points systems
    • AI billing
    • Escrow applications
  3. Understand Blnk metrics export modes

    main

    Blnk supports two modes for exporting metrics:

    • Pull (Prometheus): Prometheus scrapes the /metrics endpoint. This is always active when observability is enabled.
    • Push (OTLP HTTP): Blnk periodically pushes metrics to an OpenTelemetry Collector. This mode is activated when OTEL_EXPORTER_OTLP_METRICS_ENDPOINT or OTEL_EXPORTER_OTLP_ENDPOINT is set.
  4. Configure authentication for secure metrics endpoints

    main

    If server.secure is enabled, the /metrics endpoint requires a bearer token.

    1. Define the token in blnk.json using the key "metrics_bearer_token": "<your-token>" or via the environment variable BLNK_METRICS_BEARER_TOKEN.
    2. Configure your Prometheus scraper to include this token in the authorization header.

    If secure mode is enabled but no token is configured, the endpoint will return 403 Forbidden.

    scrape_configs:
      - job_name: 'blnk-server'
        authorization:
          type: Bearer
          credentials: '<your-token>'
        static_configs:
          - targets: ['server:5001']
  5. Enable and access Blnk metrics

    main

    Blnk exposes OpenTelemetry metrics via a Prometheus-compatible /metrics endpoint. To use metrics, you must first enable observability in your configuration.

    1. Enable Observability

    Set "enable_observability": true in your blnk.json file, or set the environment variable BLNK_ENABLE_OBSERVABILITY=true.

    2. Access Endpoints

    • Server: GET /metrics on the API port (default 5001).
    • Worker: GET /metrics on the monitoring port (default 5004).
    {
      "enable_observability": true
    }
  6. Get started with Blnk

    main

    Blnk is an open-source, double-entry ledger designed for fintech applications like wallets, banking infrastructure, and payment systems. To begin using Blnk, follow these steps:

    1. Installation: You can either install Blnk locally or deploy a sandbox on Blnk Cloud.
    2. Initial Setup: Follow the tutorial to create your first ledger, balance, and transaction.
    3. Learning: Explore existing Blnk tutorials or consult the API reference for detailed technical specifications.
  7. Understand Hook response validation logic

    main

    Blnk's hook execution engine follows specific rules to determine if a webhook attempt was successful:

    1. HTTP Status Codes: A status code in the 2xx range is generally treated as success.
    2. Empty Responses: If the response body is empty and the status is 2xx, the hook is marked as successful.
    3. Non-JSON Responses: If the response is not valid JSON but the status is 2xx, the hook is marked as successful (with a warning logged).
    4. JSON Responses: If the response is valid JSON, Blnk attempts to unmarshal it into a HookResponse object. The execution is only considered successful if the Success field in the JSON is true.
    5. Error Handling: If the status is 4xx or 5xx, or if the JSON response contains "success": false, the hook is marked as failed.
  8. Synchronous vs Asynchronous Transaction Processing

    main

    The QueueTransaction method supports two modes of operation controlled by the SkipQueue field on the model.Transaction object:

    Synchronous Mode (SkipQueue: true)

    When SkipQueue is set to true, the transaction is processed immediately within the same call. The method calls processTxns and RecordTransaction directly. This is useful when you need immediate confirmation of the transaction's persistence and status before proceeding.

    Asynchronous Mode (SkipQueue: false)

    When SkipQueue is false (the default), the transaction is processed in a background goroutine via processTransactionAsync. This mode is designed for high-throughput scenarios where the caller should not be blocked by the processing and enqueuing logic. The background worker uses a semaphore (asyncTxnSemaphore) to manage concurrency and clones the transaction to prevent race conditions with the caller.

  9. Verify Blnk webhook signatures

    main

    When receiving webhooks from Blnk, you must verify the authenticity of the request using the provided signature. Blnk uses an HMAC-SHA256 signature based on a shared secret.

    Signature Construction:

    1. Obtain the X-Blnk-Timestamp from the request header.
    2. Retrieve the raw JSON request body.
    3. Create a string in the format: {timestamp}.{payload}.
    4. Compute the HMAC-SHA256 signature of that string using your Server.SecretKey.
    5. Compare your computed signature with the value in the X-Blnk-Signature header.

    Required Headers:

    • X-Blnk-Signature: The HMAC-SHA256 signature.
    • X-Blnk-Timestamp: The timestamp used to generate the signature.
    • X-Hook-ID: The unique identifier for the hook.
    • X-Hook-Type: The type of hook being executed.
    • Content-Type: Must be application/json.
  10. Handle split transactions for precision or logic

    main

    Blnk can automatically split a single transaction into multiple transactions using the SplitTransactionPrecise method on the model.Transaction type.

    When QueueTransaction is called, it invokes handleSplitTransactions. If the transaction is splittable, the resulting slice of transactions is processed. Each split transaction is assigned a new reference following the pattern {original_reference}_{index} (e.g., ref_1, ref_2) and maintains a link to the original via the ParentTransaction field.

  11. Understand the queued transaction recovery logic

    main

    The recovery process follows these rules to ensure ledger integrity:

    1. Thresholding: Only transactions stuck longer than the configured stuckThreshold (or the provided threshold in manual recovery) are processed.
    2. Retry Limits: Each transaction tracks its own recovery_attempts in its metadata. If attempts > maxRecoveryAttempts (default 3), the transaction is rejected with the error exceeded max queued recovery attempts.
    3. Atomic Groups: For atomic transactions, the processor checks if any sibling in the atomic group has already been REJECTED. If so, the stuck transaction is skipped to maintain group consistency.
    4. Execution Path: Recovered transactions are replayed through the shared queued processing path. The processor detects if the transaction requires 'hot-lane' execution by inspecting its metadata via hotpairs.QueueLaneFromMetadata.
    5. Idempotency: If a recovery attempt fails because the reference is already used (IsDuplicateReferenceError), the processor treats it as successfully processed and updates the metadata to already_processed to prevent further retries.
  12. Configure matching rule criteria and drift

    main

    When defining MatchingCriteria, ensure the AllowableDrift is appropriate for the field and operator:

    • amount (with equals): Drift is a fraction of the amount (e.g., 0.01 allows a 1% deviation).
    • date (with equals): Drift is measured in seconds.
    • description/reference/currency (with contains): Uses Levenshtein distance for fuzzy string matching based on a percentage drift.