Skip to content

Commit

Permalink
chore(currency): cache .fromId result
Browse files Browse the repository at this point in the history
  • Loading branch information
kevindavee committed Oct 3, 2024
1 parent b2019da commit 7f95092
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/currency/src/currencyManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ export class CurrencyManager<TMeta = unknown> implements CurrencyTypes.ICurrency
private readonly legacyTokens: CurrencyTypes.LegacyTokenMap;
private readonly conversionPairs: CurrencyTypes.AggregatorsMap;

private readonly knownCurrenciesById: Map<string, CurrencyTypes.CurrencyDefinition<TMeta>> =
new Map();

private static defaultInstance: CurrencyManager;

/**
Expand Down Expand Up @@ -84,7 +87,18 @@ export class CurrencyManager<TMeta = unknown> implements CurrencyTypes.ICurrency
* Gets a supported currency from its CurrencyTypes.CurrencyDefinition id
*/
fromId(id: string): CurrencyTypes.CurrencyDefinition<TMeta> | undefined {
return this.knownCurrencies.find((knownCurrency) => knownCurrency.id === id);
const cachedCurrency = this.knownCurrenciesById.get(id);
if (cachedCurrency) {
return cachedCurrency;
}

const currency = this.knownCurrencies.find((knownCurrency) => knownCurrency.id === id);
if (!currency) {
return undefined;
}

this.knownCurrenciesById.set(id, currency);
return currency;
}

/**
Expand Down
13 changes: 13 additions & 0 deletions packages/currency/test/currencyManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,19 @@ describe('CurrencyManager', () => {
});

describe('Accessing currencies', () => {
it('access a common token by its id', () => {
expect(currencyManager.fromId('USDC-multichain-moonbeam')).toMatchObject({
symbol: 'USDC-multichain',
decimals: 6,
});

// Run the test twice to ensure caching result don't break things.
expect(currencyManager.fromId('USDC-multichain-moonbeam')).toMatchObject({
symbol: 'USDC-multichain',
decimals: 6,
});
});

it('access a common token by its symbol', () => {
expect(currencyManager.from('DAI')).toMatchObject({
symbol: 'DAI',
Expand Down

0 comments on commit 7f95092

Please sign in to comment.