Account Methods
The BBREClient class provides two account methods that let you query your
BBRE account programmatically: getBalance() and
getAccountInfo(). These methods communicate directly with the BBRE account
API endpoints using your API key for authentication. The getBalance()
method returns your current account balance as a number, giving you a quick way to
check available funds before submitting requests. The getAccountInfo()
method returns a comprehensive object containing your account details and usage
statistics, including your username, email, account status, total requests, today's
requests, completed and failed request counts, success rate, and active session count.
Both methods throw descriptive errors when the API key is invalid, the account is
suspended, or the service is temporarily unavailable. This page provides complete
documentation for both account methods, including method signatures, return types,
field descriptions, practical code examples, usage patterns, best practices, common
issues, and links to related documentation.
Both account methods use the API key configured in the BBREClient
constructor to authenticate with the BBRE account API. They send GET requests to the
/account/balance and /account/info endpoints respectively,
using the X-API-Key header for authentication. Unlike the HTTP convenience
methods (get(), post(), etc.) which send requests through the
BBRE engine to external URLs, the account methods communicate directly with the BBRE
API server to retrieve your account data. No BBRE credits are consumed when calling
these methods.
client.getBalance()
The getBalance() method retrieves your current BBRE account balance. It
sends a GET request to the /account/balance endpoint with your API key in
the X-API-Key header and returns the balance value directly as a number.
The returned value represents your available credit balance in your account currency.
This method is useful for checking whether you have sufficient funds before submitting
expensive requests, implementing pre-flight balance checks in automated workflows, and
building monitoring dashboards that track balance consumption over time.
Method Signature
const balance = await client.getBalance();
Parameters
The getBalance() method does not accept any parameters. It uses the API
key that was provided to the BBREClient constructor for authentication.
| Parameter | Type | Required | Description |
|---|---|---|---|
| This method does not accept any parameters. | |||
Return Type
The method returns a Promise that resolves to a number
representing your current account balance. The value is extracted from the API response
at response.data.balance and returned directly without any wrapper object.
| Return Type | Description |
|---|---|
| number | The current account balance as a numeric value. Represents available credits in your account. |
Basic Usage
The simplest usage of getBalance() retrieves and displays your current
account balance. The method returns the balance directly as a number, so you can use
it immediately in calculations or comparisons.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function checkBalance() {
const balance = await client.getBalance();
console.log("Current balance:", balance);
}
checkBalance();
Balance Check with Threshold Warning
You can compare the returned balance against a threshold value to trigger warnings or notifications when your balance drops below a certain level. This is useful for automated systems that need to alert operators before credits run out.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function checkBalanceWithThreshold() {
const balance = await client.getBalance();
const warningThreshold = 10;
const criticalThreshold = 2;
console.log("Current balance:", balance);
if (balance <= criticalThreshold) {
console.log("CRITICAL: Balance is extremely low. Recharge immediately.");
} else if (balance <= warningThreshold) {
console.log("WARNING: Balance is running low. Consider recharging soon.");
} else {
console.log("Balance is healthy.");
}
}
checkBalanceWithThreshold();
Error Handling for getBalance()
The getBalance() method throws an error when the API key is missing or
invalid, the account is suspended or inactive, or the BBRE service is temporarily
unavailable. Always wrap the call in a try-catch block to handle these scenarios
gracefully.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function safeBalanceCheck() {
try {
const balance = await client.getBalance();
console.log("Current balance:", balance);
return balance;
} catch (error) {
console.log("Failed to retrieve balance:", error.message);
return null;
}
}
safeBalanceCheck();
client.getAccountInfo()
The getAccountInfo() method retrieves comprehensive information about your
BBRE account, including account details and usage statistics. It sends a GET request to
the /account/info endpoint with your API key in the
X-API-Key header and returns an object containing two properties:
account and statistics. The account object
includes your username, email address, account status, current balance, and account
creation date. The statistics object includes your total request count,
today's request count, completed and failed request counts, success rate percentage,
and the number of currently active sessions. This method is ideal for building account
dashboards, monitoring usage patterns, and verifying account status before starting
large batch operations.
Method Signature
const info = await client.getAccountInfo();
Parameters
The getAccountInfo() method does not accept any parameters. It uses the
API key that was provided to the BBREClient constructor for
authentication.
| Parameter | Type | Required | Description |
|---|---|---|---|
| This method does not accept any parameters. | |||
Return Type
The method returns a Promise that resolves to an object with two
properties: account and statistics. The account
property contains your account profile information, and the statistics
property contains your usage metrics.
{
"account": {
"username": "alice_dev",
"email": "[email protected]",
"status": "active",
"balance": 85.50,
"createdAt": "2024-06-15T10:30:00.000Z"
},
"statistics": {
"totalRequests": 12450,
"todayRequests": 342,
"completedRequests": 11890,
"failedRequests": 560,
"successRate": 95.5,
"activeSessions": 3
}
}
Account Fields
The account object contains the following fields describing your BBRE
account profile and current status.
| Field | Type | Description |
|---|---|---|
username |
string | Your BBRE account username. This is the display name associated with your account. |
email |
string | The email address registered to your BBRE account. Used for account notifications and recovery. |
status |
string | The current status of your account. Possible values include active, inactive, and suspended. Only accounts with active status can submit requests. |
balance |
number | Your current account balance. This is the same value returned by getBalance(). Represents available credits for submitting requests. |
createdAt |
string | The ISO 8601 timestamp indicating when your account was created. Format: YYYY-MM-DDTHH:mm:ss.sssZ. |
Statistics Fields
The statistics object contains the following fields describing your BBRE
usage metrics and performance data.
| Field | Type | Description |
|---|---|---|
totalRequests |
number | The total number of requests submitted through your account since it was created. Includes both completed and failed requests. |
todayRequests |
number | The number of requests submitted today (UTC timezone). Resets at midnight UTC each day. |
completedRequests |
number | The total number of requests that completed successfully. A completed request means the BBRE engine received a response from the target server. |
failedRequests |
number | The total number of requests that failed. Failures include timeouts, network errors, and target server errors that prevented the BBRE engine from returning a response. |
successRate |
number | The percentage of requests that completed successfully, calculated as (completedRequests / totalRequests) * 100. Returned as a number between 0 and 100. |
activeSessions |
number | The number of currently active BBRE sessions. The maximum allowed is 10 active sessions per account. Use this to check availability before creating new sessions. |
Basic Usage
The simplest usage of getAccountInfo() retrieves and displays your account
details and usage statistics. Destructure the returned object to access the
account and statistics properties separately.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function displayAccountInfo() {
const { account, statistics } = await client.getAccountInfo();
console.log("Username:", account.username);
console.log("Email:", account.email);
console.log("Status:", account.status);
console.log("Balance:", account.balance);
console.log("Account created:", account.createdAt);
console.log("Total requests:", statistics.totalRequests);
console.log("Today requests:", statistics.todayRequests);
console.log("Completed:", statistics.completedRequests);
console.log("Failed:", statistics.failedRequests);
console.log("Success rate:", statistics.successRate, "%");
console.log("Active sessions:", statistics.activeSessions);
}
displayAccountInfo();
Check Account Status Before Operations
Before starting a batch of requests or creating sessions, use
getAccountInfo() to verify that your account is active, has sufficient
balance, and has available session slots. This prevents wasted API calls and provides
clear error messages when preconditions are not met.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function validateAccountBeforeWork() {
const { account, statistics } = await client.getAccountInfo();
if (account.status !== "active") {
console.log("Account is not active. Current status:", account.status);
return false;
}
if (account.balance < 5) {
console.log("Insufficient balance:", account.balance);
return false;
}
if (statistics.activeSessions >= 10) {
console.log("Maximum session limit reached:", statistics.activeSessions);
return false;
}
console.log("Account is ready for operations");
console.log("Available balance:", account.balance);
console.log("Available session slots:", 10 - statistics.activeSessions);
return true;
}
validateAccountBeforeWork();
Usage Statistics Dashboard
Build a simple usage statistics dashboard by formatting the statistics data into a readable summary. This pattern is useful for logging, monitoring, and reporting purposes.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function printUsageDashboard() {
const { account, statistics } = await client.getAccountInfo();
console.log("=== BBRE Account Dashboard ===");
console.log("Account:", account.username, "(" + account.email + ")");
console.log("Status:", account.status);
console.log("Balance:", account.balance, "credits");
console.log("");
console.log("=== Usage Statistics ===");
console.log("Total requests (all time):", statistics.totalRequests);
console.log("Requests today:", statistics.todayRequests);
console.log("Completed:", statistics.completedRequests);
console.log("Failed:", statistics.failedRequests);
console.log("Success rate:", statistics.successRate + "%");
console.log("Active sessions:", statistics.activeSessions, "/ 10");
}
printUsageDashboard();
Error Handling for getAccountInfo()
The getAccountInfo() method throws an error when the API key is missing or
invalid, the account is suspended or inactive, or the BBRE service is temporarily
unavailable. Always wrap the call in a try-catch block to handle these scenarios
gracefully.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function safeAccountInfoCheck() {
try {
const { account, statistics } = await client.getAccountInfo();
console.log("Account status:", account.status);
console.log("Balance:", account.balance);
console.log("Success rate:", statistics.successRate, "%");
return { account, statistics };
} catch (error) {
console.log("Failed to retrieve account info:", error.message);
return null;
}
}
safeAccountInfoCheck();
Pre-flight Balance Check Pattern
A common pattern in production applications is to check your account balance before
submitting requests, especially when running batch operations that consume significant
credits. The pre-flight balance check pattern uses getBalance() to verify
that sufficient funds are available before proceeding with the main operation. This
prevents partial batch failures caused by insufficient balance mid-execution and
provides a clean way to abort operations early with a meaningful error message.
Simple Pre-flight Check
The simplest pre-flight check verifies that the balance is above a minimum threshold before submitting a request. This is useful for individual requests where you want to avoid the overhead of a failed request due to insufficient balance.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function requestWithBalanceCheck(url) {
const balance = await client.getBalance();
if (balance < 1) {
console.log("Insufficient balance:", balance);
return null;
}
const response = await client.get(url);
console.log("Request completed. Status:", response.statusCode);
return response;
}
requestWithBalanceCheck("https://api.example.com/data");
Batch Operation with Balance Estimation
For batch operations, estimate the total cost based on the number of requests and compare it against the available balance. This prevents starting a batch that cannot be completed due to insufficient funds.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function batchRequestWithBalanceCheck(urls, costPerRequest) {
const balance = await client.getBalance();
const estimatedCost = urls.length * costPerRequest;
console.log("Current balance:", balance);
console.log("Estimated cost for", urls.length, "requests:", estimatedCost);
if (balance < estimatedCost) {
console.log("Insufficient balance for batch operation");
console.log("Need:", estimatedCost, "Have:", balance);
return [];
}
const results = [];
for (const url of urls) {
try {
const response = await client.get(url);
results.push({ url, status: response.statusCode, success: true });
} catch (error) {
results.push({ url, error: error.message, success: false });
}
}
console.log("Batch completed:", results.length, "requests processed");
return results;
}
const urls = [
"https://api.example.com/products/1",
"https://api.example.com/products/2",
"https://api.example.com/products/3"
];
batchRequestWithBalanceCheck(urls, 0.5);
Pre-flight Check with Account Validation
Combine getAccountInfo() with balance checking to perform a comprehensive
pre-flight validation that verifies account status, balance, and session availability
in a single call.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function preFlightValidation(requiredBalance, needsSession) {
try {
const { account, statistics } = await client.getAccountInfo();
const checks = {
accountActive: account.status === "active",
sufficientBalance: account.balance >= requiredBalance,
sessionAvailable: !needsSession || statistics.activeSessions < 10
};
const allPassed = checks.accountActive && checks.sufficientBalance && checks.sessionAvailable;
if (!allPassed) {
console.log("Pre-flight validation failed:");
if (!checks.accountActive) console.log(" Account status:", account.status);
if (!checks.sufficientBalance) console.log(" Balance:", account.balance, "Required:", requiredBalance);
if (!checks.sessionAvailable) console.log(" Active sessions:", statistics.activeSessions, "(max 10)");
}
return { passed: allPassed, checks, account, statistics };
} catch (error) {
console.log("Pre-flight validation error:", error.message);
return { passed: false, error: error.message };
}
}
async function runWorkflow() {
const validation = await preFlightValidation(10, true);
if (!validation.passed) {
console.log("Cannot proceed with workflow");
return;
}
console.log("All checks passed, proceeding with workflow");
console.log("Balance:", validation.account.balance);
console.log("Available sessions:", 10 - validation.statistics.activeSessions);
}
runWorkflow();
Account Monitoring Pattern
The account monitoring pattern uses getAccountInfo() at regular intervals
to track your account health, usage trends, and balance consumption over time. This
pattern is useful for long-running applications, automated scraping pipelines, and
monitoring dashboards that need to detect anomalies such as sudden balance drops,
increasing failure rates, or approaching session limits.
Periodic Balance Monitoring
Monitor your balance at regular intervals and log the consumption rate. This helps you predict when your balance will run out and plan recharges accordingly.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function monitorBalance(intervalMinutes, durationMinutes) {
const readings = [];
const totalChecks = Math.floor(durationMinutes / intervalMinutes);
const intervalMs = intervalMinutes * 60 * 1000;
for (let i = 0; i <= totalChecks; i++) {
const balance = await client.getBalance();
const timestamp = new Date().toISOString();
readings.push({ timestamp, balance });
console.log("[" + timestamp + "] Balance:", balance);
if (readings.length >= 2) {
const previous = readings[readings.length - 2];
const consumed = previous.balance - balance;
console.log(" Consumed since last check:", consumed);
}
if (i < totalChecks) {
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
}
if (readings.length >= 2) {
const totalConsumed = readings[0].balance - readings[readings.length - 1].balance;
const ratePerMinute = totalConsumed / durationMinutes;
console.log("Total consumed:", totalConsumed);
console.log("Rate per minute:", ratePerMinute.toFixed(4));
}
return readings;
}
monitorBalance(5, 30);
Success Rate Monitoring
Track your success rate over time to detect degradation in request quality. A dropping success rate may indicate issues with target websites, proxy configuration, or fingerprint settings that need attention.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function checkSuccessRate(warningThreshold, criticalThreshold) {
const { statistics } = await client.getAccountInfo();
console.log("Success rate:", statistics.successRate + "%");
console.log("Completed:", statistics.completedRequests);
console.log("Failed:", statistics.failedRequests);
if (statistics.successRate < criticalThreshold) {
console.log("CRITICAL: Success rate is below", criticalThreshold + "%");
console.log("Review your request configuration and target URLs");
return "critical";
}
if (statistics.successRate < warningThreshold) {
console.log("WARNING: Success rate is below", warningThreshold + "%");
return "warning";
}
console.log("Success rate is healthy");
return "healthy";
}
checkSuccessRate(90, 75);
Session Slot Monitoring
Before creating new sessions in an automated workflow, check the number of active sessions to avoid hitting the maximum session limit. This pattern is especially important for applications that create and close sessions dynamically.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function getAvailableSessionSlots() {
const { statistics } = await client.getAccountInfo();
const maxSessions = 10;
const available = maxSessions - statistics.activeSessions;
console.log("Active sessions:", statistics.activeSessions);
console.log("Available slots:", available);
return available;
}
async function createSessionIfAvailable(options) {
const available = await getAvailableSessionSlots();
if (available <= 0) {
console.log("No session slots available. Close existing sessions first.");
return null;
}
const session = await client.createSession(options);
console.log("Session created:", session.sessionId);
return session;
}
createSessionIfAvailable({ mode: "adaptive" });
Error Handling
Both getBalance() and getAccountInfo() throw errors when the
API request fails. The error message contains a description of what went wrong. Common
error scenarios include invalid or missing API keys, suspended or inactive accounts,
and temporary service unavailability. The following examples demonstrate how to handle
these errors in your application.
Error Types
The following table lists the common errors that can be thrown by the account methods, along with their causes and recommended solutions.
| Error Message | Cause | Solution |
|---|---|---|
API key is required |
The X-API-Key header is missing because no API key was provided to the BBREClient constructor. |
Pass a valid API key when creating the BBREClient instance: new BBREClient({ apiKey: "YOUR_KEY" }). |
Invalid API key |
The provided API key does not match any active account in the BBRE system. | Verify that your API key is correct and has not been revoked. Check for extra whitespace or truncation. |
Account suspended |
Your BBRE account has been suspended due to policy violations or payment issues. | Contact support to resolve the suspension. Check your email for suspension notifications. |
Account inactive |
Your BBRE account is in an inactive state and cannot perform operations. | Activate your account through the dashboard or contact support for assistance. |
Failed to get balance |
A network error or server error prevented the balance request from completing. | Retry the request after a short delay. If the error persists, check the BBRE service status. |
Failed to get account info |
A network error or server error prevented the account info request from completing. | Retry the request after a short delay. If the error persists, check the BBRE service status. |
Comprehensive Error Handling Example
The following example demonstrates a robust error handling pattern that distinguishes between different error types and takes appropriate action for each scenario.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function robustBalanceCheck() {
try {
const balance = await client.getBalance();
return { success: true, balance };
} catch (error) {
const message = error.message.toLowerCase();
if (message.includes("api key")) {
console.log("Authentication error: Check your API key configuration");
return { success: false, errorType: "auth", message: error.message };
}
if (message.includes("suspended") || message.includes("inactive")) {
console.log("Account error: Your account is not in active state");
return { success: false, errorType: "account", message: error.message };
}
console.log("Service error:", error.message);
return { success: false, errorType: "service", message: error.message };
}
}
robustBalanceCheck();
Retry Pattern for Transient Errors
For transient errors such as network timeouts or temporary service unavailability, implement a retry pattern with exponential backoff to improve reliability.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function getBalanceWithRetry(maxRetries, initialDelayMs) {
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const balance = await client.getBalance();
return balance;
} catch (error) {
lastError = error;
const message = error.message.toLowerCase();
if (message.includes("api key") || message.includes("suspended") || message.includes("inactive")) {
throw error;
}
if (attempt < maxRetries) {
const delay = initialDelayMs * Math.pow(2, attempt - 1);
console.log("Attempt", attempt, "failed. Retrying in", delay, "ms");
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
async function main() {
try {
const balance = await getBalanceWithRetry(3, 1000);
console.log("Balance:", balance);
} catch (error) {
console.log("All retries failed:", error.message);
}
}
main();
Best Practices
When you only need to check your available credits, use getBalance()
because it returns a single number with minimal overhead. When you need account
details, usage statistics, or session counts in addition to the balance, use
getAccountInfo() to get all the data in a single API call. Avoid
calling both methods sequentially when getAccountInfo() alone provides
all the information you need, since the account.balance field in the
response contains the same value as getBalance().
Before starting batch operations that submit many requests, call
getBalance() to verify that you have sufficient credits to complete
the entire batch. Estimate the total cost by multiplying the number of requests by
the average cost per request, and compare it against the available balance. This
prevents partial batch failures where some requests succeed and others fail due to
insufficient balance, which can leave your data in an inconsistent state.
If your application checks account information frequently (for example, before every request), cache the result for a short period (30 to 60 seconds) to reduce the number of API calls to the account endpoint. The account data does not change rapidly enough to require real-time checks on every request. Use a simple timestamp-based cache that refreshes the data after the cache duration expires.
Periodically check the statistics.successRate field from
getAccountInfo() to detect degradation in your request success rate.
A sudden drop in success rate may indicate that target websites have changed their
anti-bot measures, your proxy configuration needs updating, or your fingerprint
settings are being detected. Set up alerts when the success rate drops below a
threshold (for example, 85%) so you can investigate and adjust your configuration
promptly.
The BBRE system allows a maximum of 10 active sessions per account. Before creating
a new session, check the statistics.activeSessions field from
getAccountInfo() to verify that you have available session slots. If
all 10 slots are occupied, close unused sessions before creating new ones. This
prevents SESSION_LIMIT_REACHED errors and ensures your application
can always create sessions when needed.
Both getBalance() and getAccountInfo() can throw errors
due to authentication failures, account status issues, or temporary service
unavailability. Always wrap these calls in try-catch blocks and implement
appropriate fallback behavior. For non-critical monitoring calls, log the error and
continue with default values. For critical pre-flight checks, propagate the error
to prevent the main operation from starting with unknown account status.
Common Issues
Symptom: You try to access result.balance or
result.data.balance after calling getBalance(), but get
undefined.
Cause: The getBalance() method returns the balance
value directly as a number, not wrapped in an object. It extracts
response.data.balance internally and returns just the numeric value.
Solution: Assign the return value directly to a variable:
const balance = await client.getBalance();. Do not try to access
properties on the returned value. If you need the balance along with other account
data, use getAccountInfo() instead, which returns an object with
account.balance.
Symptom: You try to access result.data,
result.success, or result.statusCode after calling
getAccountInfo(), but get undefined.
Cause: The getAccountInfo() method extracts the
account and statistics properties from the API response
and returns them as a clean object. It does not return the raw API response with
success, data, or HTTP status information.
Solution: Destructure the return value to access the account and
statistics objects:
const { account, statistics } = await client.getAccountInfo();. Access
the balance through account.balance and usage data through the
statistics object.
Symptom: Calling getBalance() or
getAccountInfo() throws an error with a message about a missing or
invalid API key.
Cause: The BBREClient was created without an API key, or the API
key was set to null, undefined, or an empty string. Both
account methods require a valid API key to authenticate with the BBRE API.
Solution: Ensure you pass a valid API key when creating the
BBREClient instance:
const client = new BBREClient({ apiKey: "YOUR_VALID_KEY" });. Verify
that the API key is loaded correctly from your environment variables or
configuration file.
Symptom: You recharged your account, but getBalance()
still returns zero or the old balance value.
Cause: There may be a short propagation delay between the payment
processing and the balance update in the BBRE system. Additionally, if your
application caches the balance value, the cached value may be stale.
Solution: Wait a few seconds after recharging and call
getBalance() again. If you are caching balance values, clear the cache
after a recharge event. If the balance does not update after a reasonable wait time,
contact support with your payment confirmation details.
Symptom: The todayRequests field shows a higher
number than expected, or totalRequests does not match your records.
Cause: The todayRequests counter resets at midnight
UTC, which may differ from your local timezone. The totalRequests
counter includes all requests since account creation, including failed requests and
requests from all API keys associated with the account.
Solution: Account for the UTC timezone when interpreting the
todayRequests value. For precise request tracking, use the
/account/history endpoint which provides detailed per-request records
with timestamps.