-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathloan-to-balance.js
38 lines (30 loc) · 1.31 KB
/
loan-to-balance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use strict';
const plaid = require('../plaid');
const { decrypt } = require('../encrypt-decrypt');
const fetchTransactions = require('../utils/fetch-transactions');
const findUserByWallet = require('../utils/query-user');
async function loanToBalance(wallet, accountId) {
// percent of balance to allow as collateral
const COLLATERAL_PERCENT = 0.2;
const user = await findUserByWallet(wallet);
const accessToken = decrypt(user.plaid_access_token);
// Fetch account
const opts = { account_ids: accountId };
const account = await plaid.client.getBalance(accessToken, opts);
// Fetch and save latest txns to ensure they're up-to-date
// positive transaction amounts = money leaving account,
// negative transaction amounts = money entering account
// Source: https://plaid.com/docs/#transactions
const txns = await fetchTransactions({ wallet, account });
let lowestBalance = account.balances.available;
let calculated = lowestBalance;
// Working backwards from the current balance.
// Iterate through previous txns,
// If money left the account, add it back in,
// if money entered the account, remove it.
for (const txn of txns) {
calculated += txn.amount;
lowestBalance = Math.min(calculated, lowestBalance);
}
return lowestBalance * COLLATERAL_PERCENT;
}