@zebec-network/zebec-stake-sdk
Version:
An SDK for zebec network stake solana program
42 lines (41 loc) • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.callWithEnhancedBackoff = callWithEnhancedBackoff;
exports.chunkArray = chunkArray;
const core_utils_1 = require("@zebec-network/core-utils");
// Set your backoff parameters
const MAX_RETRIES = 5;
const MIN_DELAY = 200; // in milliseconds
const BACKOFF_FACTOR = 2;
const MAX_DELAY = 30000;
// Helper function that wraps an async operation with exponential backoff.
async function callWithEnhancedBackoff(fn, maxRetries = MAX_RETRIES, backoffFactor = BACKOFF_FACTOR, baseDelay = MIN_DELAY, maxDelay = MAX_DELAY) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
}
catch (error) {
if (attempt === maxRetries)
throw error;
let delay = Math.min(baseDelay * backoffFactor ** attempt, maxDelay);
// Handle 429 specifically with longer delays
if (error?.status === 429 ||
error?.code === 429 ||
error?.message?.includes("429")) {
delay = Math.min(delay * backoffFactor, maxDelay); // Double delay for rate limits
console.warn(`Rate limit hit, waiting ${delay}ms before retry ${attempt + 1}/${maxRetries}`);
}
// Add jitter to prevent thundering herd
const jitter = Math.random() * 0.3 * delay;
await (0, core_utils_1.sleep)(delay + jitter);
}
}
throw new Error("Max retries exceeded");
}
function chunkArray(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}