UNPKG

chaingate

Version:

A complete TypeScript library for connecting to and making transactions on different blockchains

57 lines 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CurrencyUtils = void 0; const CurrencyAmount_1 = require("./CurrencyAmount"); const NumberLike_1 = require("../../InternalUtils/NumberLike"); class CurrencyUtils { context; currencyInfo; constructor(context, currencyInfo) { this.context = context; this.currencyInfo = currencyInfo; } buildAmount(baseAmount) { return new CurrencyAmount_1.CurrencyAmount(this.currencyInfo, (0, NumberLike_1.toDecimal)(baseAmount), this.context.markets); } amount(amount, unit) { if (unit === this.currencyInfo.symbol) { return this.buildAmount(amount); } if (unit === this.currencyInfo.minimalUnitSymbol) { return this.buildAmount((0, NumberLike_1.toDecimal)(amount).div((0, NumberLike_1.toDecimal)(10).pow(this.currencyInfo.decimals))); } throw new Error(`Unsupported unit: ${unit}`); } async amountFiat(amountFiat, fiatCurrency, useCache = true) { const markets = await this.context.markets.get(useCache); // Calculate total in usd const fiatData = markets.fiat.find((t) => t.symbol === fiatCurrency); if (!fiatData) throw new Error(`Fiat currency ${fiatCurrency} not found`); const fiatRateUsd = (0, NumberLike_1.toDecimal)(fiatData.rateUsd); const totalUsd = (0, NumberLike_1.toDecimal)(amountFiat).mul(fiatRateUsd); //Calculate total in crypto const cryptoData = markets.crypto.find((t) => t.id === this.currencyInfo.nativeTokenId); if (!cryptoData) throw new Error('Crypto rate not found'); const cryptoRateUsd = (0, NumberLike_1.toDecimal)(cryptoData.rateUsd); if (cryptoRateUsd.eq(0)) return this.buildAmount((0, NumberLike_1.toDecimal)(0)); const totalCrypto = totalUsd.div(cryptoRateUsd); return this.buildAmount(totalCrypto); } async fiatRate(fiatCurrency, useCache = true) { const markets = await this.context.markets.get(useCache); const cryptoData = markets.crypto.find((t) => t.id === this.currencyInfo.nativeTokenId); if (!cryptoData) throw new Error('Crypto rate not found'); const cryptoRateUsd = (0, NumberLike_1.toDecimal)(cryptoData.rateUsd); const fiatData = markets.fiat.find((t) => t.symbol === fiatCurrency); if (!fiatData) throw new Error(`Fiat currency ${fiatCurrency} not found`); const fiatRateUsd = (0, NumberLike_1.toDecimal)(fiatData.rateUsd); return cryptoRateUsd.div(fiatRateUsd); } } exports.CurrencyUtils = CurrencyUtils; //# sourceMappingURL=CurrencyUtils.js.map