xud
Version:
Exchange Union Daemon
65 lines • 3.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnitConverter = void 0;
const UNITS_PER_CURRENCY = {
BTC: 1,
LTC: 1,
ETH: 10 ** 10,
USDT: 10 ** -2,
WETH: 10 ** 10,
DAI: 10 ** 10,
XUC: 10 ** 10,
};
let UnitConverter = /** @class */ (() => {
class UnitConverter {
constructor() {
/** Number of smallest units per currency. */
this.UNITS_PER_CURRENCY = UNITS_PER_CURRENCY;
this.init = () => {
// TODO: Populate the mapping from the database (Currency.decimalPlaces).
// this.UNITS_PER_CURRENCY = await fetchUnitsPerCurrencyFromDatabase();
};
this.amountToUnits = ({ currency, amount }) => {
const unitsPerCurrency = this.UNITS_PER_CURRENCY[currency];
if (!unitsPerCurrency) {
throw new Error(`cannot convert ${currency} amount of ${amount} to units because units per currency was not found in the database`);
}
return Math.floor(amount * unitsPerCurrency);
};
this.unitsToAmount = ({ currency, units }) => {
const unitsPerCurrency = this.UNITS_PER_CURRENCY[currency];
if (!unitsPerCurrency) {
throw new Error(`cannot convert ${currency} units of ${units} to amount because units per currency was not found in the database`);
}
return Math.floor(units / unitsPerCurrency);
};
}
}
/**
* Calculates the incoming and outgoing currencies and amounts of subunits/satoshis for an order if it is swapped.
* @param quantity The quantity of the order
* @param price The price of the order
* @param isBuy Whether the order is a buy
* @returns An object with the calculated incoming and outgoing values. The quote currency
* amount is returned as zero if the price is 0 or infinity, indicating a market order.
*/
UnitConverter.calculateInboundOutboundAmounts = (quantity, price, isBuy, pairId) => {
const [baseCurrency, quoteCurrency] = pairId.split('/');
const baseCurrencyAmount = quantity;
const quoteCurrencyAmount = price > 0 && price < Number.POSITIVE_INFINITY ?
Math.round(quantity * price) :
0; // if price is zero or infinity, this is a market order and we can't know the quote currency amount
const baseCurrencyUnits = Math.floor(baseCurrencyAmount * UNITS_PER_CURRENCY[baseCurrency]);
const quoteCurrencyUnits = Math.floor(quoteCurrencyAmount * UNITS_PER_CURRENCY[quoteCurrency]);
const inboundCurrency = isBuy ? baseCurrency : quoteCurrency;
const inboundAmount = isBuy ? baseCurrencyAmount : quoteCurrencyAmount;
const inboundUnits = isBuy ? baseCurrencyUnits : quoteCurrencyUnits;
const outboundCurrency = isBuy ? quoteCurrency : baseCurrency;
const outboundAmount = isBuy ? quoteCurrencyAmount : baseCurrencyAmount;
const outboundUnits = isBuy ? quoteCurrencyUnits : baseCurrencyUnits;
return { inboundCurrency, inboundAmount, inboundUnits, outboundCurrency, outboundAmount, outboundUnits };
};
return UnitConverter;
})();
exports.UnitConverter = UnitConverter;
//# sourceMappingURL=UnitConverter.js.map