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: 0 additions & 3 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -584,9 +584,6 @@
}
},
"packages/bridge-controller/tests/mock-sse.ts": {
"@typescript-eslint/explicit-function-return-type": {
"count": 10
},
"id-length": {
"count": 2
}
Expand Down
5 changes: 5 additions & 0 deletions packages/bridge-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Consume `token_warning` SSE events from the bridge-api quote stream and expose them as `tokenWarnings` in `BridgeControllerState` ([#8198](https://github.com/MetaMask/core/pull/8198))
- Export `TokenFeature` type and `TokenFeatureType` enum for use by clients ([#8198](https://github.com/MetaMask/core/pull/8198))

### Changed

- Bump `@metamask/assets-controller` from `^2.4.0` to `^3.0.0` ([#8232](https://github.com/MetaMask/core/pull/8232))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ exports[`BridgeController SSE should rethrow error from server 1`] = `
"quotesInitialLoadTime": null,
"quotesLoadingStatus": 0,
"quotesRefreshCount": 0,
"tokenWarnings": [],
}
`;

Expand Down Expand Up @@ -301,6 +302,7 @@ exports[`BridgeController SSE should trigger quote polling if request is valid 1
"quotesInitialLoadTime": null,
"quotesLoadingStatus": 0,
"quotesRefreshCount": 0,
"tokenWarnings": [],
}
`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ exports[`BridgeController should handle errors from fetchBridgeQuotes 1`] = `
"quotesInitialLoadTime": 10000,
"quotesLoadingStatus": 1,
"quotesRefreshCount": 1,
"tokenWarnings": [],
}
`;

Expand All @@ -49,6 +50,7 @@ exports[`BridgeController should handle errors from fetchBridgeQuotes 2`] = `
"quotesInitialLoadTime": 10000,
"quotesLoadingStatus": 1,
"quotesRefreshCount": 1,
"tokenWarnings": [],
}
`;

Expand Down Expand Up @@ -812,6 +814,7 @@ exports[`BridgeController updateBridgeQuoteRequestParams should trigger quote po
"quotesLastFetched": null,
"quotesLoadingStatus": 0,
"quotesRefreshCount": 0,
"tokenWarnings": [],
}
`;

Expand Down Expand Up @@ -840,6 +843,7 @@ exports[`BridgeController updateBridgeQuoteRequestParams should trigger quote po
"quotesInitialLoadTime": 10000,
"quotesLoadingStatus": 1,
"quotesRefreshCount": 1,
"tokenWarnings": [],
}
`;

Expand Down
172 changes: 168 additions & 4 deletions packages/bridge-controller/src/bridge-controller.sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import * as balanceUtils from './utils/balance';
import { formatChainIdToDec } from './utils/caip-formatters';
import * as featureFlagUtils from './utils/feature-flags';
import * as fetchUtils from './utils/fetch';
import { TokenFeatureType } from './utils/validators';
import { flushPromises } from '../../../tests/helpers';
import mockBridgeQuotesErc20Erc20 from '../tests/mock-quotes-erc20-erc20.json';
import mockBridgeQuotesNativeErc20Eth from '../tests/mock-quotes-native-erc20-eth.json';
Expand All @@ -25,6 +26,7 @@ import {
advanceToNthTimerThenFlush,
mockSseEventSource,
mockSseEventSourceWithMultipleDelays,
mockSseEventSourceWithWarnings,
mockSseServerError,
} from '../tests/mock-sse';

Expand Down Expand Up @@ -193,8 +195,9 @@ describe('BridgeController SSE', function () {
'AUTH_TOKEN',
BRIDGE_PROD_API_BASE_URL,
{
onValidationFailure: expect.any(Function),
onQuoteValidationFailure: expect.any(Function),
onValidQuoteReceived: expect.any(Function),
onTokenWarning: expect.any(Function),
onClose: expect.any(Function),
},
'13.8.0',
Expand Down Expand Up @@ -332,8 +335,9 @@ describe('BridgeController SSE', function () {
'AUTH_TOKEN',
BRIDGE_PROD_API_BASE_URL,
{
onValidationFailure: expect.any(Function),
onQuoteValidationFailure: expect.any(Function),
onValidQuoteReceived: expect.any(Function),
onTokenWarning: expect.any(Function),
onClose: expect.any(Function),
},
'13.8.0',
Expand Down Expand Up @@ -465,8 +469,9 @@ describe('BridgeController SSE', function () {
'AUTH_TOKEN',
BRIDGE_PROD_API_BASE_URL,
{
onValidationFailure: expect.any(Function),
onQuoteValidationFailure: expect.any(Function),
onValidQuoteReceived: expect.any(Function),
onTokenWarning: expect.any(Function),
onClose: expect.any(Function),
},
'13.8.0',
Expand Down Expand Up @@ -1098,8 +1103,9 @@ describe('BridgeController SSE', function () {
'AUTH_TOKEN',
BRIDGE_PROD_API_BASE_URL,
{
onValidationFailure: expect.any(Function),
onQuoteValidationFailure: expect.any(Function),
onValidQuoteReceived: expect.any(Function),
onTokenWarning: expect.any(Function),
onClose: expect.any(Function),
},
'13.8.0',
Expand Down Expand Up @@ -1140,4 +1146,162 @@ describe('BridgeController SSE', function () {
// eslint-disable-next-line jest/no-restricted-matchers
expect(trackMetaMetricsFn.mock.calls).toMatchSnapshot();
});

it('should populate tokenWarnings from token_warning SSE events', async function () {
const mockWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.MALICIOUS,
description: 'Token is a honeypot',
};
mockFetchFn.mockImplementationOnce(async () => {
return mockSseEventSourceWithWarnings(
mockBridgeQuotesNativeErc20 as QuoteResponse[],
[mockWarning],
);
});

await bridgeController.updateBridgeQuoteRequestParams(
quoteRequest,
metricsContext,
);

expect(bridgeController.state.tokenWarnings).toStrictEqual([]);

jest.advanceTimersByTime(1000);
await advanceToNthTimerThenFlush();

// After stream completes
jest.advanceTimersByTime(5000);
await flushPromises();

expect(bridgeController.state.tokenWarnings).toStrictEqual([mockWarning]);
expect(bridgeController.state.quotes.length).toBeGreaterThan(0);
});

it('should clear tokenWarnings on resetState', async function () {
const mockWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.MALICIOUS,
description: 'Token is a honeypot',
};
mockFetchFn.mockImplementationOnce(async () => {
return mockSseEventSourceWithWarnings(
mockBridgeQuotesNativeErc20 as QuoteResponse[],
[mockWarning],
);
});

await bridgeController.updateBridgeQuoteRequestParams(
quoteRequest,
metricsContext,
);

jest.advanceTimersByTime(1000);
await advanceToNthTimerThenFlush();
jest.advanceTimersByTime(5000);
await flushPromises();

expect(bridgeController.state.tokenWarnings).toStrictEqual([mockWarning]);

bridgeController.resetState();
expect(bridgeController.state.tokenWarnings).toStrictEqual([]);
});

it('should deduplicate tokenWarnings with the same feature_id', async function () {
const mockWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.MALICIOUS,
description: 'Token is a honeypot',
};
const duplicateWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.MALICIOUS,
description: 'Duplicate warning',
};
mockFetchFn.mockImplementationOnce(async () => {
return mockSseEventSourceWithWarnings(
mockBridgeQuotesNativeErc20 as QuoteResponse[],
[mockWarning, duplicateWarning],
);
});

await bridgeController.updateBridgeQuoteRequestParams(
quoteRequest,
metricsContext,
);

jest.advanceTimersByTime(1000);
await advanceToNthTimerThenFlush();
jest.advanceTimersByTime(5000);
await flushPromises();

expect(bridgeController.state.tokenWarnings).toStrictEqual([mockWarning]);
});

it('should deduplicate tokenWarnings with the same feature_id but different type', async function () {
const maliciousWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.MALICIOUS,
description: 'Token is a honeypot',
};
const infoWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.INFO,
description: 'Informational notice',
};
mockFetchFn.mockImplementationOnce(async () => {
return mockSseEventSourceWithWarnings(
mockBridgeQuotesNativeErc20 as QuoteResponse[],
[maliciousWarning, infoWarning],
);
});

await bridgeController.updateBridgeQuoteRequestParams(
quoteRequest,
metricsContext,
);

jest.advanceTimersByTime(1000);
await advanceToNthTimerThenFlush();
jest.advanceTimersByTime(5000);
await flushPromises();

expect(bridgeController.state.tokenWarnings).toStrictEqual([
maliciousWarning,
]);
});

it('should keep tokenWarnings with the same type but different feature_id', async function () {
const honeypotWarning = {
feature_id: 'HONEYPOT',
type: TokenFeatureType.MALICIOUS,
description: 'Token is a honeypot',
};
const fakeTokenWarning = {
feature_id: 'FAKE_TOKEN',
type: TokenFeatureType.MALICIOUS,
description: 'Possible fake token',
};
mockFetchFn.mockImplementationOnce(async () => {
return mockSseEventSourceWithWarnings(
mockBridgeQuotesNativeErc20 as QuoteResponse[],
[honeypotWarning, fakeTokenWarning],
);
});

await bridgeController.updateBridgeQuoteRequestParams(
quoteRequest,
metricsContext,
);

jest.advanceTimersByTime(1000);
await advanceToNthTimerThenFlush();
jest.advanceTimersByTime(5000);
await flushPromises();

expect(bridgeController.state.tokenWarnings).toStrictEqual([
honeypotWarning,
fakeTokenWarning,
]);
});
});
2 changes: 2 additions & 0 deletions packages/bridge-controller/src/bridge-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3474,6 +3474,7 @@ describe('BridgeController', function () {
"quotesLastFetched": null,
"quotesLoadingStatus": null,
"quotesRefreshCount": 0,
"tokenWarnings": [],
}
`);
});
Expand Down Expand Up @@ -3508,6 +3509,7 @@ describe('BridgeController', function () {
"quotesLastFetched": null,
"quotesLoadingStatus": null,
"quotesRefreshCount": 0,
"tokenWarnings": [],
}
`);
});
Expand Down
26 changes: 21 additions & 5 deletions packages/bridge-controller/src/bridge-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ const metadata: StateMetadata<BridgeControllerState> = {
includeInDebugSnapshot: false,
usedInUi: true,
},
tokenWarnings: {
includeInStateLogs: true,
persist: false,
includeInDebugSnapshot: false,
usedInUi: true,
},
};

/**
Expand Down Expand Up @@ -392,7 +398,7 @@ export class BridgeController extends StaticIntervalPollingController<BridgePoll
this.#clientVersion,
);

this.#trackResponseValidationFailures(validationFailures);
this.#trackQuoteValidationFailures(validationFailures);

const quotesWithFees = await appendFeesToQuotes(
baseQuotes,
Expand All @@ -404,9 +410,7 @@ export class BridgeController extends StaticIntervalPollingController<BridgePoll
return sortQuotes(quotesWithFees, featureId);
};

readonly #trackResponseValidationFailures = (
validationFailures: string[],
) => {
readonly #trackQuoteValidationFailures = (validationFailures: string[]) => {
if (validationFailures.length === 0) {
return;
}
Expand Down Expand Up @@ -609,6 +613,7 @@ export class BridgeController extends StaticIntervalPollingController<BridgePoll
DEFAULT_BRIDGE_CONTROLLER_STATE.assetExchangeRates;
state.minimumBalanceForRentExemptionInLamports =
DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;
state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;
});
};

Expand Down Expand Up @@ -651,6 +656,7 @@ export class BridgeController extends StaticIntervalPollingController<BridgePoll
this.update((state) => {
state.quoteRequest = updatedQuoteRequest;
state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;
state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;
state.quotesLastFetched = Date.now();
state.quotesLoadingStatus = RequestStatus.LOADING;
});
Expand Down Expand Up @@ -794,7 +800,7 @@ export class BridgeController extends StaticIntervalPollingController<BridgePoll
jwt,
this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,
{
onValidationFailure: this.#trackResponseValidationFailures,
onQuoteValidationFailure: this.#trackQuoteValidationFailures,
onValidQuoteReceived: async (quote: QuoteResponse) => {
const feeAppendPromise = (async () => {
const quotesWithFees = await appendFeesToQuotes(
Expand Down Expand Up @@ -837,6 +843,16 @@ export class BridgeController extends StaticIntervalPollingController<BridgePoll
// The promise is also tracked in pendingFeeAppendPromises for onClose to wait for
await feeAppendPromise;
},
onTokenWarning: (warning) => {
this.update((state) => {
const isDuplicate = state.tokenWarnings.some(
(existing) => existing.feature_id === warning.feature_id,
);
if (!isDuplicate) {
state.tokenWarnings = [...state.tokenWarnings, warning];
}
});
},
onClose: async () => {
// Wait for all pending appendFeesToQuotes operations to complete
// before setting quotesLoadingStatus to FETCHED
Expand Down
1 change: 1 addition & 0 deletions packages/bridge-controller/src/constants/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export const DEFAULT_BRIDGE_CONTROLLER_STATE: BridgeControllerState = {
quotesRefreshCount: 0,
assetExchangeRates: {},
minimumBalanceForRentExemptionInLamports: '0',
tokenWarnings: [],
};

export const METABRIDGE_CHAIN_TO_ADDRESS_MAP: Record<Hex, string> = {
Expand Down
Loading
Loading