Skip to content

Commit

Permalink
chore: Merge main, address conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
gambinish committed Nov 21, 2024
2 parents 660ed55 + 02d52b4 commit bc6c4df
Show file tree
Hide file tree
Showing 46 changed files with 5,802 additions and 296 deletions.
10 changes: 10 additions & 0 deletions app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 47 additions & 2 deletions app/scripts/controllers/bridge/bridge-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,27 @@ const messengerMock = {
publish: jest.fn(),
} as unknown as jest.Mocked<BridgeControllerMessenger>;

jest.mock('@ethersproject/contracts', () => {
return {
Contract: jest.fn(() => ({
allowance: jest.fn(() => '100000000000000000000'),
})),
};
});

jest.mock('@ethersproject/providers', () => {
return {
Web3Provider: jest.fn(),
};
});

describe('BridgeController', function () {
let bridgeController: BridgeController;

beforeAll(function () {
bridgeController = new BridgeController({ messenger: messengerMock });
bridgeController = new BridgeController({
messenger: messengerMock,
});
});

beforeEach(() => {
Expand All @@ -43,6 +59,18 @@ describe('BridgeController', function () {
'extension-support': true,
'src-network-allowlist': [10, 534352],
'dest-network-allowlist': [137, 42161],
'approval-gas-multiplier': {
'137': 1.1,
'42161': 1.2,
'10': 1.3,
'534352': 1.4,
},
'bridge-gas-multiplier': {
'137': 2.1,
'42161': 2.2,
'10': 2.3,
'534352': 2.4,
},
});
nock(BRIDGE_API_BASE_URL)
.get('/getTokens?chainId=10')
Expand Down Expand Up @@ -507,7 +535,10 @@ describe('BridgeController', function () {
bridgeController,
'startPollingByNetworkClientId',
);
messengerMock.call.mockReturnValueOnce({ address: '0x123' } as never);
messengerMock.call.mockReturnValue({
address: '0x123',
provider: jest.fn(),
} as never);

bridgeController.updateBridgeQuoteRequestParams({
srcChainId: 1,
Expand Down Expand Up @@ -536,4 +567,18 @@ describe('BridgeController', function () {
}),
);
});

describe('getBridgeERC20Allowance', () => {
it('should return the atomic allowance of the ERC20 token contract', async () => {
messengerMock.call.mockReturnValue({
address: '0x123',
provider: jest.fn(),
} as never);
const allowance = await bridgeController.getBridgeERC20Allowance(
'0x1f9840a85d5af5bf1d1762f925bdaddc4201f984',
'0xa',
);
expect(allowance).toBe('100000000000000000000');
});
});
});
38 changes: 37 additions & 1 deletion app/scripts/controllers/bridge/bridge-controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { StateMetadata } from '@metamask/base-controller';
import { add0x, Hex } from '@metamask/utils';
import { StaticIntervalPollingController } from '@metamask/polling-controller';
import { NetworkClientId } from '@metamask/network-controller';
import { StateMetadata } from '@metamask/base-controller';
import { Contract } from '@ethersproject/contracts';
import { abiERC20 } from '@metamask/metamask-eth-abis';
import { Web3Provider } from '@ethersproject/providers';
import { BigNumber } from '@ethersproject/bignumber';
import {
fetchBridgeFeatureFlags,
fetchBridgeQuotes,
Expand All @@ -25,6 +29,7 @@ import {
DEFAULT_BRIDGE_CONTROLLER_STATE,
REFRESH_INTERVAL_MS,
RequestStatus,
METABRIDGE_CHAIN_TO_ADDRESS_MAP,
} from './constants';
import {
BridgeControllerState,
Expand Down Expand Up @@ -60,6 +65,8 @@ export default class BridgeController extends StaticIntervalPollingController<

this.setIntervalLength(REFRESH_INTERVAL_MS);

this.#abortController = new AbortController();
// Register action handlers
this.messagingSystem.registerActionHandler(
`${BRIDGE_CONTROLLER_NAME}:setBridgeFeatureFlags`,
this.setBridgeFeatureFlags.bind(this),
Expand All @@ -80,6 +87,10 @@ export default class BridgeController extends StaticIntervalPollingController<
`${BRIDGE_CONTROLLER_NAME}:resetState`,
this.resetState.bind(this),
);
this.messagingSystem.registerActionHandler(
`${BRIDGE_CONTROLLER_NAME}:getBridgeERC20Allowance`,
this.getBridgeERC20Allowance.bind(this),
);
}

_executePoll = async (
Expand Down Expand Up @@ -277,4 +288,29 @@ export default class BridgeController extends StaticIntervalPollingController<
chainId,
);
}

/**
*
* @param contractAddress - The address of the ERC20 token contract
* @param chainId - The hex chain ID of the bridge network
* @returns The atomic allowance of the ERC20 token contract
*/
getBridgeERC20Allowance = async (
contractAddress: string,
chainId: Hex,
): Promise<string> => {
const provider = this.#getSelectedNetworkClient()?.provider;
if (!provider) {
throw new Error('No provider found');
}

const web3Provider = new Web3Provider(provider);
const contract = new Contract(contractAddress, abiERC20, web3Provider);
const { address: walletAddress } = this.#getSelectedAccount();
const allowance = await contract.allowance(
walletAddress,
METABRIDGE_CHAIN_TO_ADDRESS_MAP[chainId],
);
return BigNumber.from(allowance).toString();
};
}
7 changes: 7 additions & 0 deletions app/scripts/controllers/bridge/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { zeroAddress } from 'ethereumjs-util';
import { Hex } from '@metamask/utils';
import { METABRIDGE_ETHEREUM_ADDRESS } from '../../../../shared/constants/bridge';
import { CHAIN_IDS } from '../../../../shared/constants/network';
import { BridgeControllerState, BridgeFeatureFlagsKey } from './types';

export const BRIDGE_CONTROLLER_NAME = 'BridgeController';
Expand Down Expand Up @@ -36,3 +39,7 @@ export const DEFAULT_BRIDGE_CONTROLLER_STATE: BridgeControllerState = {
quotesLoadingStatus: undefined,
quotesRefreshCount: 0,
};

export const METABRIDGE_CHAIN_TO_ADDRESS_MAP: Record<Hex, string> = {
[CHAIN_IDS.MAINNET]: METABRIDGE_ETHEREUM_ADDRESS,
};
2 changes: 2 additions & 0 deletions app/scripts/controllers/bridge/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export enum BridgeUserAction {
export enum BridgeBackgroundAction {
SET_FEATURE_FLAGS = 'setBridgeFeatureFlags',
RESET_STATE = 'resetState',
GET_BRIDGE_ERC20_ALLOWANCE = 'getBridgeERC20Allowance',
}

type BridgeControllerAction<FunctionName extends keyof BridgeController> = {
Expand All @@ -64,6 +65,7 @@ type BridgeControllerAction<FunctionName extends keyof BridgeController> = {
type BridgeControllerActions =
| BridgeControllerAction<BridgeBackgroundAction.SET_FEATURE_FLAGS>
| BridgeControllerAction<BridgeBackgroundAction.RESET_STATE>
| BridgeControllerAction<BridgeBackgroundAction.GET_BRIDGE_ERC20_ALLOWANCE>
| BridgeControllerAction<BridgeUserAction.SELECT_SRC_NETWORK>
| BridgeControllerAction<BridgeUserAction.SELECT_DEST_NETWORK>
| BridgeControllerAction<BridgeUserAction.UPDATE_QUOTE_PARAMS>;
Expand Down
20 changes: 12 additions & 8 deletions app/scripts/lib/createRPCMethodTrackingMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
} from '../../../ui/helpers/utils/metrics';
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
import { REDESIGN_APPROVAL_TYPES } from '../../../ui/pages/confirmations/utils/confirm';
import { shouldUseRedesignForSignatures } from '../../../shared/lib/confirmation.utils';
import { getSnapAndHardwareInfoForMetrics } from './snap-keyring/metrics';

/**
Expand Down Expand Up @@ -196,6 +196,7 @@ function finalizeSignatureFragment(
* @param {Function} opts.getAccountType
* @param {Function} opts.getDeviceModel
* @param {Function} opts.isConfirmationRedesignEnabled
* @param {Function} opts.isRedesignedConfirmationsDeveloperEnabled
* @param {RestrictedControllerMessenger} opts.snapAndHardwareMessenger
* @param {number} [opts.globalRateLimitTimeout] - time, in milliseconds, of the sliding
* time window that should limit the number of method calls tracked to globalRateLimitMaxAmount.
Expand All @@ -214,6 +215,7 @@ export default function createRPCMethodTrackingMiddleware({
getAccountType,
getDeviceModel,
isConfirmationRedesignEnabled,
isRedesignedConfirmationsDeveloperEnabled,
snapAndHardwareMessenger,
appStateController,
metaMetricsController,
Expand Down Expand Up @@ -315,13 +317,15 @@ export default function createRPCMethodTrackingMiddleware({
req.securityAlertResponse.description;
}

const isConfirmationRedesign =
isConfirmationRedesignEnabled() &&
REDESIGN_APPROVAL_TYPES.find(
(type) => type === MESSAGE_TYPE_TO_APPROVAL_TYPE[method],
);

if (isConfirmationRedesign) {
if (
shouldUseRedesignForSignatures({
approvalType: MESSAGE_TYPE_TO_APPROVAL_TYPE[method],
isRedesignedSignaturesUserSettingEnabled:
isConfirmationRedesignEnabled(),
isRedesignedConfirmationsDeveloperEnabled:
isRedesignedConfirmationsDeveloperEnabled(),
})
) {
eventProperties.ui_customizations = [
...(eventProperties.ui_customizations || []),
MetaMetricsEventUiCustomization.RedesignedConfirmation,
Expand Down
13 changes: 13 additions & 0 deletions app/scripts/lib/createRPCMethodTrackingMiddleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ const createHandler = (opts) =>
appStateController,
metaMetricsController,
isConfirmationRedesignEnabled: () => false,
isRedesignedConfirmationsDeveloperEnabled: () => false,
...opts,
});

Expand Down Expand Up @@ -217,10 +218,22 @@ describe('createRPCMethodTrackingMiddleware', () => {
});

describe('participateInMetaMetrics is set to true', () => {
const originalEnableConfirmationRedesign =
process.env.ENABLE_CONFIRMATION_REDESIGN;

beforeEach(() => {
metaMetricsController.setParticipateInMetaMetrics(true);
});

beforeAll(() => {
process.env.ENABLE_CONFIRMATION_REDESIGN = 'false';
});

afterAll(() => {
process.env.ENABLE_CONFIRMATION_REDESIGN =
originalEnableConfirmationRedesign;
});

it(`should immediately track a ${MetaMetricsEventName.SignatureRequested} event`, async () => {
const req = {
id: MOCK_ID,
Expand Down
32 changes: 10 additions & 22 deletions app/scripts/lib/transaction/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,12 @@ import {
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
} from '../../../../ui/helpers/utils/metrics';
import {
REDESIGN_DEV_TRANSACTION_TYPES,
REDESIGN_USER_TRANSACTION_TYPES,
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
} from '../../../../ui/pages/confirmations/utils';

import {
getSnapAndHardwareInfoForMetrics,
type SnapAndHardwareMessenger,
} from '../snap-keyring/metrics';
import { shouldUseRedesignForTransactions } from '../../../../shared/lib/confirmation.utils';

export type TransactionMetricsRequest = {
createEventFragment: (
Expand Down Expand Up @@ -996,23 +992,15 @@ async function buildEventFragmentProperties({
if (simulationFails) {
uiCustomizations.push(MetaMetricsEventUiCustomization.GasEstimationFailed);
}
const isRedesignedConfirmationsDeveloperSettingEnabled =
transactionMetricsRequest.getIsRedesignedConfirmationsDeveloperEnabled() ||
process.env.ENABLE_CONFIRMATION_REDESIGN === 'true';

const isRedesignedTransactionsUserSettingEnabled =
transactionMetricsRequest.getRedesignedTransactionsEnabled();

if (
(isRedesignedConfirmationsDeveloperSettingEnabled &&
REDESIGN_DEV_TRANSACTION_TYPES.includes(
transactionMeta.type as TransactionType,
)) ||
(isRedesignedTransactionsUserSettingEnabled &&
REDESIGN_USER_TRANSACTION_TYPES.includes(
transactionMeta.type as TransactionType,
))
) {
const isRedesignedForTransaction = shouldUseRedesignForTransactions({
transactionMetadataType: transactionMeta.type as TransactionType,
isRedesignedTransactionsUserSettingEnabled:
transactionMetricsRequest.getRedesignedTransactionsEnabled(),
isRedesignedConfirmationsDeveloperEnabled:
transactionMetricsRequest.getIsRedesignedConfirmationsDeveloperEnabled(),
});
if (isRedesignedForTransaction) {
uiCustomizations.push(
MetaMetricsEventUiCustomization.RedesignedConfirmation,
);
Expand Down
Loading

0 comments on commit bc6c4df

Please sign in to comment.