import { fetchWithTimeout } from "../../utils";
const { ACROSS_USER_AGENT = "across-protocol" } = process.env;
export class AbstractAdapter {
    name;
    path;
    timeout;
    retries;
    throw;
    logger;
    constructor(name, path, opts) {
        this.name = name;
        this.path = path;
        this.timeout = opts?.timeout ?? 2000;
        this.retries = opts?.retries ?? 1;
        this.throw = opts?.throwOnError ?? true;
        this.logger = opts?.logger;
    }
    sleep(ms) {
        return new Promise((r) => setTimeout(r, ms));
    }
    async fetch(name, url, timeout = 2000, retries = 1) {
        const errs = [];
        let tries = 0;
        do {
            try {
                return await fetchWithTimeout(url, {}, { "User-Agent": ACROSS_USER_AGENT }, timeout);
            }
            catch (err) {
                const errMsg = err instanceof Error ? err.message : "unknown error";
                errs.push(errMsg);
                if (++tries <= retries)
                    await this.sleep(Math.pow(1.5, tries) * 1000); // simple backoff
            }
        } while (tries <= retries);
        throw new Error(`${name} retrieval failure (${errs.join(", ")})`);
    }
    error(error) {
        if (this.throw) {
            throw error;
        }
        let reason;
        if (error instanceof Error) {
            reason = error.message;
        }
        else {
            reason = typeof error === "string" ? error : "unknown error";
        }
        const { name, path, timeout, retries } = this;
        this.logger?.warn({
            at: `${name}::update`,
            message: `Failed to read addresses from ${name}.`,
            reason,
            path,
            retries,
            timeout,
        });
        return Promise.resolve([]);
    }
}
//# sourceMappingURL=abstract.js.map