Wallet/js/services/rate.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

'use strict';
var MINS_IN_HOUR = 60;
var MILLIS_IN_SECOND = 1000;
var RateService = function(request) {
this.isAvailable = false;
2014-08-29 12:09:39 -03:00
this.UNAVAILABLE_ERROR = 'Service is not available - check for service.isAvailable or use service.whenAvailable';
this.SAT_TO_BTC = 1 / 1e8;
this.BTC_TO_SAT = 1e8;
2014-08-29 12:09:39 -03:00
var rateServiceConfig = config.rate;
var updateFrequencySeconds = rateServiceConfig.updateFrequencySeconds || 60 * MINS_IN_HOUR;
var rateServiceUrl = rateServiceConfig.url || 'https://bitpay.com/api/rates';
2014-08-27 17:15:05 -03:00
this.queued = [];
this.alternatives = [];
var self = this;
2014-08-29 12:09:39 -03:00
var backoffSeconds = 5;
var retrieve = function() {
2014-08-27 17:15:05 -03:00
request.get({
2014-08-29 12:09:39 -03:00
url: rateServiceUrl,
2014-08-27 17:15:05 -03:00
json: true
}, function(err, response, listOfCurrencies) {
if (err) {
2014-08-29 12:09:39 -03:00
backoffSeconds *= 1.5;
setTimeout(retrieve, backoffSeconds * MILLIS_IN_SECOND);
2014-08-27 17:15:05 -03:00
return;
}
var rates = {};
2014-08-27 17:15:05 -03:00
listOfCurrencies.forEach(function(element) {
rates[element.code] = element.rate;
self.alternatives.push({
2014-08-27 17:15:05 -03:00
name: element.name,
isoCode: element.code,
rate: element.rate
});
});
self.isAvailable = true;
self.rates = rates;
self.queued.forEach(function(callback) {
2014-08-28 21:06:49 -03:00
setTimeout(callback, 1);
2014-08-27 17:15:05 -03:00
});
2014-08-29 12:09:39 -03:00
setTimeout(retrieve, updateFrequencySeconds * MILLIS_IN_SECOND);
});
};
retrieve();
};
2014-08-27 17:15:05 -03:00
RateService.prototype.whenAvailable = function(callback) {
if (this.isAvailable) {
2014-08-28 21:06:49 -03:00
setTimeout(callback, 1);
2014-08-27 17:15:05 -03:00
} else {
this.queued.push(callback);
}
};
RateService.prototype.toFiat = function(satoshis, code) {
if (!this.isAvailable) {
2014-08-29 12:09:39 -03:00
throw new Error(this.UNAVAILABLE_ERROR);
}
return satoshis * this.SAT_TO_BTC * this.rates[code];
};
RateService.prototype.fromFiat = function(amount, code) {
if (!this.isAvailable) {
2014-08-29 12:09:39 -03:00
throw new Error(this.UNAVAILABLE_ERROR);
}
return amount / this.rates[code] * this.BTC_TO_SAT;
};
2014-08-27 17:15:05 -03:00
RateService.prototype.listAlternatives = function() {
if (!this.isAvailable) {
2014-08-29 12:09:39 -03:00
throw new Error(this.UNAVAILABLE_ERROR);
2014-08-27 17:15:05 -03:00
}
var alts = [];
this.alternatives.forEach(function(element) {
alts.push({
name: element.name,
isoCode: element.isoCode
});
});
return alts;
};
angular.module('copayApp.services').service('rateService', RateService);