Skip to content
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
3 changes: 2 additions & 1 deletion packages/assets-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- `usdPrice` is not included in asset price data ([#8123](https://github.com/MetaMask/core/pull/8123))
- Add `getStateForTransactionPay()` method and `AssetsController:getStateForTransactionPay` messenger action. Returns state in the legacy format expected by transaction-pay-controller (TokenBalancesController, AccountTrackerController, TokensController, TokenRatesController, CurrencyRateController shapes) so that when `useAssetsController` is true the transaction-pay-controller can use a single action instead of five separate getState calls. Also export `formatStateForTransactionPay` and types `TransactionPayLegacyFormat`, `AccountForLegacyFormat`, `LegacyToken` from utils ([#8094](https://github.com/MetaMask/core/pull/8094))

### Changed
Expand All @@ -19,7 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- `getStateForTransactionPay()` and `formatStateForTransactionPay()` now accept optional `usdToSelectedCurrencyRate` (rate: 1 USD = N units of selected currency). When `selectedCurrency` is not USD, passing this rate ensures `currencyRates` and `marketData` use correct user-currency vs USD values; previously they incorrectly used USD price for both
- `formatExchangeRatesForBridge` and `formatStateForTransactionPay` now read both `price` (selected currency) and `usdPrice` (USD) directly from asset price data ([#8123](https://github.com/MetaMask/core/pull/8123))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Since we haven't released this yet, it is not breaking. I'm just amending the changelog.


## [2.2.0]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ export type AssetsControllerGetAssetsPriceAction = {
* action instead of MultichainAssetsRatesController, TokenRatesController,
* and CurrencyRateController.
*
* @param options - Optional options for bridge rate conversion.
* @param options.usdToSelectedCurrencyRate - When selectedCurrency is not 'usd', pass 1 USD = this many units of selected currency so that currencyRates and conversionRates use correct user-currency vs USD values; otherwise the bridge USD conversion will be wrong for non-USD currencies.
* @returns Bridge-compatible exchange rate state derived from assetsPrice and selectedCurrency.
*/
export type AssetsControllerGetExchangeRatesForBridgeAction = {
Expand All @@ -48,8 +46,6 @@ export type AssetsControllerGetExchangeRatesForBridgeAction = {
* useAssetsController is true the transaction-pay-controller can use a
* single action instead of five separate getState calls.
*
* @param options - Optional options for legacy rate conversion.
* @param options.usdToSelectedCurrencyRate - When selectedCurrency is not 'usd', pass 1 USD = this many units of selected currency so that currencyRates and marketData use correct user-currency vs USD values; otherwise conversion rates will be wrong for non-USD currencies.
* @returns Legacy-compatible state for transaction-pay-controller.
*/
export type AssetsControllerGetStateForTransactionPayAction = {
Expand Down
113 changes: 31 additions & 82 deletions packages/assets-controller/src/AssetsController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@ import type {
} from './AssetsController';
import type { PriceDataSourceConfig } from './data-sources/PriceDataSource';
import type { Caip19AssetId, AccountId } from './types';
import { formatExchangeRatesForBridge } from './utils';

jest.mock('./utils', () => {
const actual = jest.requireActual<typeof import('./utils')>('./utils');
return {
...actual,
formatExchangeRatesForBridge: jest.fn(actual.formatExchangeRatesForBridge),
};
});

const formatExchangeRatesForBridgeMock = jest.mocked(
formatExchangeRatesForBridge,
);

function createMockQueryApiClient(): ApiPlatformClient {
return { fetch: jest.fn() } as unknown as ApiPlatformClient;
Expand Down Expand Up @@ -621,99 +634,33 @@ describe('AssetsController', () => {
});

describe('getExchangeRatesForBridge', () => {
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 do not need to re-test formatExchangeRatesForBridge logic here. That function is imported from the utils module and is already being tested, we just need to check that it is being called with the correct parameters.

it('returns bridge format via action with empty state', async () => {
await withController(({ messenger }) => {
const result = (messenger.call as CallableFunction)(
'AssetsController:getExchangeRatesForBridge',
);

expect(result).toStrictEqual({
conversionRates: {},
currencyRates: {},
marketData: {},
currentCurrency: 'usd',
});
});
});

it('returns bridge format derived from assetsPrice and selectedCurrency', async () => {
const bitcoinAssetId =
'bip122:000000000019d6689c085ae165831e93/slip44:0' as Caip19AssetId;
it('calls formatExchangeRatesForBridge with state and network data', async () => {
const initialState: Partial<AssetsControllerState> = {
assetsPrice: {
[bitcoinAssetId]: {
price: 50000,
lastUpdated: 1_600_000_000,
[MOCK_NATIVE_ASSET_ID]: {
assetPriceType: 'fungible',
price: 2000,
usdPrice: 2000,
lastUpdated: 1_700_000_000_000,
},
},
selectedCurrency: 'eur',
};

await withController({ state: initialState }, ({ messenger }) => {
const result = (messenger.call as CallableFunction)(
'AssetsController:getExchangeRatesForBridge',
);

expect(result.currentCurrency).toBe('eur');
expect(result.conversionRates[bitcoinAssetId]).toBeDefined();
expect(result.conversionRates[bitcoinAssetId].rate).toBe('50000');
expect(result.conversionRates[bitcoinAssetId].currency).toBe(
'swift:0/iso4217:EUR',
);
});
});

it('returns same result as controller.getExchangeRatesForBridge()', async () => {
await withController(({ controller, messenger }) => {
const viaAction = (messenger.call as CallableFunction)(
'AssetsController:getExchangeRatesForBridge',
);
const viaMethod = controller.getExchangeRatesForBridge();

expect(viaAction).toStrictEqual(viaMethod);
});
});

it('passes usdToSelectedCurrencyRate so currencyRates have distinct conversionRate and usdConversionRate', async () => {
const ethNativeId = 'eip155:1/slip44:60' as Caip19AssetId;
const initialState: Partial<AssetsControllerState> = {
assetsPrice: {
[ethNativeId]: { price: 2000, lastUpdated: 1_700_000_000_000 },
},
selectedCurrency: 'eur',
};

await withController({ state: initialState }, ({ controller }) => {
const result = controller.getExchangeRatesForBridge({
usdToSelectedCurrencyRate: 0.92,
});

expect(result.currencyRates.ETH).toBeDefined();
expect(result.currencyRates.ETH?.conversionRate).toBe(2000 * 0.92);
expect(result.currencyRates.ETH?.usdConversionRate).toBe(2000);
});
});
});
formatExchangeRatesForBridgeMock.mockClear();

describe('getStateForTransactionPay', () => {
it('passes usdToSelectedCurrencyRate so currencyRates have distinct conversionRate and usdConversionRate', async () => {
const ethNativeId = 'eip155:1/slip44:60' as Caip19AssetId;
const initialState: Partial<AssetsControllerState> = {
assetsPrice: {
[ethNativeId]: { price: 2000, lastUpdated: 1_700_000_000_000 },
},
selectedCurrency: 'eur',
};
controller.getExchangeRatesForBridge();

await withController({ state: initialState }, ({ controller }) => {
const result = controller.getStateForTransactionPay({
usdToSelectedCurrencyRate: 0.92,
expect(formatExchangeRatesForBridgeMock).toHaveBeenCalledTimes(1);
expect(formatExchangeRatesForBridgeMock).toHaveBeenCalledWith({
assetsPrice: initialState.assetsPrice,
selectedCurrency: 'eur',
nativeAssetIdentifiers: {
'eip155:1': 'eip155:1/slip44:60',
},
networkConfigurationsByChainId: {},
});

expect(result.currentCurrency).toBe('eur');
expect(result.currencyRates.ETH).toBeDefined();
expect(result.currencyRates.ETH?.conversionRate).toBe(2000 * 0.92);
expect(result.currencyRates.ETH?.usdConversionRate).toBe(2000);
});
});
});
Expand Down Expand Up @@ -976,7 +923,9 @@ describe('AssetsController', () => {
{
assetsPrice: {
[MOCK_ASSET_ID]: {
assetPriceType: 'fungible',
price: 1.0,
usdPrice: 1.0,
pricePercentChange1d: 0.5,
lastUpdated: Date.now(),
},
Expand Down
14 changes: 2 additions & 12 deletions packages/assets-controller/src/AssetsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1138,13 +1138,9 @@ export class AssetsController extends BaseController<
* action instead of MultichainAssetsRatesController, TokenRatesController,
* and CurrencyRateController.
*
* @param options - Optional options for bridge rate conversion.
* @param options.usdToSelectedCurrencyRate - When selectedCurrency is not 'usd', pass 1 USD = this many units of selected currency so that currencyRates and conversionRates use correct user-currency vs USD values; otherwise the bridge USD conversion will be wrong for non-USD currencies.
* @returns Bridge-compatible exchange rate state derived from assetsPrice and selectedCurrency.
*/
getExchangeRatesForBridge(options?: {
usdToSelectedCurrencyRate?: number;
}): BridgeExchangeRatesFormat {
getExchangeRatesForBridge(): BridgeExchangeRatesFormat {
Copy link
Contributor

Choose a reason for hiding this comment

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

this is good and exactly what we need here 👍

const { nativeAssetIdentifiers } = this.messenger.call(
'NetworkEnablementController:getState',
);
Expand All @@ -1156,7 +1152,6 @@ export class AssetsController extends BaseController<
selectedCurrency: this.state.selectedCurrency,
nativeAssetIdentifiers,
networkConfigurationsByChainId,
usdToSelectedCurrencyRate: options?.usdToSelectedCurrencyRate,
});
}

Expand All @@ -1167,13 +1162,9 @@ export class AssetsController extends BaseController<
* useAssetsController is true the transaction-pay-controller can use a
* single action instead of five separate getState calls.
*
* @param options - Optional options for legacy rate conversion.
* @param options.usdToSelectedCurrencyRate - When selectedCurrency is not 'usd', pass 1 USD = this many units of selected currency so that currencyRates and marketData use correct user-currency vs USD values; otherwise conversion rates will be wrong for non-USD currencies.
* @returns Legacy-compatible state for transaction-pay-controller.
*/
getStateForTransactionPay(options?: {
usdToSelectedCurrencyRate?: number;
}): TransactionPayLegacyFormat {
getStateForTransactionPay(): TransactionPayLegacyFormat {
const accounts = this.#selectedAccounts;
const { nativeAssetIdentifiers } = this.messenger.call(
'NetworkEnablementController:getState',
Expand All @@ -1189,7 +1180,6 @@ export class AssetsController extends BaseController<
accounts: accounts.map((a) => ({ id: a.id, address: a.address })),
nativeAssetIdentifiers,
networkConfigurationsByChainId,
usdToSelectedCurrencyRate: options?.usdToSelectedCurrencyRate,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,9 @@ describe('PriceDataSource', () => {
{ currency: 'usd', includeMarketData: true },
);
expect(response.assetsPrice?.[MOCK_NATIVE_ASSET]).toStrictEqual({
assetPriceType: 'fungible',
price: 2500,
usdPrice: 2500,
pricePercentChange1d: 2.5,
lastUpdated: expect.any(Number),
marketCap: 1000000000,
Expand Down Expand Up @@ -241,7 +243,9 @@ describe('PriceDataSource', () => {
{ currency: 'usd', includeMarketData: true },
);
expect(response.assetsPrice?.[MOCK_NATIVE_ASSET]).toStrictEqual({
assetPriceType: 'fungible',
price: 2500,
usdPrice: 2500,
pricePercentChange1d: 2.5,
lastUpdated: expect.any(Number),
marketCap: 1000000000,
Expand Down Expand Up @@ -680,7 +684,9 @@ describe('PriceDataSource', () => {
{ currency: 'usd', includeMarketData: true },
);
expect(context.response.assetsPrice?.[MOCK_TOKEN_ASSET]).toStrictEqual({
assetPriceType: 'fungible',
price: 1.0,
usdPrice: 1.0,
pricePercentChange1d: 2.5,
lastUpdated: expect.any(Number),
marketCap: 1000000000,
Expand Down Expand Up @@ -714,7 +720,9 @@ describe('PriceDataSource', () => {
{ currency: 'usd', includeMarketData: true },
);
expect(context.response.assetsPrice?.[MOCK_TOKEN_ASSET]).toStrictEqual({
assetPriceType: 'fungible',
price: 1.0,
usdPrice: 1.0,
pricePercentChange1d: 2.5,
lastUpdated: expect.any(Number),
marketCap: 1000000000,
Expand Down Expand Up @@ -787,7 +795,12 @@ describe('PriceDataSource', () => {
const context = createMiddlewareContext({
response: {
assetsPrice: {
[anotherAsset]: { price: 1.0, lastUpdated: Date.now() },
[anotherAsset]: {
assetPriceType: 'fungible',
price: 1.0,
usdPrice: 1.0,
lastUpdated: Date.now(),
},
},
detectedAssets: {
'mock-account-id': [MOCK_TOKEN_ASSET],
Expand Down
Loading
Loading