lending-apy-fetcher-ts
Version:
TypeScript library for fetching APYs from DeFi lending protocols
106 lines • 3.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApyFetcher = void 0;
const types_1 = require("./types");
class ApyFetcher {
constructor(protocols) {
this.protocols = [];
this.initializeProtocols(protocols || []);
}
initializeProtocols(protocols) {
this.protocols.push(...protocols);
}
/**
* Fetch APYs from all configured protocols
* @param gracefulDegradation - Continue with other protocols if one fails
*/
async fetchApys(gracefulDegradation = true) {
const results = await this.fetchApysWithResults(gracefulDegradation);
// Aggregate all successful results
const allApys = [];
for (const result of results) {
if (result.success && result.data) {
allApys.push(...result.data);
}
}
return allApys;
}
/**
* Fetch APYs with detailed results per protocol
*/
async fetchApysWithResults(gracefulDegradation = true) {
const promises = this.protocols.map(async (protocol) => {
try {
const data = await protocol.fetchApys();
return {
success: true,
data,
protocol: protocol.name,
};
}
catch (error) {
const apyError = error instanceof types_1.ApyFetcherError
? error
: new types_1.ApyFetcherError(`Failed to fetch from ${protocol.name}`, protocol.name, error);
if (!gracefulDegradation) {
throw apyError;
}
return {
success: false,
error: apyError,
protocol: protocol.name,
};
}
});
return Promise.all(promises);
}
/**
* Get APYs grouped by token symbol
*/
async getApysByToken(gracefulDegradation = true) {
const apys = await this.fetchApys(gracefulDegradation);
const grouped = {};
for (const apy of apys) {
if (!grouped[apy.token_symbol]) {
grouped[apy.token_symbol] = [];
}
grouped[apy.token_symbol].push(apy);
}
// Sort each group by APY descending
for (const symbol in grouped) {
grouped[symbol].sort((a, b) => b.apy - a.apy);
}
return grouped;
}
/**
* Get the best APY for a specific token across all protocols
*/
async getBestApyForToken(tokenSymbol, gracefulDegradation = true) {
const apys = await this.fetchApys(gracefulDegradation);
const tokenApys = apys.filter(apy => apy.token_symbol.toLowerCase() === tokenSymbol.toLowerCase());
if (tokenApys.length === 0) {
return null;
}
// Sort by APY descending
tokenApys.sort((a, b) => b.apy - a.apy);
return {
token_symbol: tokenSymbol,
apy: tokenApys[0].apy,
network: tokenApys[0].network,
};
}
/**
* Get all available protocols
*/
getProtocols() {
return [...this.protocols];
}
/**
* Add a custom protocol
*/
addProtocol(protocol) {
this.protocols.push(protocol);
}
}
exports.ApyFetcher = ApyFetcher;
//# sourceMappingURL=fetcher.js.map