1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-12 20:57:12 +01:00
metamask-extension/app/scripts/controllers/token-rates.js

89 lines
2.6 KiB
JavaScript
Raw Normal View History

import { ObservableStore } from '@metamask/obs-store';
import log from 'loglevel';
import { normalize as normalizeAddress } from 'eth-sig-util';
import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout';
2021-05-17 23:19:39 +02:00
import { toChecksumHexAddress } from '../../../shared/modules/hexstring-utils';
import { MINUTE, SECOND } from '../../../shared/constants/time';
const fetchWithTimeout = getFetchWithTimeout(SECOND * 30);
// By default, poll every 3 minutes
const DEFAULT_INTERVAL = MINUTE * 3;
/**
* A controller that polls for token exchange
* rates based on a user's current token list
*/
export default class TokenRatesController {
/**
* Creates a TokenRatesController
*
* @param {Object} [config] - Options to configure controller
*/
constructor({ tokensController, getNativeCurrency } = {}) {
this.store = new ObservableStore();
this.getNativeCurrency = getNativeCurrency;
this.tokens = tokensController.state.tokens;
tokensController.subscribe(({ tokens = [] }) => {
this.tokens = tokens;
});
}
/**
* Updates exchange rates for all tokens
*/
2020-11-03 00:41:28 +01:00
async updateExchangeRates() {
const contractExchangeRates = {};
const nativeCurrency = this.getNativeCurrency().toLowerCase();
const pairs = this._tokens.map((token) => token.address).join(',');
const query = `contract_addresses=${pairs}&vs_currencies=${nativeCurrency}`;
if (this._tokens.length > 0) {
try {
const response = await fetchWithTimeout(
2020-11-03 00:41:28 +01:00
`https://api.coingecko.com/api/v3/simple/token_price/ethereum?${query}`,
);
const prices = await response.json();
2020-02-15 21:34:12 +01:00
this._tokens.forEach((token) => {
2020-11-03 00:41:28 +01:00
const price =
prices[token.address.toLowerCase()] ||
2021-05-17 23:19:39 +02:00
prices[toChecksumHexAddress(token.address)];
2020-11-03 00:41:28 +01:00
contractExchangeRates[normalizeAddress(token.address)] = price
? price[nativeCurrency]
: 0;
});
} catch (error) {
2020-11-03 00:41:28 +01:00
log.warn(
`MetaMask - TokenRatesController exchange rate fetch failed.`,
error,
);
}
}
this.store.putState({ contractExchangeRates });
}
/* eslint-disable accessor-pairs */
/**
2018-04-18 23:24:36 +02:00
* @type {Array}
*/
2020-11-03 00:41:28 +01:00
set tokens(tokens) {
this._tokens = tokens;
this.updateExchangeRates();
}
/* eslint-enable accessor-pairs */
2020-11-03 00:41:28 +01:00
start(interval = DEFAULT_INTERVAL) {
this._handle && clearInterval(this._handle);
if (!interval) {
return;
}
this._handle = setInterval(() => {
this.updateExchangeRates();
}, interval);
this.updateExchangeRates();
}
2020-11-03 00:41:28 +01:00
stop() {
this._handle && clearInterval(this._handle);
}
}