Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CurrencyRatesController: add baseAsset support #30

Merged
merged 5 commits into from
Nov 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ script:
- npm run format
- npm run lint
- npm run test
- npm run build
- npm run doc
- codecov
deploy:
Expand Down
22 changes: 11 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
"ethjs-provider-http": "^0.1.6",
"fetch-mock": "^6.4.3",
"husky": "^0.14.3",
"isomorphic-fetch": "^2.2.1",
"jest": "^22.1.4",
"jsdom": "11.11.0",
"lint-staged": "^6.1.0",
Expand All @@ -83,7 +82,9 @@
"ethjs-query": "^0.3.8",
"human-standard-collectible-abi": "^1.0.2",
"human-standard-token-abi": "^2.0.0",
"isomorphic-fetch": "^2.2.1",
"percentile": "^1.2.1",
"uuid": "^3.3.2",
Copy link
Contributor

@brunobar79 brunobar79 Nov 27, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't find where you are using this dep. in this PR

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were missing it, it's used in TransactionController.

"web3": "^0.20.7",
"web3-provider-engine": "^14.0.5"
}
Expand Down
34 changes: 24 additions & 10 deletions src/CurrencyRateController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@ describe('CurrencyRateController', () => {
expect(controller.state).toEqual({
conversionDate: 0,
conversionRate: 0,
currentCurrency: 'usd'
currentCurrency: 'usd',
nativeCurrency: 'eth'
});
});

it('should set default config', () => {
const controller = new CurrencyRateController();
expect(controller.config).toEqual({
currency: 'usd',
interval: 180000
currentCurrency: 'usd',
interval: 180000,
nativeCurrency: 'eth'
});
});

Expand All @@ -39,13 +41,6 @@ describe('CurrencyRateController', () => {
});
});

it('should update currency', async () => {
const controller = new CurrencyRateController({ interval: 10 });
expect(controller.state.conversionRate).toEqual(0);
await controller.updateCurrency('eur');
expect(controller.state.conversionRate).toBeGreaterThan(0);
});

it('should not update rates if disabled', async () => {
const controller = new CurrencyRateController({
disabled: true,
Expand All @@ -63,4 +58,23 @@ describe('CurrencyRateController', () => {
expect(mock.called).toBe(true);
mock.restore();
});

it('should update currency', async () => {
const controller = new CurrencyRateController({ interval: 10 });
expect(controller.state.conversionRate).toEqual(0);
await controller.updateExchangeRate();
expect(controller.state.conversionRate).toBeGreaterThan(0);
});

it('should use default base asset', async () => {
const nativeCurrency = 'FOO';
const controller = new CurrencyRateController({ nativeCurrency });
const mock = stub(window, 'fetch');
mock.resolves({
json: () => ({ USD: 1337 })
});
await controller.fetchExchangeRate('usd');
mock.restore();
expect(mock.getCall(0).args[0]).toContain(nativeCurrency);
});
});
100 changes: 60 additions & 40 deletions src/CurrencyRateController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import { safelyExecute } from './util';
*
* Currency rate controller configuration
*
* @property currency - Currently-active ISO 4217 currency code
* @property currentCurrency - Currently-active ISO 4217 currency code
* @property interval - Polling interval used to fetch new currency rate
* @property nativeCurrency - Symbol for the base asset used for conversion
*/
export interface CurrencyRateConfig extends BaseConfig {
currency: string;
currentCurrency: string;
interval: number;
nativeCurrency: string;
}

/**
Expand All @@ -21,24 +23,31 @@ export interface CurrencyRateConfig extends BaseConfig {
* Currency rate controller state
*
* @property conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
* @property conversionRate - Conversion rate from ETH to the selected currency
* @property conversionRate - Conversion rate from current base asset to the current currency
* @property currentCurrency - Currently-active ISO 4217 currency code
* @property nativeCurrency - Symbol for the base asset used for conversion
*/
export interface CurrencyRateState extends BaseState {
conversionDate: number;
conversionRate: number;
currentCurrency: string;
nativeCurrency: string;
}

/**
* Controller that passively polls on a set interval for an ETH-to-fiat exchange rate
* Controller that passively polls on a set interval for an exchange rate from the current base
* asset to the current currency
*/
export class CurrencyRateController extends BaseController<CurrencyRateConfig, CurrencyRateState> {
private activeCurrency: string = '';
private activeCurrency = '';
private activeNativeCurrency = '';
private handle?: NodeJS.Timer;

private getPricingURL(currency: string) {
return `https://api.infura.io/v1/ticker/eth${currency.toLowerCase()}`;
private getPricingURL(currentCurrency: string, nativeCurrency: string) {
return (
`https://min-api.cryptocompare.com/data/price?fsym=` +
`${nativeCurrency.toUpperCase()}&tsyms=${currentCurrency.toUpperCase()}`
);
}

/**
Expand All @@ -55,65 +64,68 @@ export class CurrencyRateController extends BaseController<CurrencyRateConfig, C
constructor(config?: Partial<CurrencyRateConfig>, state?: Partial<CurrencyRateState>) {
super(config, state);
this.defaultConfig = {
currency: 'usd',
interval: 180000
currentCurrency: 'usd',
interval: 180000,
nativeCurrency: 'eth'
};
this.defaultState = {
conversionDate: 0,
conversionRate: 0,
currentCurrency: this.defaultConfig.currency
currentCurrency: this.defaultConfig.currentCurrency,
nativeCurrency: this.defaultConfig.nativeCurrency
};
this.initialize();
}

/**
* Sets a new polling interval
* Sets a currency to track
*
* @param interval - Polling interval used to fetch new exchange rate
* @param currentCurrency - ISO 4217 currency code
*/
set interval(interval: number) {
this.handle && clearInterval(this.handle);
set currentCurrency(currentCurrency: string) {
this.activeCurrency = currentCurrency;
safelyExecute(() => this.updateExchangeRate());
this.handle = setInterval(() => {
safelyExecute(() => this.updateExchangeRate());
}, interval);
}

/**
* Sets a currency to track a exchange rate for
* Sets a new native currency
*
* @param currency - ISO 4217 currency code
* @param symbol - Symbol for the base asset
*/
set currency(currency: string) {
this.activeCurrency = currency;
set nativeCurrency(symbol: string) {
this.activeNativeCurrency = symbol;
safelyExecute(() => this.updateExchangeRate());
}

/**
* Fetches the exchange rate for a given currency
* Sets a new polling interval
*
* @param currency - ISO 4217 currency code
* @returns - Promise resolving to exchange rate for given currecy
* @param interval - Polling interval used to fetch new exchange rate
*/
async fetchExchangeRate(currency: string): Promise<CurrencyRateState> {
const response = await fetch(this.getPricingURL(currency));
const json = await response.json();
return {
conversionDate: Number(json.timestamp),
conversionRate: Number(json.bid),
currentCurrency: this.activeCurrency
};
set interval(interval: number) {
this.handle && clearInterval(this.handle);
safelyExecute(() => this.updateExchangeRate());
this.handle = setInterval(() => {
safelyExecute(() => this.updateExchangeRate());
}, interval);
}

/**
* Sets a new currency to track and fetches its exchange rate
* Fetches the exchange rate for a given currency
*
* @param currency - ISO 4217 currency code
* @returns - Promise resolving to exchange rate for given currecy
* @param nativeCurrency - Symbol for base asset
* @returns - Promise resolving to exchange rate for given currency
*/
async updateCurrency(currency: string): Promise<CurrencyRateState | void> {
this.configure({ currency });
return this.updateExchangeRate();
async fetchExchangeRate(currency: string, nativeCurrency = this.activeNativeCurrency): Promise<CurrencyRateState> {
const response = await fetch(this.getPricingURL(currency, nativeCurrency));
const json = await response.json();
return {
conversionDate: Date.now(),
conversionRate: Number(json[currency.toUpperCase()]),
currentCurrency: currency,
nativeCurrency
};
}

/**
Expand All @@ -122,11 +134,19 @@ export class CurrencyRateController extends BaseController<CurrencyRateConfig, C
* @returns Promise resolving to currency data or undefined if disabled
*/
async updateExchangeRate(): Promise<CurrencyRateState | void> {
if (this.disabled) {
if (this.disabled || !this.activeCurrency || !this.activeNativeCurrency) {
return;
}
const { conversionDate, conversionRate } = await this.fetchExchangeRate(this.activeCurrency);
this.update({ conversionDate, conversionRate, currentCurrency: this.activeCurrency });
const { conversionDate, conversionRate } = await this.fetchExchangeRate(
this.activeCurrency,
this.activeNativeCurrency
);
this.update({
conversionDate,
conversionRate,
currentCurrency: this.activeCurrency,
nativeCurrency: this.activeNativeCurrency
});
return this.state;
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/KeyringController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,9 @@ export class KeyringController extends BaseController<BaseConfig, KeyringState>
const keyrings = await Promise.all(
this.keyring.keyrings.map(async (keyring: KeyringObject, index: number) => {
const keyringAccounts = await keyring.getAccounts();
const accounts = Array.isArray(keyringAccounts) ? keyringAccounts.map((address) => toChecksumAddress(address)) : [];
const accounts = Array.isArray(keyringAccounts)
? keyringAccounts.map((address) => toChecksumAddress(address))
: [];
return {
accounts,
index,
Expand Down
1 change: 1 addition & 0 deletions tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"forin": [false],
"indent": [true, "tabs"],
"interface-name": [false],
"max-line-length": [true, 120],
"member-access": [true, "no-public"],
"member-ordering": [false],
"no-console": [false],
Expand Down