Skip to content

Commit d3a2341

Browse files
committed
update references
1 parent 5a84716 commit d3a2341

File tree

6 files changed

+64
-127
lines changed

6 files changed

+64
-127
lines changed

packages/assets-controllers/src/TokenRatesController.ts

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ import { isEqual } from 'lodash';
2525

2626
import { reduceInBatchesSerially, TOKEN_PRICES_BATCH_SIZE } from './assetsUtil';
2727
import { fetchExchangeRate as fetchNativeCurrencyExchangeRate } from './crypto-compare-service';
28-
import type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';
28+
import type {
29+
AbstractTokenPricesService,
30+
EvmAssetWithMarketData,
31+
} from './token-prices-service/abstract-token-prices-service';
2932
import { getNativeTokenAddress } from './token-prices-service/codefi-v2';
3033
import type {
3134
TokensControllerGetStateAction,
@@ -703,17 +706,26 @@ export class TokenRatesController extends StaticIntervalPollingController<TokenR
703706
let contractNativeInformations;
704707
const tokenPricesByTokenAddress = await reduceInBatchesSerially<
705708
Hex,
706-
Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>
709+
Record<Hex, EvmAssetWithMarketData>
707710
>({
708711
values: [...tokenAddresses].sort(),
709712
batchSize: TOKEN_PRICES_BATCH_SIZE,
710713
eachBatch: async (allTokenPricesByTokenAddress, batch) => {
711-
const tokenPricesByTokenAddressForBatch =
714+
const tokenPricesByTokenAddressForBatch = (
712715
await this.#tokenPricesService.fetchTokenPrices({
713-
tokenAddresses: batch,
714-
chainId,
716+
assets: batch.map((address) => ({
717+
chainId,
718+
address,
719+
})),
715720
currency: nativeCurrency,
716-
});
721+
})
722+
).reduce(
723+
(acc, tokenPrice) => {
724+
acc[tokenPrice.address] = tokenPrice;
725+
return acc;
726+
},
727+
{} as Record<Hex, EvmAssetWithMarketData>,
728+
);
717729

718730
return {
719731
...allTokenPricesByTokenAddress,
@@ -726,18 +738,19 @@ export class TokenRatesController extends StaticIntervalPollingController<TokenR
726738

727739
// fetch for native token
728740
if (tokenAddresses.length === 0) {
729-
const contractNativeInformationsNative =
741+
const contractNativeInformationNative =
730742
await this.#tokenPricesService.fetchTokenPrices({
731-
tokenAddresses: [],
732-
chainId,
743+
assets: [
744+
{
745+
chainId,
746+
address: getNativeTokenAddress(chainId),
747+
},
748+
],
733749
currency: nativeCurrency,
734750
});
735751

736752
contractNativeInformations = {
737-
[getNativeTokenAddress(chainId)]: {
738-
currency: nativeCurrency,
739-
...contractNativeInformationsNative[getNativeTokenAddress(chainId)],
740-
},
753+
[getNativeTokenAddress(chainId)]: contractNativeInformationNative[0],
741754
};
742755
}
743756
return Object.entries(contractNativeInformations).reduce(

packages/assets-controllers/src/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import type { TokenDisplayData } from './types';
1111
import { formatIconUrlWithProxy } from '../assetsUtil';
1212
import type { GetCurrencyRateState } from '../CurrencyRateController';
1313
import type { AbstractTokenPricesService } from '../token-prices-service';
14-
import type { TokenPrice } from '../token-prices-service/abstract-token-prices-service';
1514
import {
1615
fetchTokenMetadata,
1716
TOKEN_METADATA_NO_SUPPORT_ERROR,
@@ -172,22 +171,18 @@ export class TokenSearchDiscoveryDataController extends BaseController<
172171
this.#fetchSwapsTokensThresholdMs = fetchSwapsTokensThresholdMs;
173172
}
174173

175-
async #fetchPriceData(
176-
chainId: Hex,
177-
address: string,
178-
): Promise<TokenPrice<Hex, string> | null> {
174+
async #fetchPriceData(chainId: Hex, address: string) {
179175
const { currentCurrency } = this.messenger.call(
180176
'CurrencyRateController:getState',
181177
);
182178

183179
try {
184180
const pricesData = await this.#tokenPricesService.fetchTokenPrices({
185-
chainId,
186-
tokenAddresses: [address as Hex],
181+
assets: [{ chainId, address: address as Hex }],
187182
currency: currentCurrency,
188183
});
189184

190-
return pricesData[address as Hex] ?? null;
185+
return pricesData[0] ?? null;
191186
} catch (error) {
192187
console.error(error);
193188
return null;

packages/assets-controllers/src/TokenSearchDiscoveryDataController/types.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Hex } from '@metamask/utils';
22

3-
import type { TokenPrice } from '../token-prices-service/abstract-token-prices-service';
3+
import type { EvmAssetWithMarketData } from '../token-prices-service/abstract-token-prices-service';
44
import type { Token } from '../TokenRatesController';
55

66
export type NotFoundTokenDisplayData = {
@@ -16,7 +16,7 @@ export type FoundTokenDisplayData = {
1616
address: string;
1717
currency: string;
1818
token: Token;
19-
price: TokenPrice<Hex, string> | null;
19+
price: EvmAssetWithMarketData<Hex, string> | null;
2020
};
2121

2222
export type TokenDisplayData = NotFoundTokenDisplayData | FoundTokenDisplayData;

packages/assets-controllers/src/assetsUtil.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ import { CID } from 'multiformats/cid';
1515

1616
import type { Nft, NftMetadata } from './NftController';
1717
import type { AbstractTokenPricesService } from './token-prices-service';
18-
import { type ContractExchangeRates } from './TokenRatesController';
18+
import type { EvmAssetWithMarketData } from './token-prices-service/abstract-token-prices-service';
19+
import type { ContractExchangeRates } from './TokenRatesController';
1920

2021
/**
2122
* The maximum number of token addresses that should be sent to the Price API in
@@ -370,17 +371,26 @@ export async function fetchTokenContractExchangeRates({
370371

371372
const tokenPricesByTokenAddress = await reduceInBatchesSerially<
372373
Hex,
373-
Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>
374+
Record<Hex, EvmAssetWithMarketData>
374375
>({
375376
values: [...tokenAddresses].sort(),
376377
batchSize: TOKEN_PRICES_BATCH_SIZE,
377378
eachBatch: async (allTokenPricesByTokenAddress, batch) => {
378-
const tokenPricesByTokenAddressForBatch =
379+
const tokenPricesByTokenAddressForBatch = (
379380
await tokenPricesService.fetchTokenPrices({
380-
tokenAddresses: batch,
381-
chainId,
381+
assets: batch.map((address) => ({
382+
chainId,
383+
address,
384+
})),
382385
currency: nativeCurrency,
383-
});
386+
})
387+
).reduce(
388+
(acc, tokenPrice) => {
389+
acc[tokenPrice.address] = tokenPrice;
390+
return acc;
391+
},
392+
{} as Record<Hex, EvmAssetWithMarketData>,
393+
);
384394

385395
return {
386396
...allTokenPricesByTokenAddress,

packages/assets-controllers/src/token-prices-service/abstract-token-prices-service.ts

Lines changed: 14 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,6 @@
11
import type { ServicePolicy } from '@metamask/controller-utils';
22
import type { CaipAssetType, Hex } from '@metamask/utils';
33

4-
/**
5-
* Represents the price of a token in a currency.
6-
*/
7-
export type TokenPrice<Currency extends string> = {
8-
tokenAddress: Hex;
9-
currency: Currency;
10-
allTimeHigh: number;
11-
allTimeLow: number;
12-
circulatingSupply: number;
13-
dilutedMarketCap: number;
14-
high1d: number;
15-
low1d: number;
16-
marketCap: number;
17-
marketCapPercentChange1d: number;
18-
price: number;
19-
priceChange1d: number;
20-
pricePercentChange1d: number;
21-
pricePercentChange1h: number;
22-
pricePercentChange1y: number;
23-
pricePercentChange7d: number;
24-
pricePercentChange14d: number;
25-
pricePercentChange30d: number;
26-
pricePercentChange200d: number;
27-
totalVolume: number;
28-
};
29-
304
/**
315
* Represents an exchange rate.
326
*/
@@ -38,12 +12,15 @@ export type ExchangeRate = {
3812
usd?: number;
3913
};
4014

41-
/**
42-
* A map of token address to its price.
43-
*/
44-
export type TokenPricesByTokenAddress<Currency extends string> = {
45-
[A in Hex]: TokenPrice<Currency>;
46-
};
15+
// /**
16+
// * A map of token address to its price.
17+
// */
18+
// export type TokenPricesByTokenAddress<
19+
// ChainId extends Hex = Hex,
20+
// Currency extends string = string,
21+
// > = {
22+
// [A in Hex]: EvmAssetWithMarketData<ChainId, Currency>;
23+
// };
4724

4825
/**
4926
* A map of currency to its exchange rate.
@@ -52,19 +29,19 @@ export type ExchangeRatesByCurrency<Currency extends string> = {
5229
[C in Currency]: ExchangeRate;
5330
};
5431

55-
export type EvmAssetAddressWithChain<ChainId extends Hex> = {
32+
export type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {
5633
address: Hex;
5734
chainId: ChainId;
5835
};
5936

60-
export type EvmAssetWithId<ChainId extends Hex> =
37+
export type EvmAssetWithId<ChainId extends Hex = Hex> =
6138
EvmAssetAddressWithChain<ChainId> & {
6239
assetId: CaipAssetType;
6340
};
6441

6542
export type EvmAssetWithMarketData<
66-
ChainId extends Hex,
67-
Currency extends string,
43+
ChainId extends Hex = Hex,
44+
Currency extends string = string,
6845
> = EvmAssetWithId<ChainId> & MarketData & { currency: Currency };
6946

7047
/**
@@ -167,7 +144,7 @@ export type AbstractTokenPricesService<
167144
* @param args.currency - The desired currency of the token prices.
168145
* @returns The prices for the requested tokens.
169146
*/
170-
fetchTokenPricesV3({
147+
fetchTokenPrices({
171148
assets,
172149
currency,
173150
}: {

packages/assets-controllers/src/token-prices-service/codefi-v2.ts

Lines changed: 3 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@ import type {
2121
EvmAssetWithMarketData,
2222
ExchangeRatesByCurrency,
2323
MarketData,
24-
TokenPrice,
25-
TokenPricesByTokenAddress,
2624
} from './abstract-token-prices-service';
2725

2826
/**
@@ -449,67 +447,11 @@ export class CodefiTokenPricesServiceV2
449447
* given addresses which are expected to live on the given chain.
450448
*
451449
* @param args - The arguments to function.
452-
* @param args.chainId - An EIP-155 chain ID.
453-
* @param args.tokenAddresses - Addresses for tokens that live on the chain.
450+
* @param args.assets - The assets to get prices for.
454451
* @param args.currency - The desired currency of the token prices.
455452
* @returns The prices for the requested tokens.
456453
*/
457454
async fetchTokenPrices({
458-
chainId,
459-
tokenAddresses,
460-
currency,
461-
}: {
462-
chainId: SupportedChainId;
463-
tokenAddresses: Hex[];
464-
currency: SupportedCurrency;
465-
}): Promise<Partial<TokenPricesByTokenAddress<SupportedCurrency>>> {
466-
const chainIdAsNumber = hexToNumber(chainId);
467-
468-
const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);
469-
url.searchParams.append(
470-
'tokenAddresses',
471-
[getNativeTokenAddress(chainId), ...tokenAddresses].join(','),
472-
);
473-
url.searchParams.append('vsCurrency', currency);
474-
url.searchParams.append('includeMarketData', 'true');
475-
476-
const addressCryptoDataMap: MarketDataByTokenAddress =
477-
await this.#policy.execute(() =>
478-
handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),
479-
);
480-
481-
return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce(
482-
(
483-
obj: Partial<TokenPricesByTokenAddress<SupportedCurrency>>,
484-
tokenAddress,
485-
) => {
486-
// The Price API lowercases both currency and token addresses, so we have
487-
// to keep track of them and make sure we return the original versions.
488-
const lowercasedTokenAddress =
489-
tokenAddress.toLowerCase() as Lowercase<Hex>;
490-
491-
const marketData = addressCryptoDataMap[lowercasedTokenAddress];
492-
493-
if (!marketData) {
494-
return obj;
495-
}
496-
497-
const token: TokenPrice<SupportedCurrency> = {
498-
tokenAddress,
499-
currency,
500-
...marketData,
501-
};
502-
503-
return {
504-
...obj,
505-
[tokenAddress]: token,
506-
};
507-
},
508-
{},
509-
) as Partial<TokenPricesByTokenAddress<SupportedCurrency>>;
510-
}
511-
512-
async fetchTokenPricesV3({
513455
assets,
514456
currency,
515457
}: {
@@ -557,11 +499,11 @@ export class CodefiTokenPricesServiceV2
557499

558500
return {
559501
...assetWithId,
560-
currency,
561502
...marketData,
503+
currency,
562504
};
563505
})
564-
.filter((x) => x !== undefined);
506+
.filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));
565507
}
566508

567509
/**

0 commit comments

Comments
 (0)