@getalby/lightning-tools
Version:
Collection of helpful building blocks and tools to develop Bitcoin Lightning web apps
58 lines (55 loc) • 2.06 kB
JavaScript
;
const numSatsInBtc = 100000000;
const getFiatCurrencies = async () => {
const url = "https://getalby.com/api/rates";
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch currencies: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const mappedCurrencies = Object.entries(data)
.filter(([code]) => code.toUpperCase() !== "BTC")
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(([code, details]) => ({
code: code.toUpperCase(),
name: details.name,
priority: details.priority,
symbol: details.symbol,
}))
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) => a.priority - b.priority);
return mappedCurrencies;
};
const getFiatBtcRate = async (currency) => {
const url = "https://getalby.com/api/rates/" + currency.toLowerCase() + ".json";
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch rate: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.rate_float / numSatsInBtc;
};
const getFiatValue = async ({ satoshi, currency, }) => {
const rate = await getFiatBtcRate(currency);
return Number(satoshi) * rate;
};
const getSatoshiValue = async ({ amount, currency, }) => {
const rate = await getFiatBtcRate(currency);
return Math.floor(Number(amount) / rate);
};
const getFormattedFiatValue = async ({ satoshi, currency, locale, }) => {
if (!locale) {
locale = "en";
}
const fiatValue = await getFiatValue({ satoshi, currency });
return fiatValue.toLocaleString(locale, {
style: "currency",
currency,
});
};
exports.getFiatBtcRate = getFiatBtcRate;
exports.getFiatCurrencies = getFiatCurrencies;
exports.getFiatValue = getFiatValue;
exports.getFormattedFiatValue = getFormattedFiatValue;
exports.getSatoshiValue = getSatoshiValue;
//# sourceMappingURL=fiat.cjs.map