A savings application empowers users to effectively manage and grow their savings through automated and manual contributions. This guide will assist you in building a comprehensive savings platform using the Blnk Ledger.

We’ll learn about:

  1. Defining and creating your ledger structure
  2. Savings account creation
  3. Funding account
  4. Scheduled transactions for savings
  5. Calculating & crediting interest
  6. Best Practices (with Inflight)

1. Ledger structure

In this example, we’ll use Blnk ledger to build a detailed savings app with interest. Each user will have their own savings account, and we’ll use the scheduling feature to apply interest regularly.

In this guide, we’ll use the following structure:

  • Savings Ledger: Contains all savings accounts for users.

The ledger structure is flexible and can be customized based on your specific needs. For instance, you could group by types of transactions (e.g., real estate, freelance work), or use a combination of both.

See also

Creating a savings ledger

View your ledgers in your terminal:

bash
blnk ledgers list

Always store the ledger_id in your database. You’ll need it for future operations related to this ledger.

2. Balance (savings account) creation

Blnk uses the concept of ledger balances to manage accounts/balances in a ledger. In this example, we’ll create savings accounts for Alice.

See also

Creating a savings account for User Alice

View your balances in your terminal:

bash
blnk balances list

The balance_id is crucial. Always store this in your database and associate it with the customer. You’ll use this ID for all future transactions involving this loyalty point account.

3. Funding account

Customers can fund their savings accounts. We’ll use the Inflight feature to manage funding transactions.

See also

Funding Alice’s escrow account

The transaction should be committed after the payment has been verified from the external payment partner.

4. Scheduled transactions for savings

We’ll use the scheduled_for transaction feature to schedule regular deposits into the savings accounts.

Scheduling a monthly deposit for Alice

To schedule a monthly deposit, you can use a recurring task scheduler like cron in combination with the Blnk API. Below is an example of how you can achieve this using Node.js and the node-cron package.

1

Install the required package

npm install node-cron request
2

Create a script to handle scheduled deposits

your_script_name.js
const request = require('request');
const cron = require('node-cron');

// Function to schedule monthly deposit
function scheduleMonthlyDeposit(customerId, balanceId, amount, dayOfMonth) {
  cron.schedule(`0 0 ${dayOfMonth} * *`, () => {
    const options = {
      method: 'POST',
      urllocalhost:5001/transactions',
      headers: {
        'X-Blnk-Key': 'blnk-api',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "amount": amount
        "precision": 100,
        "reference": `monthly-deposit-${customerId}`,
        "description": "Monthly deposit",
        "currency": "USD",
        "source": "@bank-account",
        "destination": balanceId,
        "scheduled_for": new Date().toISOString(),
        "meta_data": {
          "transaction_type": "deposit",
          "customer_id": customerId
        }
      })
    };

    request(options, (error, response) => {
      if (error) throw new Error(error);
      console.log(`Scheduled deposit for customer ${customerId}:`, response.body);
    });
  });
}

// Schedule deposits for Alice and Bob
scheduleMonthlyDeposit("alice-5678", "bln_alice5678-90ab-cdef-1234-567890abcdef", 200, 1);
scheduleMonthlyDeposit("bob-9101", "bln_bob9101-90ab-cdef-1234-567890abcdef", 150, 1);
3

Run the script

This script schedules a monthly deposit for Alice and Bob on the 1st day of every month. You can adjust the dayOfMonth parameter to change the day when the deposit should be made.

node your_script_name.js

View your transactions in your terminal:

bash
blnk transactions list

5. Calculating & crediting interest

We’ll calculate interest periodically and credit it to the savings accounts.

Example: Crediting monthly interest

You can set up a similar cron job for calculating and crediting interest. Below is an example script for crediting monthly interest.

1

Create a script to handle interest calculation and crediting

your_interest_script_name.js
const request = require('request');
const cron = require('node-cron');

// Function to calculate and credit interest
function creditMonthlyInterest(balanceId, interestRate) {
  cron.schedule('0 0 1 * *', () => {  // Runs on the 1st day of every month
    // Fetch the current balance
    request({
      method: 'GET',
      urllocalhost:5001/balances/${balanceId}`,
      headers: {
        'X-Blnk-Key': 'blnk-api',
        'Content-Type': 'application/json'
      }
    }, (error, response, body) => {
      if (error) throw new Error(error);

      const balance = JSON.parse(body).balance;
      const interest = (balance * interestRate) / 100;

      // Credit the interest to the account
      const options = {
        method: 'POST',
        urllocalhost:5001/transactions',
        headers: {
          'X-Blnk-Key': 'blnk-api',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          "amount": interest,
          "precision": 100,
          "reference": `interest-credit-${balanceId}`,
          "description": "Monthly interest credit",
          "currency": "USD",
          "source": "@interest-pool",
          "destination": balanceId,
          "meta_data": {
            "transaction_type": "interest",
            "balance_id": balanceId
          }
        })
      };

      request(options, (error, response) => {
        if (error) throw new Error(error);
        console.log(`Credited interest to balance ${balanceId}:`, response.body);
      });
    });
  });
}

// Credit interest for Alice
creditMonthlyInterest("bln_alice5678-90ab-cdef-1234-567890abcdef", 2.5);
2

Running the script

node your_interest_script_name.js

This script calculates and credits monthly interest to Alice on the 1st day of every month.

See also

Managing side effects with Inflight

A deep-dive guide into how to implement Inflight in your application.

Best practices (with Inflight)

  1. Balance Checks: Ensure the source balance has enough funds to complete the transaction. Prevent the source balance from having a balance lower than the amount in its inflight_debit_balance.
  2. Available Balance Calculation: In your application, calculate the available balance to prevent users from accessing funds that are held in Inflight transactions. This can be done as follows:
    const availableBalance = balance - inflight_debit_balance;
    
  3. Error Handling: Implement robust error handling in your Inflight process. If a commit or void operation fails, you may need to retry or escalate to manual intervention.
  4. Customer Communication: Implement a system to notify customers about the status of their transactions, especially when they’re held in inflight.
  5. Reconciliation: Regularly reconcile your internal records with Blnk’s transaction logs to ensure accuracy. Pay special attention to Inflight transactions. Blnk v1 will support reconciliation features built into the ledger, which can aid in this process.
  6. Webhook Authentication: In a production environment, implement a mechanism to verify that webhooks are genuinely from your payment provider. This helps in maintaining the integrity and security of your transaction processing.
  7. Idempotency: Ensure your webhook handler is idempotent. Providers may send the same webhook multiple times, so your system should handle duplicate notifications gracefully.
  8. Monitoring: Set up monitoring and alerting for your webhook endpoint and inflight transactions. This can help you quickly identify and respond to any issues in the payment verification process.

Need help?

We are very happy to help you make the most of Blnk, regardless of whether it is your first time or you are switching from another tool.

To ask questions or discuss issues, please join our Discord community.