UNPKG

chaingate

Version:

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

55 lines 2.43 kB
import { CurrencyAmount } from './CurrencyAmount'; import { toDecimal } from '../../InternalUtils/NumberLike'; export class CurrencyUtils { client; markets; currencyInfo; constructor(client, currencyInfo, markets) { this.client = client; this.currencyInfo = currencyInfo; this.markets = markets; } buildAmount(baseAmount) { return new CurrencyAmount(this.currencyInfo, toDecimal(baseAmount), this.markets); } amount(amount, unit) { if (unit === this.currencyInfo.symbol) { return this.buildAmount(amount); } if (unit === this.currencyInfo.minimalUnitSymbol) { return this.buildAmount(toDecimal(amount).div(toDecimal(10).pow(this.currencyInfo.decimals))); } throw new Error(`Unsupported unit: ${unit}`); } async amountFiat(amountFiat, fiatCurrency, useCache = true) { const markets = await this.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 = toDecimal(fiatData.rateUsd); const totalUsd = 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 = toDecimal(cryptoData.rateUsd); if (cryptoRateUsd.eq(0)) return this.buildAmount(toDecimal(0)); const totalCrypto = totalUsd.div(cryptoRateUsd); return this.buildAmount(totalCrypto); } async fiatRate(fiatCurrency, useCache = true) { const markets = await this.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 = toDecimal(cryptoData.rateUsd); const fiatData = markets.fiat.find((t) => t.symbol === fiatCurrency); if (!fiatData) throw new Error(`Fiat currency ${fiatCurrency} not found`); const fiatRateUsd = toDecimal(fiatData.rateUsd); return cryptoRateUsd.div(fiatRateUsd); } } //# sourceMappingURL=CurrencyUtils.js.map