Skip to content
Open
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
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
75 changes: 70 additions & 5 deletions packages/bridge-controller/src/bridge-controller.sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
DEFAULT_BRIDGE_CONTROLLER_STATE,
ETH_USDT_ADDRESS,
} from './constants/bridge';
import { ChainId, RequestStatus } from './types';
import { ChainId, RequestStatus, TokenFeatureType } from './types';
import type { BridgeControllerMessenger, QuoteResponse, TxData } from './types';
import * as balanceUtils from './utils/balance';
import { formatChainIdToDec } from './utils/caip-formatters';
Expand All @@ -25,6 +25,7 @@ import {
advanceToNthTimerThenFlush,
mockSseEventSource,
mockSseEventSourceWithMultipleDelays,
mockSseEventSourceWithWarnings,
mockSseServerError,
} from '../tests/mock-sse';

Expand Down Expand Up @@ -193,8 +194,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 +334,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 +468,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 +1102,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 +1145,64 @@ 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([]);
});
});
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
21 changes: 16 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,11 @@ 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) => {
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
2 changes: 2 additions & 0 deletions packages/bridge-controller/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ export {
RequestStatus,
BridgeUserAction,
BridgeBackgroundAction,
TokenFeatureType,
type TokenFeature,
type BridgeControllerGetStateAction,
type BridgeControllerStateChangeEvent,
} from './types';
Expand Down
15 changes: 15 additions & 0 deletions packages/bridge-controller/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import type {
QuoteResponseSchema,
QuoteSchema,
StepSchema,
TokenFeatureSchema,
TronTradeDataSchema,
TxDataSchema,
} from './utils/validators';
Expand Down Expand Up @@ -322,6 +323,15 @@ export enum ChainId {

export type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;

export enum TokenFeatureType {
MALICIOUS = 'Malicious',
WARNING = 'Warning',
INFO = 'Info',
BENIGN = 'Benign',
}

export type TokenFeature = Infer<typeof TokenFeatureSchema>;

export enum RequestStatus {
LOADING,
FETCHED,
Expand Down Expand Up @@ -376,6 +386,11 @@ export type BridgeControllerState = {
* the max amount that can be sent.
*/
minimumBalanceForRentExemptionInLamports: string | null;
/**
* Security alerts for the destination token in the current quote request,
* populated from `token_warning` SSE events.
*/
tokenWarnings: TokenFeature[];
};

export type BridgeControllerAction<
Expand Down
Loading
Loading