### Development Environment Setup Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Initialize the Blnk SDK for a development environment using a specific API key and local base URL. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('dev-api-key', { baseUrl: 'http://localhost:5001', timeout: 5000, }); ``` -------------------------------- ### Verify Blnk CLI Installation Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Verify the Blnk CLI installation and view available commands by running `blnk --help`. ```bash blnk --help ``` -------------------------------- ### Initialize Blnk Client and Access Search Service Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/search.md Demonstrates how to initialize the Blnk client and access the Search service. This is typically done once during application setup. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('api-key', { baseUrl: 'http://localhost:5001' }); // Access the Search service const searchService = blnk.Search; ``` -------------------------------- ### Install Blnk TypeScript SDK Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Install the Blnk TypeScript SDK in your project using npm. ```bash npm install @blnkfinance/blnk-typescript --save ``` -------------------------------- ### Testing Environment Setup Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Initialize the Blnk SDK for a testing environment, using a test API key and potentially a local URL, with suppressed logging. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('test-api-key', { baseUrl: process.env.TEST_BLNK_URL || 'http://localhost:5001', timeout: 10000, logger: { info: () => {}, // Suppress logs in tests error: () => {}, debug: () => {}, }, }); ``` -------------------------------- ### Initialize Blnk Client and Access LedgerBalances Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/ledger-balances.md Demonstrates how to initialize the Blnk client and access the LedgerBalances service. This is typically done once during application setup. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('api-key', { baseUrl: 'http://localhost:5001' }); // Access the LedgerBalances service const balancesService = blnk.LedgerBalances; ``` -------------------------------- ### Initialize Blnk-TS with Pino Logger Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/blnk-init.md Set up the Blnk-TS client to use Pino for logging. Pino must be installed and configured independently. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; import pino from 'pino'; const pinoLogger = pino(); const blnk = BlnkInit(process.env.BLNK_API_KEY!, { baseUrl: process.env.BLNK_BASE_URL!, logger: { info: (message, ...meta) => pinoLogger.info({ msg: message, meta }), error: (message, ...meta) => pinoLogger.error({ msg: message, meta }), debug: (message, ...meta) => pinoLogger.debug({ msg: message, meta }), }, }); export default blnk; ``` -------------------------------- ### Initialize Blnk Client and Access Ledgers Service Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/ledgers.md Demonstrates how to initialize the Blnk client and access the Ledgers service. This is typically done once during application setup. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('api-key', { baseUrl: 'http://localhost:5001' }); // Access the Ledgers service const ledgersService = blnk.Ledgers; ``` -------------------------------- ### Using Blnk-TS Services to Create Resources Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/blnk-init.md Illustrates a workflow for creating a ledger, then a balance within that ledger, and finally recording a transaction. This example requires a valid API key and base URL. ```typescript const blnk = BlnkInit('api-key', { baseUrl: 'http://localhost:5001'}); // Create a ledger const ledgerResponse = await blnk.Ledgers.create({ name: 'Customer Accounts', meta_data: { region: 'US' }, }); if (ledgerResponse.status === 201) { const ledgerId = ledgerResponse.data.ledger_id; // Create a balance in that ledger const balanceResponse = await blnk.LedgerBalances.create({ ledger_id: ledgerId, currency: 'USD', }); if (balanceResponse.status === 201) { const balanceId = balanceResponse.data.balance_id; // Record a transaction const txResponse = await blnk.Transactions.create({ amount: 1000, precision: 100, reference: 'ref_001', description: 'Deposit', currency: 'USD', source: 'bln_source_id', destination: balanceId, }); console.log('Transaction recorded:', txResponse.data.transaction_id); } } ``` -------------------------------- ### Production Environment Setup Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Initialize the Blnk SDK for a production environment, using environment variables for the API key and URL, and configuring a longer timeout and custom logger. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit(process.env.BLNK_API_KEY!, { baseUrl: process.env.BLNK_API_URL || 'https://api.blnk.io', timeout: 30000, // Longer timeout for production logger: { info: (msg, meta) => console.info(`[INFO] ${msg}`, meta), error: (msg, meta) => console.error(`[ERROR] ${msg}`, meta), }, }); ``` -------------------------------- ### Clone Blnk Repository Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Clone the Blnk repository from GitHub to get started. ```bash git clone https://github.com/blnkfinance/blnk && cd blnk ``` -------------------------------- ### Migrate from Single to Bulk Transactions Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Illustrates the difference between creating single transactions and initiating bulk transactions. The example shows how multiple 'Transactions.create' calls can be consolidated into a single 'Transactions.createBulk' call. ```typescript // Before (Single Transactions) // const tx1 = await Transactions.create(transactionData1); // const tx2 = await Transactions.create(transactionData2); ``` -------------------------------- ### Initialize Blnk-TS with Winston Logger Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/blnk-init.md Configure the Blnk-TS client to use Winston for logging. Ensure Winston is installed and configured separately. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; import winston from 'winston'; const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }); const blnk = BlnkInit(process.env.BLNK_API_KEY!, { baseUrl: process.env.BLNK_BASE_URL!, logger: { info: (message, ...meta) => logger.info(message, { meta }), error: (message, ...meta) => logger.error(message, { meta }), debug: (message, ...meta) => logger.debug(message, { meta }), }, }); export default blnk; ``` -------------------------------- ### get() Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Retrieves a specific balance monitor by its unique identifier. This allows you to fetch the details of an existing monitor. ```APIDOC ## get() ### Description Retrieves a specific balance monitor by its unique identifier. This allows you to fetch the details of an existing monitor. ### Method GET ### Endpoint /balance-monitors/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the monitor to retrieve. ### Response #### Success Response (200) - **monitor_id** (string) - The unique identifier for the monitor. - **balance_id** (string) - The ID of the balance being monitored. - **condition** (MonitorCondition) - The condition that triggers the monitor. - **call_back_url** (string) - The webhook URL, if provided. - **created_at** (string) - The timestamp when the monitor was created. #### Error Responses - **404**: Monitor not found. - **500**: Server error during retrieval. ### Response Example (200) ```json { "monitor_id": "mon_12345", "balance_id": "bln_28edb3e5-c168-4127-a1c4-16274e7a28d3", "condition": { "field": "balance", "operator": "<", "value": 10000, "precision": 100 }, "created_at": "2024-01-15T10:30:00Z" } ``` ``` -------------------------------- ### Create a Balance Monitor with Webhook Notification Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md This example shows how to create a balance monitor and configure a webhook URL to receive notifications when the condition is met. The `call_back_url` parameter is essential for this functionality. ```typescript const response = await blnk.BalanceMonitor.create({ balance_id: 'bln_account_123', condition: { field: 'balance', operator: '>', value: 100000, // Greater than 1000.00 precision: 100, }, description: 'Notify when balance exceeds $1000', call_back_url: 'https://api.example.com/webhooks/balance-alert', }); if (response.status === 201) { console.log('Webhook monitor created'); } ``` -------------------------------- ### list() Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Retrieves a list of all configured balance monitors. This is useful for getting an overview of all active alerts. ```APIDOC ## list() ### Description Retrieves a list of all configured balance monitors. This is useful for getting an overview of all active alerts. ### Method GET ### Endpoint /balance-monitors ### Response #### Success Response (200) - An array of MonitorDataResp objects, each representing a balance monitor. #### Error Responses - **500**: Server error during retrieval. ### Response Example (200) ```json [ { "monitor_id": "mon_12345", "balance_id": "bln_28edb3e5-c168-4127-a1c4-16274e7a28d3", "condition": { "field": "balance", "operator": "<", "value": 10000, "precision": 100 }, "created_at": "2024-01-15T10:30:00Z" }, { "monitor_id": "mon_67890", "balance_id": "bln_account_123", "condition": { "field": "balance", "operator": ">", "value": 100000, "precision": 100 }, "call_back_url": "https://api.example.com/webhooks/balance-alert", "created_at": "2024-01-16T11:00:00Z" } ] ``` ``` -------------------------------- ### Create Balance Monitor Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md This example demonstrates how to create a new balance monitor to trigger an alert when a specific balance reaches zero. It includes setting the balance ID, condition, description, and a callback URL for notifications. ```APIDOC ## Create Balance Monitor ### Description Creates a new balance monitor that triggers an alert when a specified balance meets a certain condition. This is useful for setting up real-time notifications for critical balance changes. ### Method POST ### Endpoint `/balance-monitors` ### Parameters #### Request Body - **balance_id** (string) - Required - The ID of the balance to monitor. - **condition** (object) - Required - The condition to monitor. - **field** (string) - Required - The balance field to monitor (e.g., 'balance', 'credit_balance', 'inflight_balance', 'inflight_credit_balance'). - **operator** (string) - Required - The comparison operator (e.g., '=', '>', '<', '!='). - **value** (number) - Required - The value to compare against. - **precision** (number) - Required - The precision for the comparison. - **description** (string) - Optional - A description for the monitor. - **call_back_url** (string) - Optional - The URL to send webhook notifications to when the condition is met. ### Request Example ```json { "balance_id": "bln_restricted_account", "condition": { "field": "balance", "operator": "=", "value": 0, "precision": 100 }, "description": "Alert when balance reaches zero", "call_back_url": "https://api.example.com/webhook/zero-balance" } ``` ### Response #### Success Response (201 Created) - **monitor_id** (string) - The ID of the created monitor. #### Response Example ```json { "monitor_id": "mon_12345" } ``` ``` -------------------------------- ### Handle Blnk-TS Initialization Errors Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/blnk-init.md Provides an example of how to catch and handle errors during Blnk-TS client initialization, specifically checking for missing required configuration like `baseUrl`. ```typescript try { const blnk = BlnkInit('api-key', { // Missing baseUrl }); } catch (error) { if (error instanceof Error && error.message.includes('baseUrl is required')) { console.error('Configuration error: baseUrl must be provided'); } } ``` -------------------------------- ### Create Individual Identity with Metadata Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md Example of creating an individual identity with custom metadata. ```APIDOC ## create() with Metadata ### Description Creates a new individual identity and includes custom metadata. ### Method `create>(data: IdentityData): Promise>>` ### Parameters #### Request Body - **identity_type** (string) - Required - Type of identity ('individual' or 'organization'). - **first_name** (string) - Required - First name. - **last_name** (string) - Required - Last name. - **email_address** (string) - Required - Email address. - **phone_number** (string) - Required - Phone number. - **category** (string) - Required - Category of the identity. - **street** (string) - Required - Street address. - **country** (string) - Required - Country. - **state** (string) - Required - State or province. - **post_code** (string) - Required - Postal code. - **city** (string) - Required - City. - **meta_data** (object) - Optional - Additional metadata for the identity. - **kyc_status** (string) - KYC status ('verified', 'pending', 'rejected'). - **verification_date** (string) - Date of verification. - **risk_score** (number) - Risk score. ### Request Example ```typescript interface IdentityMeta { kyc_status: 'verified' | 'pending' | 'rejected'; verification_date: string; risk_score: number; } const response = await blnk.Identity.create({ identity_type: 'individual', first_name: 'Jane', last_name: 'Smith', email_address: 'jane.smith@example.com', phone_number: '+1-555-0789', category: 'vip_customer', street: '789 Oak Lane', country: 'USA', state: 'Texas', post_code: '75201', city: 'Dallas', meta_data: { kyc_status: 'verified', verification_date: '2024-01-10', risk_score: 2, }, }); ``` ``` -------------------------------- ### Create Async Bulk Transactions with All Options Source: https://github.com/blnkfinance/blnk-ts/blob/main/README.md Illustrates creating bulk transactions with all available options: atomic, inflight, and run_async. This example includes setting inflight expiry dates and metadata for each transaction. ```typescript // Process transactions asynchronously with atomic and inflight options const asyncBulkData = { atomic: true, inflight: true, run_async: true, transactions: [ { amount: 12000, precision: 100, reference: 'async_txn_001', description: 'Async atomic inflight payment 1', currency: 'USD', source: '@source_account_1', destination: '@destination_account_1', allow_overdraft: true, inflight_expiry_date: new Date(Date.now() + 48 * 60 * 60 * 1000), // 48 hours meta_data: { department: 'sales', project: 'Q4_campaign', }, }, { amount: 8500, precision: 100, reference: 'async_txn_002', description: 'Async atomic inflight payment 2', currency: 'USD', source: '@source_account_2', destination: '@destination_account_2', allow_overdraft: true, inflight_expiry_date: new Date(Date.now() + 48 * 60 * 60 * 1000), // 48 hours meta_data: { department: 'marketing', project: 'Q4_campaign', }, }, ], }; const asyncResponse = await Transactions.createBulk(asyncBulkData); ``` -------------------------------- ### List All Monitors Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Fetches a list of all balance monitors configured in the system. This can be used to get an overview of all active monitoring. ```APIDOC ## GET /BalanceMonitor ### Description Retrieves all balance monitors in the system. ### Method GET ### Endpoint /BalanceMonitor ### Parameters #### Query Parameters None ### Response #### Success Response (200) - **status** (number) - 200 on success, 500 on server error - **message** (string) - Description of the result - **data** (Array) - Array of monitor objects #### Response Example ```json { "status": 200, "message": "Monitors retrieved successfully", "data": [ { "monitor_id": "mon_12345", "balance_id": "bln_abcde", "condition": { "field": "balance", "operator": "<", "value": 10000, "precision": 100 }, "description": "Alert when balance drops below $100", "call_back_url": "https://api.example.com/webhook" } ] } ``` #### Error Responses - **500** - Server error during retrieval ``` -------------------------------- ### Initialize Blnk Client Once Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/blnk-init.md Initialize the Blnk client once and export it for reuse across your application. This ensures consistent configuration and avoids redundant setup. ```typescript // client.ts import { BlnkInit } from '@blnkfinance/blnk-typescript'; export const blnk = BlnkInit(process.env.BLNK_API_KEY!, { baseUrl: process.env.BLNK_BASE_URL!, }); // other-file.ts import { blnk } from './client'; const ledger = await blnk.Ledgers.create({ name: 'My Ledger' }); ``` -------------------------------- ### Create Balance Monitor with Error Handling Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Implement robust error handling when creating a balance monitor. This example demonstrates how to catch potential validation, not found, or server errors. ```typescript try { const response = await blnk.BalanceMonitor.create({ balance_id: 'bln_account_123', condition: { field: 'balance', operator: '<', value: 10000, precision: 100, }, description: 'Low balance alert', }); if (!response.data) { if (response.status === 400) { console.error('Validation error:', response.message); } else if (response.status === 404) { console.error('Balance not found'); } else { console.error('Server error:', response.message); } return; } console.log('Monitor created:', response.data.monitor_id); } catch (error) { console.error('Unexpected error:', error); } ``` -------------------------------- ### Monitoring Different Fields Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Examples of how to configure monitors for various balance fields, including credit balance, inflight balance, and inflight credit balance, using different comparison operators. ```APIDOC ## Monitoring Different Fields ### Description This section provides examples of configuring balance monitors for different fields beyond the primary balance, such as credit balances and pending transaction amounts. ### Examples #### Monitor Credit Balance ```typescript const creditMonitor = { balance_id: 'bln_abc123', condition: { field: 'credit_balance', operator: '>', value: 100000, precision: 100, }, description: 'Track credit inflows', }; ``` #### Monitor Inflight Balance ```typescript const inflightMonitor = { balance_id: 'bln_abc123', condition: { field: 'inflight_balance', operator: '!=', value: 0, precision: 100, }, description: 'Alert when pending transactions exist', }; ``` #### Monitor Inflight Credits ```typescript const inflightCreditMonitor = { balance_id: 'bln_abc123', condition: { field: 'inflight_credit_balance', operator: '>', value: 0, precision: 100, }, description: 'Track incoming pending funds', }; ``` ``` -------------------------------- ### Create Identity Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md Demonstrates how to create a new identity using the `blnk.Identity.create` method. It includes a full example of the request payload and basic error handling for validation and server errors. ```APIDOC ## Create Identity ### Description Creates a new identity with specified details. This method is used to register new users or entities within the system. ### Method `blnk.Identity.create(data: IdentityData): Promise>>` ### Parameters #### Request Body - **identity_type** (string) - Required - The type of identity (e.g., 'individual', 'organization'). - **first_name** (string) - Optional - The first name of the individual. - **last_name** (string) - Optional - The last name of the individual. - **email_address** (string) - Required - The email address of the identity. - **phone_number** (string) - Optional - The phone number of the identity. - **category** (string) - Optional - The category the identity belongs to (e.g., 'customer', 'merchant'). - **street** (string) - Optional - The street address. - **country** (string) - Optional - The country. - **state** (string) - Optional - The state or province. - **post_code** (string) - Optional - The postal code. - **city** (string) - Optional - The city. ### Request Example ```typescript await blnk.Identity.create({ identity_type: 'individual', first_name: 'John', last_name: 'Doe', email_address: 'john@example.com', phone_number: '+1-555-0123', category: 'customer', street: '123 Main St', country: 'USA', state: 'CA', post_code: '90001', city: 'Los Angeles', }); ``` ### Response #### Success Response (200) - **data** (IdentityDataResponse) - Contains the created identity details, including `identity_id`. - **status** (number) - HTTP status code, typically 200 for success. #### Error Response - **message** (string) - Description of the error. - **status** (number) - HTTP status code (e.g., 400 for validation errors, 500 for server errors). ### Error Handling Handles potential validation errors (status 400) and general server errors (other statuses) by logging appropriate messages. Unexpected errors during the request are caught and logged. ``` -------------------------------- ### Fetch Identity and Create Linked Balance Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md This example demonstrates fetching an identity's details using its ID and then using the retrieved `identity_id` to create a new balance associated with that identity in a specified ledger and currency. ```typescript // Get identity details const identityResponse = await blnk.Identity.get('id_user_123'); if (identityResponse.status === 200) { const identity = identityResponse.data; // Use identity_id to create balance linked to this identity const balanceResponse = await blnk.LedgerBalances.create({ ledger_id: 'ldg_main', identity_id: identity.identity_id, currency: 'USD', }); if (balanceResponse.status === 201) { console.log('Balance created for identity:', identity.identity_id); } } ``` -------------------------------- ### Error Handling for Balance Monitor Creation Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Provides an example of how to handle potential errors when creating a balance monitor, including validation errors, not found errors, and general server errors. ```APIDOC ## Error Handling ### Description This section illustrates how to implement error handling when interacting with the Balance Monitor API, specifically for the creation of monitors. It covers common error scenarios such as validation failures, resource not found, and server-side issues. ### Example ```typescript try { const response = await blnk.BalanceMonitor.create({ balance_id: 'bln_account_123', condition: { field: 'balance', operator: '<', value: 10000, precision: 100, }, description: 'Low balance alert', }); if (!response.data) { if (response.status === 400) { console.error('Validation error:', response.message); } else if (response.status === 404) { console.error('Balance not found'); } else { console.error('Server error:', response.message); } return; } console.log('Monitor created:', response.data.monitor_id); } catch (error) { console.error('Unexpected error:', error); } ``` ``` -------------------------------- ### Create Individual Identity Record Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md Example of creating a new identity record for an individual, including personal details, contact information, and address. This is often the first step in KYC processes. ```typescript const blnk = BlnkInit('api-key', { baseUrl: 'http://localhost:5001' }); const response = await blnk.Identity.create({ identity_type: 'individual', first_name: 'John', last_name: 'Doe', gender: 'male', dob: new Date('1990-01-15'), email_address: 'john.doe@example.com', phone_number: '+1-555-0123', nationality: 'US', category: 'customer', street: '123 Main Street', country: 'USA', state: 'California', post_code: '90210', city: 'Los Angeles', }); if (response.status === 201) { console.log('Identity created:', response.data); // { // identity_id: 'id_12345', // identity_type: 'individual', // first_name: 'John', // ... // created_at: '2024-01-15T10:30:00Z' // } } ``` -------------------------------- ### KYC Workflow: Create, Verify, and Update Identity Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md This snippet outlines a complete KYC workflow, starting with identity creation, followed by an external verification step (represented by comments), and finally updating the identity with the verification status. It demonstrates sequential API calls. ```typescript // Step 1: Create identity const createResponse = await blnk.Identity.create({ identity_type: 'individual', first_name: 'Alice', last_name: 'Johnson', email_address: 'alice@example.com', phone_number: '+1-555-1234', category: 'customer', street: '100 Main St', country: 'USA', state: 'NY', post_code: '10001', city: 'New York', meta_data: { kyc_status: 'pending' }, }); if (createResponse.status !== 201) { throw new Error('Failed to create identity'); } const identityId = createResponse.data!.identity_id; // Step 2: Perform KYC verification (external service) // ... verification logic ... // Step 3: Update identity with KYC status const updateResponse = await blnk.Identity.update(identityId, { identity_type: 'individual', first_name: 'Alice', last_name: 'Johnson', email_address: 'alice@example.com', phone_number: '+1-555-1234', category: 'verified_customer', street: '100 Main St', country: 'USA', state: 'NY', post_code: '10001', city: 'New York', meta_data: { kyc_status: 'verified' }, }); console.log('KYC workflow completed'); ``` -------------------------------- ### Initialize Blnk SDK Client Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Use `BlnkInit` to create a configured Blnk client instance. Provide your API key and client options, including the base URL for the Blnk server. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; // Initialize the SDK const blnk = BlnkInit('your-api-key', { baseUrl: 'http://localhost:5001', timeout: 5000, }); // Access services const ledgersService = blnk.Ledgers; const balancesService = blnk.LedgerBalances; const transactionsService = blnk.Transactions; ``` -------------------------------- ### BlnkInit() - Initialization Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md The main entry point for initializing the Blnk SDK client. It creates and returns a configured Blnk client instance ready to make API requests. ```APIDOC ## BlnkInit() ### Description Main entry point for initializing the Blnk SDK client. ### Signature ```typescript function BlnkInit(apiKey: string, options: BlnkClientOptions): Blnk ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | apiKey | string | Yes | — | API key for authentication with the Blnk server | | options | BlnkClientOptions | Yes | — | Configuration object for the client | ### Return Value Returns a `Blnk` instance with various service properties like `Ledgers`, `LedgerBalances`, `Transactions`, etc. ### Throws Throws an `Error` if `baseUrl` is not provided in options. ### Example ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; // Initialize the SDK const blnk = BlnkInit('your-api-key', { baseUrl: 'http://localhost:5001', timeout: 5000, }); // Access services const ledgersService = blnk.Ledgers; const balancesService = blnk.LedgerBalances; const transactionsService = blnk.Transactions; ``` ``` -------------------------------- ### Error API Response Example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md An example of an error API response, showing a 400 status code and a null data payload. ```json { "status": 400, "message": "Invalid request", "data": null } ``` -------------------------------- ### Full Client Configuration Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Initialize the Blnk SDK with all available client options, including `baseUrl`, `timeout`, and a custom `logger` object. ```typescript const blnk = BlnkInit('api-key-here', { baseUrl: 'http://localhost:5001', timeout: 10000, // 10 seconds logger: { info: (message, ...meta) => console.log(message, meta), error: (message, ...meta) => console.error(message, meta), debug: (message, ...meta) => console.debug(message, meta), }, }); ``` -------------------------------- ### Success API Response Example Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md An example of a successful API response, indicating a 201 status code and returning created data. ```json { "status": 201, "message": "Success", "data": { "ledger_id": "ldg_12345", "name": "Customer Accounts", "created_at": "2024-01-15T10:30:00Z", "meta_data": {} } } ``` -------------------------------- ### get() Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md Retrieves a specific identity record by its unique identifier. ```APIDOC ## get() ### Description Retrieves a specific identity record by its unique identifier. ### Method GET ### Endpoint /identities/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the identity to retrieve ### Response #### Success Response (200) - **status** (number) - 200 on success - **message** (string) - Description of the result - **data** (IdentityDataResponse | null) - The retrieved identity object #### Response Example ```json { "status": 200, "message": "Identity retrieved successfully", "data": { "identity_id": "id_12345", "identity_type": "individual", "first_name": "John", "last_name": "Doe", "email_address": "john.doe@example.com", "phone_number": "+1-555-0123", "category": "customer", "street": "123 Main Street", "country": "USA", "state": "California", "post_code": "90210", "city": "Los Angeles", "created_at": "2024-01-15T10:30:00Z" } } ``` ### Error Responses - **404**: Identity not found - **500**: Server error during retrieval ``` -------------------------------- ### Create Organization Identity Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md Example of creating an organization identity with basic details. ```APIDOC ## create() ### Description Creates a new identity record. This can be an individual or an organization. ### Method `create>(data: IdentityData): Promise>>` ### Parameters #### Request Body - **identity_type** (string) - Required - Type of identity ('individual' or 'organization'). - **organization_name** (string) - Optional - Name of the organization (required if identity_type is 'organization'). - **email_address** (string) - Required - Email address of the identity. - **phone_number** (string) - Required - Phone number of the identity. - **category** (string) - Required - Category of the identity (e.g., 'business', 'vip_customer'). - **street** (string) - Required - Street address. - **country** (string) - Required - Country. - **state** (string) - Required - State or province. - **post_code** (string) - Required - Postal code. - **city** (string) - Required - City. - **first_name** (string) - Optional - First name (required if identity_type is 'individual'). - **last_name** (string) - Optional - Last name (required if identity_type is 'individual'). - **meta_data** (object) - Optional - Additional metadata for the identity. ### Request Example ```typescript const response = await blnk.Identity.create({ identity_type: 'organization', organization_name: 'TechCorp Inc.', email_address: 'info@techcorp.com', phone_number: '+1-555-0456', category: 'business', street: '456 Corporate Blvd', country: 'USA', state: 'New York', post_code: '10001', city: 'New York', }); if (response.status === 201) { console.log('Organization created:', response.data.organization_name); } ``` ``` -------------------------------- ### Get Ledger Balance Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/ledger-balances.md Retrieves a specific balance within a ledger by its ID. ```APIDOC ## GET /ledgers/{ledger_id}/balances/{balance_id} ### Description Retrieves the details of a specific balance within a ledger. ### Method GET ### Endpoint /ledgers/{ledger_id}/balances/{balance_id} ### Parameters #### Path Parameters - **ledger_id** (string) - Required - The ID of the ledger containing the balance. - **balance_id** (string) - Required - The unique identifier of the balance to retrieve. ### Response #### Success Response (200) - **balance_id** (string) - Unique identifier for the balance - **balance** (number) - Current net balance - **version** (number) - Version for concurrency control - **inflight_balance** (number) - Balance in pending/inflight transactions - **credit_balance** (number) - Total credits received - **inflight_credit_balance** (number) - Credits in inflight transactions - **debit_balance** (number) - Total debits sent - **inflight_debit_balance** (number) - Debits in inflight transactions - **currency_multiplier** (number) - Precision multiplier for currency - **ledger_id** (string) - Associated ledger ID - **identity_id** (string) - Associated identity ID - **currency** (string) - Currency code - **indicator** (string) - Balance status indicator - **created_at** (string) - ISO 8601 creation timestamp - **meta_data** (object) - Custom metadata #### Response Example ```json { "balance_id": "bln_28edb3e5-c168-4127-a1c4-16274e7a28d3", "balance": 100.50, "version": 2, "inflight_balance": 10.00, "credit_balance": 150.00, "inflight_credit_balance": 5.00, "debit_balance": 49.50, "inflight_debit_balance": 5.00, "currency_multiplier": 100, "ledger_id": "ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc", "identity_id": "id_user_12345", "currency": "USD", "indicator": "positive", "created_at": "2024-01-15T10:30:00Z", "meta_data": { "key": "value" } } ``` #### Error Responses - **404**: Balance ID not found within the specified ledger. - **500**: Server error during retrieval. ``` -------------------------------- ### Initialize Blnk Client and Access BalanceMonitor Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/balance-monitor.md Demonstrates how to initialize the Blnk client and access the BalanceMonitor service. This is a prerequisite for using any BalanceMonitor methods. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; const blnk = BlnkInit('api-key', { baseUrl: 'http://localhost:5001' }); // Access the BalanceMonitor service const monitorService = blnk.BalanceMonitor; ``` -------------------------------- ### Get Identity by ID Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/identity.md Retrieves a single identity record using its unique identifier. ```APIDOC ## get() ### Description Retrieves a single identity by ID. ### Method `get>(id: string): Promise | null>>` ### Parameters #### Path Parameters - **id** (string) - Required - Identity ID to retrieve. ### Return Value Returns an `ApiResponse>` with: - `status`: 200 on success, 404 if not found, 500 on server error - `message`: Description of the result - `data`: Identity object with all fields ### Error Responses | Status | |--------| | 404 | Identity with given ID not found | | 500 | Server error during retrieval | ### Example: Basic Retrieval ```typescript const response = await blnk.Identity.get('id_12345'); if (response.status === 200) { const identity = response.data; console.log(`Name: ${identity.first_name} ${identity.last_name}`); console.log(`Email: ${identity.email_address}`); } else if (response.status === 404) { console.log('Identity not found'); } ``` ### Example: Retrieve and Check Metadata ```typescript interface CustomerMeta { kyc_status: 'verified' | 'pending'; tier: 'gold' | 'silver' | 'bronze'; } const response = await blnk.Identity.get('id_customer_123'); if (response.status === 200) { const identity = response.data; const meta = identity.meta_data; if (meta?.kyc_status === 'verified') { console.log('Customer is KYC verified'); console.log('Tier:', meta.tier); } } ``` ``` -------------------------------- ### Initialize Blnk SDK and Create Resources Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/README.md Initialize the Blnk SDK with an API key and base URL. Then, create a new ledger, a balance within that ledger, and record a transaction. Ensure you have the correct API key and base URL for your Blnk environment. ```typescript import { BlnkInit } from '@blnkfinance/blnk-typescript'; // Initialize the SDK const blnk = BlnkInit('your-api-key', { baseUrl: 'http://localhost:5001', }); // Create a ledger const ledger = await blnk.Ledgers.create({ name: 'Customer Accounts', }); // Create a balance in that ledger const balance = await blnk.LedgerBalances.create({ ledger_id: ledger.data.ledger_id, currency: 'USD', }); // Record a transaction const transaction = await blnk.Transactions.create({ amount: 1000, precision: 100, // 2 decimal places reference: 'ref_001', currency: 'USD', description: 'Sample transaction', source: 'source_balance_id', destination: balance.data.balance_id, }); ``` -------------------------------- ### Minimal Client Configuration Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Configure the Blnk SDK with the essential `baseUrl` option. This is the minimum required for initializing the client. ```typescript const blnk = BlnkInit('api-key-here', { baseUrl: 'http://localhost:5001', }); ``` -------------------------------- ### API Key Initialization (Good vs. Bad) Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/configuration.md Demonstrates the recommended practice of using environment variables for API keys and warns against hardcoding them. ```typescript // Good: Use environment variable const apiKey = process.env.BLNK_API_KEY; const blnk = BlnkInit(apiKey, { baseUrl: 'http://localhost:5001' }); // Bad: Never hardcode in source const blnk = BlnkInit('super-secret-key', { baseUrl: 'http://localhost:5001' }); ``` -------------------------------- ### Get Ledger Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/ledgers.md Retrieves a specific ledger by its unique identifier. Returns the ledger details if found, or an error if not. ```APIDOC ## GET /ledgers/{id} ### Description Retrieves a single ledger using its ID. ### Method GET ### Endpoint /ledgers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Ledger ID to retrieve ### Response #### Success Response (200) - **status** (number) - 200 on success - **message** (string) - Description of the result - **data** (CreateLedgerResp) - Ledger object with fields: `ledger_id`, `name`, `created_at`, `meta_data` #### Response Example ```json { "status": 200, "message": "Ledger retrieved successfully", "data": { "ledger_id": "ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc", "name": "Customer Accounts", "created_at": "2024-01-15T10:30:00Z", "meta_data": {} } } ``` #### Error Responses - **404** - Ledger with given ID not found - **500** - Server error during retrieval ``` -------------------------------- ### Get Ledger Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/ledgers.md Retrieves a specific ledger by its ID. Supports type-safe retrieval by providing a generic type argument for metadata. ```APIDOC ## GET /ledgers/{ledger_id} ### Description Retrieves a specific ledger by its ID. You can optionally provide a type for the `meta_data` field for type-safe access. ### Method GET ### Endpoint `/ledgers/{ledger_id}` ### Parameters #### Path Parameters - **ledger_id** (string) - Required - The unique identifier of the ledger to retrieve. ### Response #### Success Response (200) - **ledger_id** (string) - The unique identifier of the ledger. - **name** (string) - The name of the ledger. - **created_at** (string) - The timestamp when the ledger was created. - **meta_data** (object) - Optional - Custom metadata associated with the ledger. #### Response Example ```json { "ledger_id": "ldg_073f7ffe-9dfd-42ce-aa50-d1dca1788adc", "name": "Customer Accounts", "created_at": "2024-01-15T10:30:00Z", "meta_data": { ... } } ``` ``` -------------------------------- ### Workflow: Create Ledger and then Balance Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/ledger-balances.md Demonstrates a common workflow: first creating a ledger, then creating a balance within that newly created ledger. Includes error handling for both steps. ```typescript // Step 1: Create a ledger const ledgerResponse = await blnk.Ledgers.create({ name: 'Customer Accounts', meta_data: { region: 'US' }, }); if (ledgerResponse.status !== 201) { throw new Error('Failed to create ledger'); } const ledgerId = ledgerResponse.data!.ledger_id; // Step 2: Create a balance in that ledger const balanceResponse = await blnk.LedgerBalances.create({ ledger_id: ledgerId, identity_id: 'user_12345', currency: 'USD', }); if (balanceResponse.status !== 201) { throw new Error('Failed to create balance'); } const balanceId = balanceResponse.data!.balance_id; console.log(`Created balance ${balanceId} in ledger ${ledgerId}`); ``` -------------------------------- ### Multi-Field Sort Source: https://github.com/blnkfinance/blnk-ts/blob/main/_autodocs/api-reference/search.md Sorts search results by multiple fields, allowing for hierarchical ordering. This example sorts by ledger ID and then by creation date. ```typescript const response = await blnk.Search.search( { q: 'customer', sort_by: 'ledger_id:asc&&created_at:desc', // Group by ledger, then by date page: 1, per_page: 50, }, 'balances' ); ```