diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index fb5338165573..8f65ecc54966 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -496,6 +496,7 @@ app/util/parseAmount.test.ts @MetaMask/swaps-engineers @MetaMask app/core/Engine/wallet-init/initialization* @MetaMask/mobile-platform @MetaMask/core-platform app/core/Engine/wallet-init/keyrings* @MetaMask/accounts-engineers @MetaMask/mobile-platform @MetaMask/core-platform app/core/Engine/wallet-init/instance-options/analytics-controller* @MetaMask/mobile-platform @MetaMask/core-platform +app/core/Engine/wallet-init/instance-options/geolocation-api-service* @MetaMask/mobile-platform @MetaMask/core-platform app/core/Engine/wallet-init/listeners/ @MetaMask/mobile-platform @MetaMask/core-platform app/core/Engine/wallet-init/messengers/analytics-controller-messenger* @MetaMask/mobile-platform @MetaMask/core-platform app/core/Engine/wallet-init/instance-options/approval-controller* @MetaMask/confirmations diff --git a/app/core/Engine/Engine.ts b/app/core/Engine/Engine.ts index 551176c3c138..5d8f7aa2d5dc 100644 --- a/app/core/Engine/Engine.ts +++ b/app/core/Engine/Engine.ts @@ -147,9 +147,7 @@ import { earnControllerInit } from './controllers/earn-controller-init'; import { moneyAccountControllerInit } from './controllers/money-account-controller-init'; import { moneyAccountBalanceServiceInit } from './controllers/money-account-balance-service-init'; import { moneyAccountApiDataServiceInit } from './controllers/money-account-api-data-service-init'; -import { geolocationApiServiceInit } from './controllers/geolocation-api-service-init'; import { sentinelApiServiceInit } from './controllers/sentinel-api-service-init'; -import { geolocationControllerInit } from './controllers/geolocation-controller'; import { rewardsDataServiceInit } from './controllers/rewards-data-service-init'; import { rewardsMoneyDataServiceInit } from './controllers/rewards-money-data-service-init'; import { type RemoteFeatureFlagControllerState } from '@metamask/remote-feature-flag-controller'; @@ -321,9 +319,7 @@ export class Engine { MoneyAccountController: moneyAccountControllerInit, MoneyAccountBalanceService: moneyAccountBalanceServiceInit, MoneyAccountApiDataService: moneyAccountApiDataServiceInit, - GeolocationApiService: geolocationApiServiceInit, SentinelApiService: sentinelApiServiceInit, - GeolocationController: geolocationControllerInit, PredictVenueController: predictVenueControllerInit, TokensController: tokensControllerInit, MultichainNetworkController: multichainNetworkControllerInit, @@ -424,7 +420,9 @@ export class Engine { const seedlessOnboardingController = this.#wallet.getInstance( 'SeedlessOnboardingController', ); - const geolocationController = messengerClientsByName.GeolocationController; + const geolocationController = this.#wallet.getInstance( + 'GeolocationController', + ); const perpsController = messengerClientsByName.PerpsController; const phishingController = messengerClientsByName.PhishingController; const predictController = messengerClientsByName.PredictController; diff --git a/app/core/Engine/controllers/geolocation-api-service-init.test.ts b/app/core/Engine/controllers/geolocation-api-service-init.test.ts deleted file mode 100644 index b219a5d86635..000000000000 --- a/app/core/Engine/controllers/geolocation-api-service-init.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { buildMessengerClientInitRequestMock } from '../utils/test-utils'; -import { ExtendedMessenger } from '../../ExtendedMessenger'; -import { getGeolocationApiServiceMessenger } from '../messengers/geolocation-api-service-messenger'; -import type { MessengerClientInitRequest } from '../types'; -import { geolocationApiServiceInit } from './geolocation-api-service-init'; -import { - GeolocationApiService, - Env, - type GeolocationApiServiceMessenger, -} from '@metamask/geolocation-controller'; -import { MOCK_ANY_NAMESPACE, type MockAnyNamespace } from '@metamask/messenger'; - -jest.mock('@metamask/geolocation-controller'); - -jest.mock('../../../components/UI/Ramp/utils/getSdkEnvironment', () => ({ - getSdkEnvironment: jest.fn(), -})); - -import { getSdkEnvironment } from '../../../components/UI/Ramp/utils/getSdkEnvironment'; -import { SdkEnvironment } from '../../../components/UI/Ramp/types/legacyDeposit'; -const mockGetSdkEnvironment = jest.mocked(getSdkEnvironment); - -function getInitRequestMock(): jest.Mocked< - MessengerClientInitRequest -> { - const baseMessenger = new ExtendedMessenger({ - namespace: MOCK_ANY_NAMESPACE, - }); - - return { - ...buildMessengerClientInitRequestMock(baseMessenger), - controllerMessenger: getGeolocationApiServiceMessenger(baseMessenger), - initMessenger: undefined, - }; -} - -describe('geolocationApiServiceInit', () => { - beforeEach(() => { - jest.clearAllMocks(); - mockGetSdkEnvironment.mockReturnValue(SdkEnvironment.Production); - }); - - it('initializes the service', () => { - const { controller } = geolocationApiServiceInit(getInitRequestMock()); - expect(controller).toBeInstanceOf(GeolocationApiService); - }); - - it('passes Env.PRD for production environment', () => { - mockGetSdkEnvironment.mockReturnValue(SdkEnvironment.Production); - geolocationApiServiceInit(getInitRequestMock()); - - const ServiceMock = jest.mocked(GeolocationApiService); - expect(ServiceMock).toHaveBeenCalledWith( - expect.objectContaining({ env: Env.PRD }), - ); - }); - - it('passes Env.DEV for staging environment', () => { - mockGetSdkEnvironment.mockReturnValue(SdkEnvironment.Staging); - geolocationApiServiceInit(getInitRequestMock()); - - const ServiceMock = jest.mocked(GeolocationApiService); - expect(ServiceMock).toHaveBeenCalledWith( - expect.objectContaining({ env: Env.DEV }), - ); - }); - - it('passes fetch and messenger to the service', () => { - geolocationApiServiceInit(getInitRequestMock()); - - const ServiceMock = jest.mocked(GeolocationApiService); - expect(ServiceMock).toHaveBeenCalledWith( - expect.objectContaining({ - messenger: expect.any(Object), - fetch: expect.any(Function), - }), - ); - }); -}); diff --git a/app/core/Engine/controllers/geolocation-api-service-init.ts b/app/core/Engine/controllers/geolocation-api-service-init.ts deleted file mode 100644 index d3a1bc2e4cb4..000000000000 --- a/app/core/Engine/controllers/geolocation-api-service-init.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - GeolocationApiService, - Env, - type GeolocationApiServiceMessenger, -} from '@metamask/geolocation-controller'; -import { SdkEnvironment } from '../../../components/UI/Ramp/types/legacyDeposit'; -import { getSdkEnvironment } from '../../../components/UI/Ramp/utils/getSdkEnvironment'; -import type { MessengerClientInitFunction } from '../types'; - -/** - * Initialize the GeolocationApiService. - * - * @param request - The request object. - * @param request.controllerMessenger - The messenger to use for the service. - * @returns The initialized service. - */ -export const geolocationApiServiceInit: MessengerClientInitFunction< - GeolocationApiService, - GeolocationApiServiceMessenger -> = ({ controllerMessenger }) => { - const sdkEnv = getSdkEnvironment(); - const env = sdkEnv === SdkEnvironment.Production ? Env.PRD : Env.DEV; - - const controller = new GeolocationApiService({ - messenger: controllerMessenger, - env, - fetch: fetch.bind(globalThis), - }); - - return { controller }; -}; diff --git a/app/core/Engine/controllers/geolocation-controller/index.test.ts b/app/core/Engine/controllers/geolocation-controller/index.test.ts deleted file mode 100644 index 855f60a2b87c..000000000000 --- a/app/core/Engine/controllers/geolocation-controller/index.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { buildMessengerClientInitRequestMock } from '../../utils/test-utils'; -import { ExtendedMessenger } from '../../../ExtendedMessenger'; -import { getGeolocationControllerMessenger } from '../../messengers/geolocation-controller-messenger'; -import type { MessengerClientInitRequest } from '../../types'; -import { geolocationControllerInit } from './index'; -import { - GeolocationController, - type GeolocationControllerMessenger, -} from '@metamask/geolocation-controller'; -import { MOCK_ANY_NAMESPACE, type MockAnyNamespace } from '@metamask/messenger'; - -jest.mock('@metamask/geolocation-controller', () => { - const MockGeolocationController = jest.fn().mockImplementation(() => ({ - getGeolocation: jest.fn().mockResolvedValue('US'), - })); - // Preserve instanceof checks - MockGeolocationController.prototype = Object.create( - MockGeolocationController.prototype, - ); - return { - ...jest.requireActual('@metamask/geolocation-controller'), - GeolocationController: MockGeolocationController, - }; -}); - -function getInitRequestMock( - overrides?: Partial< - MessengerClientInitRequest - >, -): jest.Mocked> { - const baseMessenger = new ExtendedMessenger({ - namespace: MOCK_ANY_NAMESPACE, - }); - - return { - ...buildMessengerClientInitRequestMock(baseMessenger), - controllerMessenger: getGeolocationControllerMessenger(baseMessenger), - initMessenger: undefined, - ...overrides, - } as jest.Mocked>; -} - -describe('geolocationControllerInit', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('initializes the controller', () => { - const { controller } = geolocationControllerInit(getInitRequestMock()); - expect(controller).toBeDefined(); - expect(GeolocationController).toHaveBeenCalledTimes(1); - }); - - it('passes the messenger to the controller', () => { - geolocationControllerInit(getInitRequestMock()); - - const ControllerMock = jest.mocked(GeolocationController); - expect(ControllerMock).toHaveBeenCalledWith( - expect.objectContaining({ - messenger: expect.any(Object), - }), - ); - }); - - it('triggers eager fetch when location is UNKNOWN', () => { - const { controller } = geolocationControllerInit(getInitRequestMock()); - expect(controller.getGeolocation).toHaveBeenCalled(); - }); - - it('skips eager fetch when persisted state has a known location', () => { - const { controller } = geolocationControllerInit( - getInitRequestMock({ - persistedState: { - GeolocationController: { - location: 'US', - status: 'complete', - lastFetchedAt: Date.now(), - error: null, - }, - }, - }), - ); - expect(controller.getGeolocation).not.toHaveBeenCalled(); - }); - - it('hydrates controller state from persisted state', () => { - const persistedLocation = { - location: 'FR', - status: 'complete' as const, - lastFetchedAt: 1234567890, - error: null, - }; - geolocationControllerInit( - getInitRequestMock({ - persistedState: { GeolocationController: persistedLocation }, - }), - ); - - const ControllerMock = jest.mocked(GeolocationController); - expect(ControllerMock).toHaveBeenCalledWith( - expect.objectContaining({ - state: persistedLocation, - }), - ); - }); -}); diff --git a/app/core/Engine/controllers/geolocation-controller/index.ts b/app/core/Engine/controllers/geolocation-controller/index.ts deleted file mode 100644 index bb46ba02a8c6..000000000000 --- a/app/core/Engine/controllers/geolocation-controller/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { - GeolocationController, - getDefaultGeolocationControllerState, - UNKNOWN_LOCATION, - type GeolocationControllerMessenger, -} from '@metamask/geolocation-controller'; -import type { MessengerClientInitFunction } from '../../types'; - -/** - * Initialize the GeolocationController. - * - * @param request - The request object. - * @param request.controllerMessenger - The messenger to use for the controller. - * @param request.persistedState - The persisted state to hydrate from. - * @returns The initialized controller. - */ -export const geolocationControllerInit: MessengerClientInitFunction< - GeolocationController, - GeolocationControllerMessenger -> = ({ controllerMessenger, persistedState }) => { - const geolocationControllerState = - persistedState.GeolocationController ?? - getDefaultGeolocationControllerState(); - - const controller = new GeolocationController({ - messenger: controllerMessenger, - state: geolocationControllerState, - }); - - // Eagerly fetch geolocation on Engine start so the value is available - // to all consumers (Ramp, Perps, Rewards, Card) before they need it. - // Skip when the persisted/fixture state already has a known location to - // avoid overwriting it (all controller state fields are non-persistent, so - // a known location only exists when hydrated from E2E fixtures or redux). - const hasKnownLocation = - geolocationControllerState.location !== UNKNOWN_LOCATION && - geolocationControllerState.location !== ''; - - if (!hasKnownLocation) { - controller.getGeolocation().catch(() => { - // Best-effort fetch; errors are surfaced via controller state. - }); - } - - return { controller }; -}; diff --git a/app/core/Engine/messengers/geolocation-api-service-messenger.ts b/app/core/Engine/messengers/geolocation-api-service-messenger.ts deleted file mode 100644 index 0fdbb3a4152c..000000000000 --- a/app/core/Engine/messengers/geolocation-api-service-messenger.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { - Messenger, - type MessengerActions, - type MessengerEvents, -} from '@metamask/messenger'; -import type { RootMessenger } from '../types'; -import type { GeolocationApiServiceMessenger } from '@metamask/geolocation-controller'; - -/** - * Get the messenger for the geolocation API service. This is scoped to the - * actions and events that the geolocation API service is allowed to handle. - * - * @param rootMessenger - The root messenger. - * @returns The GeolocationApiServiceMessenger. - */ -export function getGeolocationApiServiceMessenger( - rootMessenger: RootMessenger< - MessengerActions, - MessengerEvents - >, -): GeolocationApiServiceMessenger { - const messenger: GeolocationApiServiceMessenger = new Messenger({ - namespace: 'GeolocationApiService', - parent: rootMessenger, - }); - return messenger; -} diff --git a/app/core/Engine/messengers/geolocation-controller-messenger/index.ts b/app/core/Engine/messengers/geolocation-controller-messenger/index.ts deleted file mode 100644 index 03d6edae22aa..000000000000 --- a/app/core/Engine/messengers/geolocation-controller-messenger/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - Messenger, - type MessengerActions, - type MessengerEvents, -} from '@metamask/messenger'; -import type { GeolocationControllerMessenger } from '@metamask/geolocation-controller'; -import type { RootMessenger } from '../../types'; - -const name = 'GeolocationController' as const; - -/** - * Get the messenger for the GeolocationController. Delegates the - * GeolocationApiService:fetchGeolocationData action so the controller can - * call the API service via the messenger. - * - * @param rootMessenger - The root messenger. - * @returns The GeolocationControllerMessenger. - */ -export function getGeolocationControllerMessenger( - rootMessenger: RootMessenger< - MessengerActions, - MessengerEvents - >, -): GeolocationControllerMessenger { - const messenger: GeolocationControllerMessenger = new Messenger({ - namespace: name, - parent: rootMessenger, - }); - - rootMessenger.delegate({ - messenger, - actions: ['GeolocationApiService:fetchGeolocationData'], - events: [], - }); - - return messenger; -} diff --git a/app/core/Engine/messengers/index.ts b/app/core/Engine/messengers/index.ts index 49789cc8145a..c7c97dfa756e 100644 --- a/app/core/Engine/messengers/index.ts +++ b/app/core/Engine/messengers/index.ts @@ -102,9 +102,7 @@ import { } from './money-account-controller-messenger'; import { getMoneyAccountBalanceServiceMessenger } from './money-account-balance-service-messenger'; import { getMoneyAccountApiDataServiceMessenger } from './money-account-api-data-service-messenger'; -import { getGeolocationApiServiceMessenger } from './geolocation-api-service-messenger'; import { getSentinelApiServiceMessenger } from './sentinel-api-service-messenger'; -import { getGeolocationControllerMessenger } from './geolocation-controller-messenger'; import { getRewardsDataServiceMessenger } from './rewards-data-service-messenger'; import { getRewardsMoneyDataServiceMessenger } from './rewards-money-data-service-messenger'; import { getDelegationControllerMessenger } from './delegation/delegation-controller-messenger'; @@ -176,18 +174,10 @@ export const MESSENGER_FACTORIES = { getMessenger: getEarnControllerMessenger, getInitMessenger: noop, }, - GeolocationApiService: { - getMessenger: getGeolocationApiServiceMessenger, - getInitMessenger: noop, - }, SentinelApiService: { getMessenger: getSentinelApiServiceMessenger, getInitMessenger: noop, }, - GeolocationController: { - getMessenger: getGeolocationControllerMessenger, - getInitMessenger: noop, - }, TransactionPayController: { getMessenger: getTransactionPayControllerMessenger, getInitMessenger: getTransactionPayControllerInitMessenger, diff --git a/app/core/Engine/types.ts b/app/core/Engine/types.ts index 9aec5157b4ab..8623d122162b 100644 --- a/app/core/Engine/types.ts +++ b/app/core/Engine/types.ts @@ -1162,8 +1162,6 @@ export type MessengerClientsToInitialize = | 'AccountTreeController' | 'DeFiPositionsController' | 'DeFiPositionsControllerV2' - | 'GeolocationController' - | 'GeolocationApiService' | 'MultichainNetworkController' | 'NftController' | 'TokensController' diff --git a/app/core/Engine/wallet-init/initialization.test.ts b/app/core/Engine/wallet-init/initialization.test.ts index bb9ff93aa171..cc1cf2b78a06 100644 --- a/app/core/Engine/wallet-init/initialization.test.ts +++ b/app/core/Engine/wallet-init/initialization.test.ts @@ -14,16 +14,21 @@ import { } from './instance-options/analytics-controller'; import { getAnalyticsControllerInitMessenger } from './messengers/analytics-controller-messenger'; import { setupAnalyticsControllerListeners } from './listeners/analytics-controller'; +import { fetchInitialGeolocation } from './listeners/geolocation-controller'; import DomainProxyMap from '../../../lib/DomainProxyMap/DomainProxyMap'; import { unrestrictedMethods } from '../../Permissions/specifications'; import { getLedgerDmkMode, initializeLedgerDmkMode } from '../../Ledger/dmk'; import { FeatureFlagNames } from '../../../constants/featureFlags'; const mockWalletInit = jest.fn().mockResolvedValue([]); +const mockGeolocationController = { name: 'GeolocationController' }; +const mockWalletGetInstance = jest.fn((name: string) => + name === 'GeolocationController' ? mockGeolocationController : undefined, +); jest.mock('@metamask/wallet', () => ({ Wallet: jest.fn().mockImplementation(() => ({ init: mockWalletInit, - getInstance: jest.fn(), + getInstance: mockWalletGetInstance, })), })); jest.mock('./instance-options/analytics-controller', () => ({ @@ -35,6 +40,11 @@ jest.mock('./instance-options/analytics-controller', () => ({ }), ), })); +jest.mock('./instance-options/geolocation-api-service', () => ({ + getGeolocationApiServiceInstanceOptions: jest.fn( + () => 'geolocation-api-service-options', + ), +})); jest.mock('./messengers/analytics-controller-messenger', () => ({ getAnalyticsControllerInitMessenger: jest.fn( () => 'analytics-init-messenger', @@ -43,6 +53,9 @@ jest.mock('./messengers/analytics-controller-messenger', () => ({ jest.mock('./listeners/analytics-controller', () => ({ setupAnalyticsControllerListeners: jest.fn(), })); +jest.mock('./listeners/geolocation-controller', () => ({ + fetchInitialGeolocation: jest.fn(), +})); jest.mock('./instance-options/approval-controller', () => ({ getApprovalControllerInstanceOptions: jest.fn(() => 'approval-options'), })); @@ -123,6 +136,7 @@ describe('initializeWallet', () => { remoteFeatureFlagController: 'rffc-options', connectivityController: 'connectivity-options', gasFeeController: 'gas-fee-options', + geolocationApiService: 'geolocation-api-service-options', seedlessOnboardingController: 'seedless-options', storageService: 'storage-options', subscriptionService: 'subscription-service-options', @@ -177,6 +191,15 @@ describe('initializeWallet', () => { ); }); + it('eagerly fetches geolocation from the wallet-owned GeolocationController', () => { + initializeWallet({ messenger, state, analyticsId }); + + expect(mockWalletGetInstance).toHaveBeenCalledWith('GeolocationController'); + expect(fetchInitialGeolocation).toHaveBeenCalledWith( + mockGeolocationController, + ); + }); + it('builds the TransactionController options and listeners with the init messenger', () => { initializeWallet({ messenger, state, analyticsId }); diff --git a/app/core/Engine/wallet-init/initialization.ts b/app/core/Engine/wallet-init/initialization.ts index 0121f712abec..07684a848c36 100644 --- a/app/core/Engine/wallet-init/initialization.ts +++ b/app/core/Engine/wallet-init/initialization.ts @@ -28,6 +28,8 @@ import { } from './instance-options/analytics-controller'; import { getAnalyticsControllerInitMessenger } from './messengers/analytics-controller-messenger'; import { setupAnalyticsControllerListeners } from './listeners/analytics-controller'; +import { getGeolocationApiServiceInstanceOptions } from './instance-options/geolocation-api-service'; +import { fetchInitialGeolocation } from './listeners/geolocation-controller'; /** * Construct the `@metamask/wallet` `Wallet` for mobile. Each controller's @@ -90,6 +92,7 @@ export function initializeWallet({ approvalController: getApprovalControllerInstanceOptions(), connectivityController: getConnectivityControllerInstanceOptions(), gasFeeController: getGasFeeControllerInstanceOptions(), + geolocationApiService: getGeolocationApiServiceInstanceOptions(), keyringController: getKeyringControllerInstanceOptions(messenger, useDmk), networkController: getNetworkControllerInstanceOptions(), permissionController: getPermissionControllerInstanceOptions( @@ -122,5 +125,7 @@ export function initializeWallet({ wallet.init().catch((error: unknown) => console.error(error)); + fetchInitialGeolocation(wallet.getInstance('GeolocationController')); + return wallet; } diff --git a/app/core/Engine/wallet-init/instance-options/geolocation-api-service.test.ts b/app/core/Engine/wallet-init/instance-options/geolocation-api-service.test.ts new file mode 100644 index 000000000000..04bec31f4af4 --- /dev/null +++ b/app/core/Engine/wallet-init/instance-options/geolocation-api-service.test.ts @@ -0,0 +1,40 @@ +import { Env } from '@metamask/geolocation-controller'; +import { getGeolocationApiServiceInstanceOptions } from './geolocation-api-service'; +import { getSdkEnvironment } from '../../../../components/UI/Ramp/utils/getSdkEnvironment'; +import { SdkEnvironment } from '../../../../components/UI/Ramp/types/legacyDeposit'; + +jest.mock('../../../../components/UI/Ramp/utils/getSdkEnvironment', () => ({ + getSdkEnvironment: jest.fn(), +})); + +const mockGetSdkEnvironment = jest.mocked(getSdkEnvironment); + +describe('getGeolocationApiServiceInstanceOptions', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('uses the production geolocation API for the production SDK environment', () => { + mockGetSdkEnvironment.mockReturnValue(SdkEnvironment.Production); + + const options = getGeolocationApiServiceInstanceOptions(); + + expect(options.env).toBe(Env.PRD); + }); + + it('uses the dev geolocation API for the staging SDK environment', () => { + mockGetSdkEnvironment.mockReturnValue(SdkEnvironment.Staging); + + const options = getGeolocationApiServiceInstanceOptions(); + + expect(options.env).toBe(Env.DEV); + }); + + it('passes a fetch function', () => { + mockGetSdkEnvironment.mockReturnValue(SdkEnvironment.Production); + + const options = getGeolocationApiServiceInstanceOptions(); + + expect(options.fetch).toStrictEqual(expect.any(Function)); + }); +}); diff --git a/app/core/Engine/wallet-init/instance-options/geolocation-api-service.ts b/app/core/Engine/wallet-init/instance-options/geolocation-api-service.ts new file mode 100644 index 000000000000..739c924061d6 --- /dev/null +++ b/app/core/Engine/wallet-init/instance-options/geolocation-api-service.ts @@ -0,0 +1,24 @@ +import { Env } from '@metamask/geolocation-controller'; +import type { WalletOptions } from '@metamask/wallet'; +import { SdkEnvironment } from '../../../../components/UI/Ramp/types/legacyDeposit'; +import { getSdkEnvironment } from '../../../../components/UI/Ramp/utils/getSdkEnvironment'; + +type GeolocationApiServiceInstanceOptions = NonNullable< + WalletOptions['instanceOptions']['geolocationApiService'] +>; + +/** + * Mobile follows the Ramp SDK environment so the geolocation API points at + * the same backend cluster as Ramp. + * + * @returns The mobile GeolocationApiService instance options. + */ +export function getGeolocationApiServiceInstanceOptions(): GeolocationApiServiceInstanceOptions { + const env = + getSdkEnvironment() === SdkEnvironment.Production ? Env.PRD : Env.DEV; + + return { + env, + fetch: fetch.bind(globalThis), + }; +} diff --git a/app/core/Engine/wallet-init/listeners/geolocation-controller.test.ts b/app/core/Engine/wallet-init/listeners/geolocation-controller.test.ts new file mode 100644 index 000000000000..12e2af6eea5b --- /dev/null +++ b/app/core/Engine/wallet-init/listeners/geolocation-controller.test.ts @@ -0,0 +1,46 @@ +import { + UNKNOWN_LOCATION, + type GeolocationController, +} from '@metamask/geolocation-controller'; +import { fetchInitialGeolocation } from './geolocation-controller'; + +function buildGeolocationController(location: string) { + return { + state: { location }, + getGeolocation: jest.fn().mockResolvedValue('US'), + } as unknown as jest.Mocked; +} + +describe('fetchInitialGeolocation', () => { + it('fetches geolocation when the location is unknown', () => { + const controller = buildGeolocationController(UNKNOWN_LOCATION); + + fetchInitialGeolocation(controller); + + expect(controller.getGeolocation).toHaveBeenCalledTimes(1); + }); + + it('fetches geolocation when the location is empty', () => { + const controller = buildGeolocationController(''); + + fetchInitialGeolocation(controller); + + expect(controller.getGeolocation).toHaveBeenCalledTimes(1); + }); + + it('skips the fetch when the hydrated state already has a known location', () => { + const controller = buildGeolocationController('US'); + + fetchInitialGeolocation(controller); + + expect(controller.getGeolocation).not.toHaveBeenCalled(); + }); + + it('swallows fetch errors', async () => { + const controller = buildGeolocationController(UNKNOWN_LOCATION); + controller.getGeolocation.mockRejectedValue(new Error('network')); + + expect(() => fetchInitialGeolocation(controller)).not.toThrow(); + await Promise.resolve(); + }); +}); diff --git a/app/core/Engine/wallet-init/listeners/geolocation-controller.ts b/app/core/Engine/wallet-init/listeners/geolocation-controller.ts new file mode 100644 index 000000000000..ccc39e1dc505 --- /dev/null +++ b/app/core/Engine/wallet-init/listeners/geolocation-controller.ts @@ -0,0 +1,29 @@ +import { + UNKNOWN_LOCATION, + type GeolocationController, +} from '@metamask/geolocation-controller'; + +/** + * Eagerly fetch geolocation on Engine start so the value is available to all + * consumers (Ramp, Perps, Rewards, Card) before they need it. + * + * Skipped when the hydrated state already has a known location to avoid + * overwriting it (all controller state fields are non-persistent, so a known + * location only exists when hydrated from E2E fixtures or redux). + * + * @param geolocationController - The wallet-owned GeolocationController. + */ +export function fetchInitialGeolocation( + geolocationController: GeolocationController, +): void { + const { location } = geolocationController.state; + const hasKnownLocation = location !== UNKNOWN_LOCATION && location !== ''; + + if (hasKnownLocation) { + return; + } + + geolocationController.getGeolocation().catch(() => { + // Best-effort fetch; errors are surfaced via controller state. + }); +} diff --git a/package.json b/package.json index 56272e4e3f7e..12034c18927c 100644 --- a/package.json +++ b/package.json @@ -486,7 +486,7 @@ "@metamask/transaction-pay-controller": "^30.4.3", "@metamask/tron-wallet-snap": "^4.4.0", "@metamask/utils": "^12.0.0", - "@metamask/wallet": "^19.1.0", + "@metamask/wallet": "^20.0.0", "@ngraveio/bc-ur": "^1.1.6", "@nktkas/hyperliquid": "^0.33.3", "@noble/curves": "1.9.7", diff --git a/tests/integration/harnesses/predict-next.ts b/tests/integration/harnesses/predict-next.ts index c5af0ed8e009..0f8883d87fea 100644 --- a/tests/integration/harnesses/predict-next.ts +++ b/tests/integration/harnesses/predict-next.ts @@ -2,8 +2,8 @@ import { deriveStateFromMetadata } from '@metamask/base-controller'; import { ConstantBackoff } from '@metamask/controller-utils'; import { GeolocationApiService, + GeolocationController, type GeolocationApiServiceMessenger, - type GeolocationController, type GeolocationControllerMessenger, } from '@metamask/geolocation-controller'; import { @@ -63,9 +63,7 @@ import { type PredictVenueControllerMessenger, type PredictVenueControllerState, } from '../../../app/components/UI/PredictNext/implementation/PredictVenueController'; -import { geolocationControllerInit } from '../../../app/core/Engine/controllers/geolocation-controller'; -import { getGeolocationApiServiceMessenger } from '../../../app/core/Engine/messengers/geolocation-api-service-messenger'; -import { getGeolocationControllerMessenger } from '../../../app/core/Engine/messengers/geolocation-controller-messenger'; +import { fetchInitialGeolocation } from '../../../app/core/Engine/wallet-init/listeners/geolocation-controller'; import { getPredictDeviceAuthServiceMessenger } from '../../../app/core/Engine/messengers/predict-device-auth-service-messenger'; import { getPredictVenueControllerMessenger } from '../../../app/core/Engine/messengers/predict-venue-controller-messenger'; @@ -541,23 +539,28 @@ export const buildPredictVenueIntegrationHarness = ({ settle = resolve; }), ) as unknown as jest.MockedFunction; + // Mirrors the GeolocationApiService and GeolocationController messengers + // that @metamask/wallet builds. + const geolocationApiServiceMessenger: GeolocationApiServiceMessenger = + new Messenger({ namespace: 'GeolocationApiService', parent: messenger }); // Registers the fetch action the controller calls; nothing else holds it. // eslint-disable-next-line no-new new GeolocationApiService({ - messenger: - getGeolocationApiServiceMessenger( - rootFor(), - ), + messenger: geolocationApiServiceMessenger, fetch: geolocationFetchMock, policyOptions: { maxRetries: 0 }, }); - const { controller: geolocationController } = geolocationControllerInit({ - controllerMessenger: - getGeolocationControllerMessenger( - rootFor(), - ), - persistedState: {}, - } as unknown as Parameters[0]); + const geolocationControllerMessenger: GeolocationControllerMessenger = + new Messenger({ namespace: 'GeolocationController', parent: messenger }); + messenger.delegate({ + messenger: geolocationControllerMessenger, + actions: ['GeolocationApiService:fetchGeolocationData'], + }); + const geolocationController = new GeolocationController({ + messenger: geolocationControllerMessenger, + }); + // Mirrors the eager Engine-start fetch in initializeWallet. + fetchInitialGeolocation(geolocationController); // Mirrors predictVenueControllerInit, minus its Redux subscription. const venueController = new PredictVenueController({ diff --git a/yarn.lock b/yarn.lock index ce60fdc7a1f9..d672e4980c18 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12626,13 +12626,13 @@ __metadata: languageName: node linkType: hard -"@metamask/wallet@npm:^19.1.0": - version: 19.1.0 - resolution: "@metamask/wallet@npm:19.1.0" +"@metamask/wallet@npm:^20.0.0": + version: 20.0.0 + resolution: "@metamask/wallet@npm:20.0.0" dependencies: "@metamask/accounts-controller": "npm:^40.1.0" "@metamask/address-book-controller": "npm:^8.0.0" - "@metamask/analytics-controller": "npm:^4.0.0" + "@metamask/analytics-controller": "npm:^4.1.0" "@metamask/approval-controller": "npm:^10.0.0" "@metamask/base-controller": "npm:^10.1.0" "@metamask/browser-passworder": "npm:^6.0.0" @@ -12642,6 +12642,7 @@ __metadata: "@metamask/connectivity-controller": "npm:^1.0.0" "@metamask/controller-utils": "npm:^13.0.0" "@metamask/gas-fee-controller": "npm:^27.0.0" + "@metamask/geolocation-controller": "npm:^2.0.0" "@metamask/keyring-controller": "npm:^28.2.0" "@metamask/logging-controller": "npm:^10.0.0" "@metamask/messenger": "npm:^3.0.0" @@ -12657,7 +12658,7 @@ __metadata: "@metamask/subscription-controller": "npm:^15.0.0" "@metamask/transaction-controller": "npm:^72.2.1" "@metamask/utils": "npm:^12.0.0" - checksum: 10/5b5647b3992c563eccac7249f93fb368174e04725dddd8267f28925dc19aec1cf898dd35049f09ccc201a852ae51be2183afef9bac843281614ee310f3273ad1 + checksum: 10/1e45709cfa32901d0d4f9ac950f4cde8733cd0d25b9fbca2e89e72113916adcd314e5768402fa45776efde7dea57106f2a2815696e398d6411916e44a4cae9bd languageName: node linkType: hard @@ -38411,7 +38412,7 @@ __metadata: "@metamask/transaction-pay-controller": "npm:^30.4.3" "@metamask/tron-wallet-snap": "npm:^4.4.0" "@metamask/utils": "npm:^12.0.0" - "@metamask/wallet": "npm:^19.1.0" + "@metamask/wallet": "npm:^20.0.0" "@ngraveio/bc-ur": "npm:^1.1.6" "@nktkas/hyperliquid": "npm:^0.33.3" "@noble/curves": "npm:1.9.7"