Added Rates Service: Base, Coinbase, Composite

This commit is contained in:
2025-04-28 12:36:30 +00:00
committed by Jim Hamill
parent c168d6124e
commit a0395514ba
8 changed files with 590 additions and 6 deletions
@@ -0,0 +1,43 @@
import { Satoshis } from "@xocash/primitives";
import { BaseRates, type RateOptions } from "./base-rates.js";
export type RatesCompositePolicy = (rates: number[]) => number;
const ratesAveragePolicy: RatesCompositePolicy = (rates) => rates.reduce((acc, rate) => acc + rate, 0) / rates.length;
/**
* A composite rate that averages the rates of multiple rates.
*/
export class RatesComposite extends BaseRates {
constructor(private rates: BaseRates[], private policy: RatesCompositePolicy = ratesAveragePolicy) {
super();
}
public async start(): Promise<void> {
await Promise.all(this.rates.map((rate) => rate.start()));
}
public async stop(): Promise<void> {
await Promise.all(this.rates.map((rate) => rate.stop()));
}
public async getRate(currency: string, options?: Partial<RateOptions>): Promise<number> {
const rates = await Promise.all(this.rates.map((rate) => rate.getRate(currency, options)));
return this.policy(rates);
}
public async toBCH(amount: number, fromCurrency: string): Promise<Satoshis> {
const rate = await this.getRate(fromCurrency);
const bchAmount = amount / rate;
return Satoshis.fromBCH(bchAmount);
}
public async fromBCH(amount: Satoshis, toCurrency: string): Promise<number> {
const rate = await this.getRate(toCurrency);
const result = amount.toBCH() * rate;
return result;
}
}