### Verify Blnk CLI installation Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Use this command to verify the installation and list available CLI commands. ```bash blnk --help ``` -------------------------------- ### Create Transactions Examples Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/transactions.md Demonstrates creating simple, inflight, and atomic split transactions. ```typescript // Simple transaction const response = await blnk.Transactions.create({ amount: 100, precision: 100, reference: 'ref_001', description: 'Payment from Alice to Bob', currency: 'USD', source: 'bln_alice_id', destination: 'bln_bob_id' }); // Inflight transaction (temporary hold) const inflightResponse = await blnk.Transactions.create({ amount: 500, precision: 100, reference: 'ref_inflight_001', description: 'Hold pending approval', currency: 'USD', source: 'bln_source_id', destination: 'bln_dest_id', inflight: true, inflight_expiry_date: new Date(Date.now() + 24 * 60 * 60 * 1000), allow_overdraft: false }); // Atomic split transaction const splitResponse = await blnk.Transactions.create({ amount: 1000, precision: 100, reference: 'ref_split_001', description: 'Fee split', currency: 'USD', source: '@FundingPool', destinations: [ { identifier: 'bln_fee', distribution: '240.23' }, { identifier: 'bln_recipient', distribution: 'left' } ], atomic: true }); ``` -------------------------------- ### Create ledger usage example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/ledgers.md Demonstrates creating a ledger with a name and custom metadata. ```typescript const response = await blnk.Ledgers.create({ name: 'Customer Savings Account', meta_data: { project_owner: 'MY_APP', department: 'finance' } }); if (response.status === 201) { console.log('Ledger created:', response.data?.ledger_id); } else { console.error('Failed to create ledger:', response.message); } ``` -------------------------------- ### Install Blnk TypeScript SDK Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/getting-started.md Install the package via npm to begin using the SDK in your Node.js project. ```bash npm install @blnkfinance/blnk-typescript ``` -------------------------------- ### Launch Blnk Server Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Start the Blnk server instance using Docker Compose. ```bash docker compose up ``` -------------------------------- ### Create Balance Monitors Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Examples for creating various balance monitors using the blnk.BalanceMonitor.create method. ```typescript const monitor = await blnk.BalanceMonitor.create({ balance_id: 'bln_savings_account', condition: { field: 'balance', operator: '<', value: 1000, precision: 100 }, description: 'Savings account low balance alert', call_back_url: 'https://api.myapp.com/alerts/low-balance' }); ``` ```typescript const monitor = await blnk.BalanceMonitor.create({ balance_id: 'bln_transaction_account', condition: { field: 'debit_balance', operator: '>', value: 10000, precision: 100 }, description: 'High transaction volume alert', call_back_url: 'https://api.myapp.com/alerts/high-volume' }); ``` ```typescript const monitor = await blnk.BalanceMonitor.create({ balance_id: 'bln_escrow_account', condition: { field: 'inflight_balance', operator: '>', value: 5000, precision: 100 }, description: 'Escrow inflight balance threshold', call_back_url: 'https://api.myapp.com/alerts/escrow' }); ``` ```typescript const monitor = await blnk.BalanceMonitor.create({ balance_id: 'bln_some_account', condition: { field: 'balance', operator: '=', value: 0, precision: 100 }, description: 'Account exhausted alert' }); ``` -------------------------------- ### POST /reconciliation/start Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Starts a batch reconciliation process from a previously uploaded file. ```APIDOC ## POST /reconciliation/start ### Description Starts a batch reconciliation process from a prior upload. ### Method POST ### Endpoint /reconciliation/start ``` -------------------------------- ### run Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/reconciliation.md Starts a batch reconciliation process based on a prior file upload. ```APIDOC ## async run(data: RunReconData) ### Description Starts batch reconciliation from a prior upload. ### Parameters - **data.upload_id** (string) - Required - Upload ID from prior upload() call - **data.strategy** (Strategy) - Required - 'one_to_one', 'one_to_many', or 'many_to_one' - **data.dry_run** (boolean) - Required - Preview results without persisting - **data.grouping_criteria** (CriteriaField) - Required - Field to group by ('amount', 'currency', 'reference', 'description', 'date') - **data.matching_rule_ids** (string[]) - Required - Rule IDs to apply ### Returns `ApiResponse` — On success (status 201), `data.reconciliation_id` identifies the run. ``` -------------------------------- ### Create identity examples Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/identities.md Demonstrates creating minimal individuals, full individual profiles, and organization records. ```typescript // Minimal individual const response = await blnk.Identity.create({ identity_type: 'individual' }); // Full individual with details const fullResponse = await blnk.Identity.create({ identity_id: 'idt_11111111-1111-4111-8111-111111111111', identity_type: 'individual', first_name: 'Jane', last_name: 'Doe', gender: 'female', dob: '1990-01-15T00:00:00Z', email_address: 'jane@example.com', phone_number: '+1234567890', nationality: 'US', street: '123 Main St', country: 'USA', state: 'NY', post_code: '10001', city: 'New York' }); // Organization const orgResponse = await blnk.Identity.create({ identity_type: 'organization', organization_name: 'Acme Inc.', country: 'USA' }); ``` -------------------------------- ### List All Balance Monitors in TypeScript Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Defines the method signature and provides an example of retrieving all configured monitors. ```typescript async list(): Promise> ``` ```typescript const response = await blnk.BalanceMonitor.list(); if (response.status === 200) { response.data?.forEach(monitor => { console.log(`Monitor ${monitor.monitor_id}: ${monitor.description}`); }); } ``` -------------------------------- ### Create a Balance Monitor in TypeScript Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Defines the method signature and provides an example of creating a monitor with a specific threshold condition. ```typescript async create( data: MonitorData ): Promise> ``` ```typescript const response = await blnk.BalanceMonitor.create({ balance_id: 'bln_5ce86029-3c2e-4e2a-aae2-7fb931ca4c4f', condition: { field: 'balance', operator: '<', value: 100, precision: 100 }, description: 'Alert when balance drops below $100', call_back_url: 'https://api.example.com/balance-alert' }); if (response.status === 201) { console.log('Monitor created:', response.data?.monitor_id); } ``` -------------------------------- ### Get ledger usage example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/ledgers.md Retrieves ledger details using a specific ledger ID. ```typescript const response = await blnk.Ledgers.get('ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc'); if (response.status === 200) { console.log('Ledger name:', response.data?.name); } ``` -------------------------------- ### Retrieve a Balance Monitor in TypeScript Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Defines the method signature and provides an example of fetching a specific monitor by its ID. ```typescript async get( id: string ): Promise> ``` ```typescript const response = await blnk.BalanceMonitor.get('monitor_12345'); console.log('Monitor condition:', response.data?.condition); ``` -------------------------------- ### Update a Balance Monitor in TypeScript Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Defines the method signature and provides an example of updating an existing monitor's configuration. ```typescript async update( id: string, data: MonitorData ): Promise> ``` ```typescript const response = await blnk.BalanceMonitor.update('monitor_12345', { balance_id: 'bln_5ce86029-3c2e-4e2a-aae2-7fb931ca4c4f', condition: { field: 'balance', operator: '<', value: 50, // Changed threshold precision: 100 }, description: 'Alert when balance drops below $50', call_back_url: 'https://api.example.com/balance-alert' }); ``` -------------------------------- ### Error Handling Patterns Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/errors.md Examples of how to handle various API error responses (400, 401, 403, 404, 408) when using the Blnk SDK. ```APIDOC ## Error Handling ### Validation Errors (400) Occurs when there are missing required fields, invalid data types, or business rule violations. ### Authentication Errors (401) Occurs when the provided API key is invalid or missing. ### Permission Errors (403) Occurs when the operation requires a master key or specific scopes that the current API key lacks. ### Not Found Errors (404) Occurs when the requested resource does not exist. ### Timeout Errors (408) Occurs when the request exceeds the configured timeout duration. ``` -------------------------------- ### Implement Error Handling Pattern Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/errors.md Example of checking the response status and accessing error details after an SDK method call. ```typescript const response = await blnk.Ledgers.create({ name: 'Test Ledger' }); if (response.status !== 201) { // Handle error console.error(`Error: ${response.message}`); if (response.error) { console.error(`Code: ${response.error.code}`); console.error(`Details:`, response.error.details); } } else { // Success const ledger = response.data; } ``` -------------------------------- ### Start batch reconciliation in Blnk Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Initiates a batch reconciliation process based on a previously uploaded file. ```typescript const { Reconciliation } = blnk; const started = await Reconciliation.run({ upload_id: upload.data!.upload_id, strategy: 'one_to_one', dry_run: true, grouping_criteria: 'amount', matching_rule_ids: [rule.data!.rule_id], }); // started.data?.reconciliation_id — use with Reconciliation.get() or webhooks ``` -------------------------------- ### List tokenized fields example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/identities.md Retrieves the list of PII fields currently tokenized for a given identity. ```typescript const response = await blnk.Identity.getTokenizedFields('idt_3b63c8da-af29-4cc3-ad38-df17d87456e6'); // response.data?.tokenized_fields = ["FirstName", "EmailAddress"] ``` -------------------------------- ### Delete a Balance Monitor in TypeScript Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Defines the method signature and provides an example of removing a monitor by ID. Requires Core 0.15.0 or higher. ```typescript async delete( id: string ): Promise> ``` ```typescript const response = await blnk.BalanceMonitor.delete('monitor_12345'); // response.data?.message = "BalanceMonitor deleted successfully" ``` -------------------------------- ### Get Transaction Example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/transactions.md Retrieves a specific transaction using its unique ID. ```typescript const response = await blnk.Transactions.get('txn_04551509-d7d3-4eab-a1fd-2eb12809b5a4'); console.log('Status:', response.data?.status); ``` -------------------------------- ### BlnkInit Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Initializes the Blnk SDK instance with an API key and configuration options. ```APIDOC ## BlnkInit ### Description Initializes the Blnk SDK instance, returning an object with accessors for services like Ledgers and Transactions. ### Signature `BlnkInit(apiKey: string, options: BlnkClientOptions): Blnk` ### Parameters - **apiKey** (string) - Required - API key for authentication. Pass an empty string for unauthenticated requests. - **options** (BlnkClientOptions) - Required - Configuration object containing connection and retry settings. ### BlnkClientOptions - **baseUrl** (string) - Required - Base URL of the Blnk Core server. - **timeout** (number) - Optional - Request timeout in milliseconds (default: 10000). - **retryCount** (number) - Optional - Total request attempts for idempotent GET requests (default: 1). - **retryDelayMs** (number) - Optional - Base delay between retries in milliseconds (default: 2000). - **logger** (BlnkLogger) - Optional - Custom logger implementation. ``` -------------------------------- ### Get Transaction Method Definition Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/transactions.md The signature for the get method used to retrieve transaction details by ID. ```typescript async get>( transactionId: string ): Promise | null>> ``` -------------------------------- ### Initialize Blnk SDK Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/getting-started.md Configure the SDK with your API key and server base URL. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('your-api-key', { baseUrl: 'http://localhost:5001' }); ``` -------------------------------- ### Delete identity example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/identities.md Deletes an identity record by its ID. ```typescript const response = await blnk.Identity.delete('idt_3b63c8da-af29-4cc3-ad38-df17d87456e6'); ``` -------------------------------- ### get Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/reconciliation.md Retrieves the current status and results of a specific reconciliation run. ```APIDOC ## async get(id: string) ### Description Retrieves reconciliation status and results. ### Parameters - **id** (string) - Required - Reconciliation ID ### Returns `ApiResponse` — On success, `data` contains status, match counts, and timestamps. ``` -------------------------------- ### Get Webhook Details Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Retrieves details for a specific webhook using its ID. ```typescript async get( id: string ): Promise> ``` ```typescript const response = await blnk.Hooks.get('hook_id'); console.log('Webhook URL:', response.data?.url); console.log('Last success:', response.data?.last_success); ``` -------------------------------- ### Initialize SDK with Environment Variables Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Manually configure the Blnk SDK instance by reading values from process.env. ```typescript // Manual configuration from environment const blnk = BlnkInit( process.env.BLNK_API_KEY || '', { baseUrl: process.env.BLNK_BASE_URL || 'http://localhost:5001', timeout: parseInt(process.env.BLNK_TIMEOUT || '10000'), retryCount: parseInt(process.env.BLNK_RETRY_COUNT || '1'), retryDelayMs: parseInt(process.env.BLNK_RETRY_DELAY || '2000') } ); ``` -------------------------------- ### Test Environment Configuration Source: https://github.com/blnkfinance/blnk-ts/blob/main/CORE-0.15.0-GAP-CHECKLIST.md Commands and paths for setting up the local test environment for Core 0.15.0. ```text - Core image: `jerryenebeli/blnk:0.15.0` - Start: `docker compose up -d` in `blnk/` - Health: `http://localhost:5001/health` - Postman: `blnk/postman/Blnk-SDK-Issues-Local-Core-Tests.postman_collection.json` ``` -------------------------------- ### GET /reconciliation/{reconciliation_id} Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Retrieves the status and transaction counts for a specific reconciliation run. ```APIDOC ## GET /reconciliation/{reconciliation_id} ### Description View reconciliation status and counts. ### Method GET ### Endpoint /reconciliation/{reconciliation_id} ### Parameters #### Path Parameters - **reconciliation_id** (string) - Required - The unique identifier of the reconciliation run. ``` -------------------------------- ### Documentation Usage Workflow Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/README.md Follow these steps to effectively navigate and implement the Blnk-ts SDK. ```typescript // 1. Find what you need // → Check INDEX.md → Quick Navigation by Task // 2. Open the service reference // → Read the method signature and parameters // 3. Copy an example // → Adapt the code example for your use case // 4. Handle errors // → Check errors.md for your expected status codes // 5. Look up types // → Open types.md and search by type name ``` -------------------------------- ### Configure Blnk Environment Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Define database, Redis, server, and notification settings in a blnk.json file. ```json { "project_name": "Blnk", "data_source": { "dns": "postgres://postgres:password@postgres:5432/blnk?sslmode=disable" }, "redis": { "dns": "redis:6379" }, "server": { "domain": "blnk.io", "ssl": false, "ssl_email": "jerryenebeli@gmail.com", "port": "5001" }, "notification": { "slack": { "webhook_url": "https://hooks.slack.com" } } } ``` -------------------------------- ### Handle API Response Errors Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/types.md Example of checking for errors in an API response object. ```typescript const response = await blnk.Ledgers.create({ name: 'Test' }); if (response.error) { console.error(`Error ${response.error.code}: ${response.error.message}`); } ``` -------------------------------- ### Create API Key Usage Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Demonstrates creating an API key and handling the response, noting that the raw key is only returned once. ```typescript const response = await blnk.ApiKeys.create({ name: 'Service Account', owner: 'merchant_a', scopes: ['ledgers:read', 'balances:write'], expires_at: '2026-03-11T00:00:00Z' }); if (response.status === 201) { // Store the key securely; it's only shown once const apiKey = response.data?.key; console.log('New API key:', apiKey); } ``` -------------------------------- ### Retrieve identity example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/identities.md Retrieves identity details using a specific identity ID. ```typescript const response = await blnk.Identity.get('idt_3b63c8da-af29-4cc3-ad38-df17d87456e6'); ``` -------------------------------- ### Update ledger usage example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/ledgers.md Updates the name of an existing ledger identified by its ID. ```typescript const response = await blnk.Ledgers.update( 'ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc', { name: 'Updated Customer Savings Account' } ); if (response.status === 200) { console.log('Ledger updated:', response.data?.name); } ``` -------------------------------- ### Initiate Typesense reindexing Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Starts a reindex operation to rebuild the Typesense index from the database. ```typescript const { Search } = blnk; const reindex = await Search.startReindex({ batch_size: 1000 }); // reindex.data?.message — "Reindex operation started" // reindex.data?.progress.status — "pending" | "in_progress" | "completed" | "failed" ``` -------------------------------- ### create Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Creates a new API key with defined permissions and expiration. ```APIDOC ## create ### Description Creates a new API key with scoped permissions. The raw key value is returned only once upon creation. ### Signature `async create(data: CreateApiKeyData): Promise>` ### Parameters - **data** (CreateApiKeyData) - Required - Key definition - **data.name** (string) - Required - Key name - **data.owner** (string) - Required - Owner/account identifier - **data.scopes** (string[]) - Required - Permission scopes (e.g., 'ledgers:read', 'balances:write') - **data.expires_at** (string) - Required - ISO 8601 expiration timestamp ### Requirements - Requires master key or 'api-keys:write' scope ### Example ```typescript const response = await blnk.ApiKeys.create({ name: 'Service Account', owner: 'merchant_a', scopes: ['ledgers:read', 'balances:write'], expires_at: '2026-03-11T00:00:00Z' }); ``` ``` -------------------------------- ### Define Identity get method signature Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/identities.md Defines the TypeScript signature for retrieving an identity by ID. ```typescript async get>( id: string ): Promise | null>> ``` -------------------------------- ### blnk.Hooks.create Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Registers a new webhook. Requires a master key in the X-Blnk-Key header. ```APIDOC ## blnk.Hooks.create ### Description Registers a new webhook for transaction lifecycle events. ### Method SDK Method: `async create(data: CreateHookData): Promise>` ### Parameters - **data** (CreateHookData) - Required - Hook definition - **data.name** (string) - Required - Webhook name - **data.url** (string) - Required - Webhook endpoint URL - **data.type** (HookType) - Required - 'PRE_TRANSACTION' or 'POST_TRANSACTION' - **data.active** (boolean) - Required - Enable webhook immediately - **data.timeout** (number) - Required - Request timeout in seconds - **data.retry_count** (number) - Required - Number of retries on failure ### Requirements - Requires master key (`server.secret_key`) in `X-Blnk-Key` header. ### Response - **ApiResponse** - On success (status 201), contains hook ID and metadata. ``` -------------------------------- ### Get reconciliation status in Blnk Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Retrieves the current status and transaction counts for a specific reconciliation process. ```typescript const { Reconciliation } = blnk; const status = await Reconciliation.get('recon_3803ea0d-28b4-4c73-a36b-5a9eb7a3edfd'); // status.data?.status — e.g. started, in_progress, completed, failed // status.data?.matched_transactions, unmatched_transactions ``` -------------------------------- ### Create a new ledger Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Initializes a new ledger for tracking balances using the Blnk SDK. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = await BlnkInit('', { baseUrl: 'http://localhost:5001' }); const { Ledgers } = blnk; const newLedger = await Ledgers.create({ name: "Customer Savings Account", meta_data: { project_owner: "YOUR_APP_NAME" } }); console.log("Ledger Created:", newLedger); ``` -------------------------------- ### Get Transaction Lineage in TypeScript Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/transactions.md Retrieves fund allocation and shadow transactions for a specific transaction ID. ```typescript async getLineage>( transactionId: string ): Promise | null>> ``` ```typescript const response = await blnk.Transactions.getLineage('txn_8d2ce2f0-0d75-4a91-9d43-2ad2c2e6b9ad'); if (response.status === 200) { console.log('Fund allocation:', response.data?.fund_allocation); console.log('Shadow transactions:', response.data?.shadow_transactions); } ``` -------------------------------- ### blnk.BalanceMonitor.create Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Creates a new balance monitor with a specified condition and optional webhook callback. ```APIDOC ## async create(data: MonitorData) ### Description Creates a new balance monitor with a condition. ### Parameters - **data** (MonitorData) - Required - Monitor definition - **balance_id** (string) - Required - Balance ID to monitor - **condition** (MonitorCondition) - Required - Alert condition - **field** (string) - Required - Field to monitor (e.g., 'balance', 'debit_balance') - **operator** (MonitorConditionOperators) - Required - Comparison operator: '>', '<', '=', '!=', '>=', '<=' - **value** (number) - Required - Threshold value (in major units) - **precision** (number) - Required - Decimal precision (e.g., 100 for cents) - **description** (string) - Optional - Human-readable description - **call_back_url** (string) - Optional - Webhook URL to call when condition is met ### Returns `ApiResponse` — On success (status 201), `data` contains monitor_id and creation timestamp. ``` -------------------------------- ### POST /reconciliation/start-instant Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Performs an immediate reconciliation of provided external transactions. ```APIDOC ## POST /reconciliation/start-instant ### Description Reconciles inline external transactions immediately. ### Method POST ### Endpoint /reconciliation/start-instant ``` -------------------------------- ### Create a Webhook Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Registers a new webhook. Requires the master key in the X-Blnk-Key header. ```typescript async create( data: CreateHookData ): Promise> ``` ```typescript const response = await blnk.Hooks.create({ name: 'Pre-transaction validation', url: 'https://api.example.com/validate', type: 'PRE_TRANSACTION', active: true, timeout: 30, retry_count: 3 }); if (response.status === 201) { console.log('Webhook registered:', response.data?.id); } ``` -------------------------------- ### Utilize TypeScript Type Support Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Demonstrates how the SDK provides type inference for API responses when creating resources like ledgers. ```typescript // Full type support const response = await blnk.Ledgers.create({ name: 'My Ledger', meta_data: { owner: 'my-app' } }); // Type is inferred as ApiResponse | null> if (response.data?.ledger_id) { // ledger_id is correctly typed console.log(response.data.ledger_id); } ``` -------------------------------- ### Configure Retry Count Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Set the total number of request attempts for idempotent GET requests. Defaults to 1. ```typescript // Default: 1 (no retries) const blnk = BlnkInit('key', { baseUrl: 'http://localhost:5001', retryCount: 3 // 1 initial + 2 retries }); ``` -------------------------------- ### Access SDK Services Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/getting-started.md Access various services from the initialized Blnk instance and perform operations like creating a ledger. ```typescript const { Ledgers, LedgerBalances, Transactions, BalanceMonitor, Reconciliation, Search, Identity, System, Metadata, Hooks, ApiKeys } = blnk; // Example: Create a ledger const ledger = await Ledgers.create({ name: 'My Ledger', meta_data: { owner: 'my_app' } }); ``` -------------------------------- ### startReindex(options) Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/search-and-filter.md Initiates a reindexing operation to rebuild the Typesense index from the database. ```APIDOC ## startReindex(options) ### Description Rebuilds the Typesense index from the database. ### Parameters - **options** (StartReindexRequest) - Optional - Reindex options - **batch_size** (number) - Optional - Records processed per batch ### Returns - **ApiResponse** - On success, data.message and data.progress indicate the operation started. ### Example ```typescript const response = await blnk.Search.startReindex({ batch_size: 1000 }); ``` ``` -------------------------------- ### ApiKeys.list(options?) Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Lists API keys for a specific owner. ```APIDOC ## GET /api-keys ### Description Retrieves a list of API keys associated with an owner. ### Method GET ### Endpoint /api-keys ### Query Parameters - **owner** (string) - Optional - Filter by owner ``` -------------------------------- ### Configure Structured Logging for Production Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Integrates the pino logger to provide structured output for production environments. ```typescript import pino from 'pino'; const pinoLogger = pino({ level: process.env.LOG_LEVEL || 'info' }); const blnk = BlnkInit('key', { baseUrl: 'http://localhost:5001', logger: { info: (msg, ...meta) => pinoLogger.info({msg, meta}), error: (msg, ...meta) => pinoLogger.error({msg, meta}), debug: (msg, ...meta) => pinoLogger.debug({msg, meta}) } }); ``` -------------------------------- ### blnk.BalanceMonitor.list Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Retrieves a list of all configured balance monitors. ```APIDOC ## async list() ### Description Retrieves all balance monitors. ### Returns `ApiResponse` — On success (status 200), `data` is an array of all monitors. ``` -------------------------------- ### List API Keys Usage Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Demonstrates listing all keys or filtering by a specific owner identifier. ```typescript // List all keys const allKeys = await blnk.ApiKeys.list(); // List keys for specific owner const ownerKeys = await blnk.ApiKeys.list({ owner: 'merchant_a' }); // Check details ownerKeys.data?.forEach(k => { console.log(k.api_key_id, k.scopes, k.expires_at); }); ``` -------------------------------- ### Clone Blnk Repository Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Download the Blnk source code from GitHub to your local machine. ```bash git clone https://github.com/blnkfinance/blnk && cd blnk ``` -------------------------------- ### Configure Base URL Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Set the base URL for the Blnk Core server. Trailing slashes are handled automatically. ```typescript // Self-hosted const blnk = BlnkInit('key', { baseUrl: 'http://localhost:5001' }); // Remote server const blnk = BlnkInit('key', { baseUrl: 'https://blnk.company.com' }); // Trailing slash is added automatically if missing const blnk = BlnkInit('key', { baseUrl: 'http://localhost:5001/' // Also works }); ``` -------------------------------- ### Create a new balance Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Initializes a balance within a ledger. Requires a ledger_id and currency. ```typescript const { LedgerBalances } = blnk; const newBalance = await LedgerBalances.create({ ledger_id: "ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc", currency: "USD", meta_data: { first_name: "Alice", last_name: "Hart", account_number: "1234567890" } }); console.log("Balance Created:", newBalance); ``` ```typescript const lineageBalance = await LedgerBalances.create({ ledger_id: "ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc", identity_id: "idt_3b63c8da-af29-4cc3-ad38-df17d87456e6", currency: "USD", track_fund_lineage: true, allocation_strategy: "FIFO", // FIFO | LIFO | PROPORTIONAL }); ``` -------------------------------- ### createSnapshot Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balances.md Triggers daily balance snapshots in batches. ```APIDOC ## createSnapshot ### Description Triggers daily balance snapshots in batches. ### Method async createSnapshot(options?: CreateBalanceSnapshotRequest) ### Parameters - **options** (CreateBalanceSnapshotRequest) - Optional - Snapshot options - **batch_size** (number) - Optional - Balances processed per batch (0 uses server default) ### Returns `ApiResponse` — On success, `data.message` confirms operation. ### Example ```typescript const response = await blnk.LedgerBalances.createSnapshot({ batch_size: 500 }); ``` ``` -------------------------------- ### Create Basic Bulk Transactions Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Executes a standard bulk transaction request without additional configuration options. ```typescript const { Transactions } = blnk; // Basic bulk transactions without additional options const basicBulkData = { transactions: [ { amount: 1000, precision: 100, reference: 'bulk_txn_001', description: 'Payment 1', currency: 'USD', source: '@source_account_1', destination: '@destination_account_1', }, { amount: 2000, precision: 100, reference: 'bulk_txn_002', description: 'Payment 2', currency: 'USD', source: '@source_account_2', destination: '@destination_account_2', }, ], }; const response = await Transactions.createBulk(basicBulkData); console.log('Bulk transaction response:', response); ``` -------------------------------- ### Create Balance Snapshot Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balances.md Triggers a daily balance snapshot process. The batch_size parameter controls the number of balances processed per batch. ```typescript const response = await blnk.LedgerBalances.createSnapshot({ batch_size: 500 }); ``` -------------------------------- ### blnk.BalanceMonitor.create Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balance-monitors.md Creates a new balance monitor that triggers an alert when the specified condition is met for a given balance ID. ```APIDOC ## blnk.BalanceMonitor.create ### Description Creates a new monitor to track a balance account and trigger a callback when a defined condition is met. ### Parameters - **balance_id** (string) - Required - The ID of the balance to monitor. - **condition** (MonitorCondition) - Required - The condition object containing field, operator, value, and precision. - **description** (string) - Optional - A description of the monitor. - **call_back_url** (string) - Optional - The URL to notify when the condition is met. ### Request Example { "balance_id": "bln_savings_account", "condition": { "field": "balance", "operator": "<", "value": 1000, "precision": 100 }, "description": "Savings account low balance alert", "call_back_url": "https://api.myapp.com/alerts/low-balance" } ### Response - **monitor_id** (string) - The unique identifier for the created monitor. - **created_at** (string) - The timestamp when the monitor was created. ``` -------------------------------- ### Create Ledger Balance Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/balances.md Initializes a new balance in a ledger, optionally enabling fund lineage tracking with a specific allocation strategy. ```typescript // Basic balance const response = await blnk.LedgerBalances.create({ ledger_id: 'ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc', currency: 'USD' }); // With fund lineage tracking const lineageResponse = await blnk.LedgerBalances.create({ ledger_id: 'ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc', identity_id: 'idt_3b63c8da-af29-4cc3-ad38-df17d87456e6', currency: 'USD', track_fund_lineage: true, allocation_strategy: 'FIFO' }); ``` -------------------------------- ### Initializing Blnk Services Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Services are lazily initialized upon first access and cached for subsequent use. ```typescript const blnk = BlnkInit('key', options); // Services are created on first access const ledgers = blnk.Ledgers; const transactions = blnk.Transactions; const balances = blnk.LedgerBalances; // All 11 services blnk.Ledgers; // Ledger management blnk.LedgerBalances; // Balance management blnk.Transactions; // Transaction operations blnk.BalanceMonitor; // Balance alerts blnk.Identity; // Identity management blnk.Reconciliation; // Reconciliation operations blnk.Search; // Search and filter blnk.System; // Health checks blnk.Metadata; // Entity metadata blnk.Hooks; // Webhook management (requires master key) blnk.ApiKeys; // API key management (requires master key) ``` -------------------------------- ### blnk.Ledgers.create Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/ledgers.md Creates a new ledger entry with a specified name and optional metadata. ```APIDOC ## blnk.Ledgers.create ### Description Creates a new ledger entry. This method returns the created ledger details upon success. ### Signature `async create(data: CreateLedger): Promise | null>>` ### Parameters - **data** (CreateLedger) - Required - Ledger creation data - **data.name** (string) - Required - Human-readable name for the ledger - **data.meta_data** (T) - Optional - Custom metadata object ### Returns - **ApiResponse** (Object) - On success (status 201), contains the created ledger details. ### Example ```typescript const response = await blnk.Ledgers.create({ name: 'Customer Savings Account', meta_data: { project_owner: 'MY_APP', department: 'finance' } }); ``` ``` -------------------------------- ### Create a ledger entry Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/ledgers.md Defines the method signature for creating a new ledger. ```typescript async create>( data: CreateLedger ): Promise | null>> ``` -------------------------------- ### Hooks.create(data) Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Registers a new pre- or post-transaction webhook. ```APIDOC ## POST /hooks ### Description Register a pre- or post-transaction webhook. Requires the master key in the X-Blnk-Key header. ### Method POST ### Endpoint /hooks ### Request Body - **name** (string) - Required - Name of the hook. - **url** (string) - Required - The endpoint URL for the webhook. - **type** (string) - Required - The type of hook (e.g., PRE_TRANSACTION). - **active** (boolean) - Optional - Whether the hook is active. - **timeout** (number) - Optional - Timeout in seconds. - **retry_count** (number) - Optional - Number of retries. ``` -------------------------------- ### runInstant Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/reconciliation.md Reconciles external transactions inline without requiring a prior file upload. ```APIDOC ## async runInstant(data: RunInstantReconData) ### Description Reconciles external transactions inline without prior upload. ### Parameters - **data.external_transactions** (ExternalTransaction[]) - Required - Transactions to reconcile - **data.strategy** (Strategy) - Required - 'one_to_one', 'one_to_many', or 'many_to_one' - **data.dry_run** (boolean) - Optional - Preview without persisting - **data.matching_rule_ids** (string[]) - Required - Rule IDs to apply ### Returns `ApiResponse` — On success, `data.reconciliation_id` identifies the run. ``` -------------------------------- ### ApiKeys.create(data) Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Creates a new scoped API key. ```APIDOC ## POST /api-keys ### Description Creates a new scoped API key. The raw key value is returned only once at creation. ### Method POST ### Endpoint /api-keys ### Request Body - **name** (string) - Required - Name of the API key - **owner** (string) - Required - Owner identifier - **scopes** (array) - Required - List of permissions - **expires_at** (string) - Optional - Expiration timestamp ``` -------------------------------- ### Migrate from Single to Bulk Transactions Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Shows the transition from individual transaction calls to a single bulk request. ```typescript // Before (Single Transactions) const tx1 = await Transactions.create(transactionData1); const tx2 = await Transactions.create(transactionData2); // After (Bulk Transactions) const bulkResponse = await Transactions.createBulk({ transactions: [transactionData1, transactionData2] }); ``` -------------------------------- ### blnk.System.health() Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/system-and-metadata.md Checks whether Blnk Core is running and reachable. Useful for liveness probes and initial connection verification. ```APIDOC ## blnk.System.health() ### Description Checks whether Blnk Core is running and reachable. ### Method async health() ### Returns - **ApiResponse** - On success (status 200), data.status is 'UP'. ### Example ```typescript const response = await blnk.System.health(); if (response.status === 200) { console.log('System status:', response.data?.status); } ``` ``` -------------------------------- ### Import SDK Constants Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/INDEX.md Access default configuration constants for timeouts and retries. ```typescript import { DEFAULT_TIMEOUT_MS, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_DELAY_MS } from '@blnkfinance/blnk-typescript'; ``` -------------------------------- ### Standard Method and Error Handling Pattern Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/README.md The standard template for invoking SDK methods and handling responses, including parameter signatures and error checking logic. ```typescript // Complete signature showing parameters async method(param: Type): Promise> // Usage examples - real, copy-paste-able code const response = await blnk.Service.method({...}); // Error checking pattern if (response.status === expectedStatus) { // access response.data } else { // handle error: response.message, response.error?.code } ``` -------------------------------- ### Identity.create Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Registers a new customer or organization identity. The identity_type is required, while other fields are optional. ```APIDOC ## Identity.create ### Description Registers a new customer or organization identity in the system. ### Method POST ### Endpoint /identities ### Parameters #### Request Body - **identity_type** (string) - Required - The type of identity (e.g., 'individual') - **identity_id** (string) - Optional - Custom identifier starting with 'idt_' - **first_name** (string) - Optional - First name of the identity - **last_name** (string) - Optional - Last name of the identity - **gender** (string) - Optional - Gender of the identity - **dob** (string) - Optional - Date of birth in ISO 8601 format - **email_address** (string) - Optional - Email address - **phone_number** (string) - Optional - Phone number - **nationality** (string) - Optional - Nationality code - **category** (string) - Optional - Category of the identity - **street** (string) - Optional - Street address - **country** (string) - Optional - Country - **state** (string) - Optional - State - **post_code** (string) - Optional - Postal code - **city** (string) - Optional - City ``` -------------------------------- ### Create API Key Definition Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Defines the method signature for creating a new API key with scoped permissions. ```typescript async create( data: CreateApiKeyData ): Promise> ``` -------------------------------- ### BlnkInit Function Signature Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md The function signature for initializing the Blnk client. ```typescript function BlnkInit( apiKey: string, options: BlnkClientOptions ): Blnk ``` -------------------------------- ### list Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/hooks-and-keys.md Retrieves a list of API keys, optionally filtered by owner. ```APIDOC ## list ### Description Lists API keys for an owner. Returns an array of API key objects without the raw key values. ### Signature `async list(options?: ListApiKeysOptions): Promise>` ### Parameters - **options** (ListApiKeysOptions) - Optional - Filter options - **options.owner** (string) - Optional - Owner identifier to filter by ### Requirements - Requires master key or 'api-keys:read' scope ### Example ```typescript const allKeys = await blnk.ApiKeys.list(); const ownerKeys = await blnk.ApiKeys.list({ owner: 'merchant_a' }); ``` ``` -------------------------------- ### Create a transaction Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Records a new financial transaction using source and destination balance IDs. ```typescript const { Transactions } = blnk; const newTransaction = await Transactions.create({ amount: 750, reference: "ref_001adcfgf", currency: "USD", precision: 100, source: "bln_28edb3e5-c168-4127-a1c4-16274e7a28d3", destination: "bln_ebcd230f-6265-4d4a-a4ca-45974c47f746", description: "Sent from app", meta_data: { sender_name: "John Doe", sender_account: "00000000000" } }); console.log("Transaction Recorded:", newTransaction); ``` -------------------------------- ### Configure SDK Retry Strategy Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/errors.md Set the retry count and delay interval during SDK initialization to handle transient network or server errors. ```typescript const blnk = BlnkInit('key', { baseUrl: 'http://localhost:5001', retryCount: 3, // Total attempts (default: 1, no retries) retryDelayMs: 2000 // Base delay between retries (default: 2000) }); ``` -------------------------------- ### async createMatchingRule(data: Matcher) Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/reconciliation.md Defines a matching rule for transaction reconciliation. Returns an ApiResponse containing the rule_id, created_at, and updated_at. ```APIDOC ## async createMatchingRule(data: Matcher) ### Description Defines a matching rule for transaction reconciliation. ### Parameters - **data** (Matcher) - Required - Matching rule definition - **data.name** (string) - Required - Rule name - **data.description** (string) - Required - Rule description - **data.criteria** (Criteria[]) - Required - Matching criteria ### Returns `ApiResponse` — On success (status 201), `data` contains rule_id, created_at, and updated_at. ### Example ```typescript const response = await blnk.Reconciliation.createMatchingRule({ name: 'Amount with 2% drift', description: 'Match transactions allowing 2% amount variance', criteria: [ { field: 'amount', operator: 'equals', allowable_drift: 0.02 }, { field: 'currency', operator: 'equals' } ] }); ``` ```