@metamask-previews/subscription-controller 12.0.1-preview-2bc848240 → 12.0.1-preview-136f5f1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,8 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Added
11
+
12
+ - Add optional `isEligibleForRefund` on `StartSubscriptionRequest` and `StartCryptoSubscriptionRequest` ([#10674](https://github.com/MetaMask/core/pull/10674))
13
+ - When the caller provides it, `SubscriptionController` sends that value and skips the geolocation check.
14
+ - When omitted, the controller sets it from geolocation (EU 27 + EEA), or `false` if the lookup fails.
15
+
10
16
  ### Changed
11
17
 
18
+ - **BREAKING:** `SubscriptionControllerMessenger` now requires `GeolocationController:getGeolocationData` so `startSubscriptionWithCard` and `startSubscriptionWithCrypto` can resolve refund eligibility ([#10674](https://github.com/MetaMask/core/pull/10674))
19
+ - Clients that construct this messenger must delegate `GeolocationController:getGeolocationData` before calling those actions.
20
+ - Add `@metamask/geolocation-controller` `^2.0.0` as a dependency ([#10674](https://github.com/MetaMask/core/pull/10674))
12
21
  - **BREAKING:** `SubscriptionDelegationService:startSubscriptionWithDelegation` no longer requests an approval. Callers must obtain consent and initiate funding (for example, a `membershipSubscription` transaction) before calling. ([#10666](https://github.com/MetaMask/core/pull/10666))
13
22
  - `skipApproval` is removed from `StartSubscriptionWithDelegationRequest`.
14
23
 
@@ -78,6 +78,9 @@ export type SubscriptionControllerUnCancelSubscriptionAction = {
78
78
  * `isTrialRequested` on the request is ignored and overwritten from pricing
79
79
  * (`trialPeriodDays > 0`) and `trialedProducts`.
80
80
  *
81
+ * `isEligibleForRefund` is sent as provided. When omitted, it is resolved
82
+ * from geolocation (EU/EEA), or `false` if the lookup fails.
83
+ *
81
84
  * @param request - The start subscription request.
82
85
  * @returns The checkout session response.
83
86
  */
@@ -94,6 +97,9 @@ export type SubscriptionControllerStartSubscriptionWithCardAction = {
94
97
  * `isTrialRequested` on the request is ignored and overwritten from pricing
95
98
  * (`trialPeriodDays > 0`) and `trialedProducts`.
96
99
  *
100
+ * `isEligibleForRefund` is sent as provided. When omitted, it is resolved
101
+ * from geolocation (EU/EEA), or `false` if the lookup fails.
102
+ *
97
103
  * @param request - The start crypto subscription request.
98
104
  * @returns The start crypto subscription response.
99
105
  * @throws If `products` is empty.
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController-method-action-types.d.ts","sourceRoot":"","sources":["../src/SubscriptionController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAE1E;;;;GAIG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,sBAAsB,CAAC,YAAY,CAAC,CAAC;CAC/C,CAAC;AAEF,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,sBAAsB,CAAC,kBAAkB,CAAC,CAAC;CACrD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,uCAAuC,GAAG;IACpD,IAAI,EAAE,oCAAoC,CAAC;IAC3C,OAAO,EAAE,sBAAsB,CAAC,aAAa,CAAC,CAAC;CAChD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,oDAAoD,GAAG;IACjE,IAAI,EAAE,iDAAiD,CAAC;IACxD,OAAO,EAAE,sBAAsB,CAAC,0BAA0B,CAAC,CAAC;CAC7D,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;IACtD,OAAO,EAAE,sBAAsB,CAAC,wBAAwB,CAAC,CAAC;CAC3D,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,yDAAyD,GAAG;IACtE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,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,sBAAsB,CAAC,YAAY,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qDAAqD,GAAG;IAClE,IAAI,EAAE,kDAAkD,CAAC;IACzD,OAAO,EAAE,sBAAsB,CAAC,2BAA2B,CAAC,CAAC;CAC9D,CAAC;AAEF,MAAM,MAAM,0CAA0C,GAAG;IACvD,IAAI,EAAE,uCAAuC,CAAC;IAC9C,OAAO,EAAE,sBAAsB,CAAC,gBAAgB,CAAC,CAAC;CACnD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mCAAmC,GAC3C,sCAAsC,GACtC,4CAA4C,GAC5C,uCAAuC,GACvC,oDAAoD,GACpD,kDAAkD,GAClD,yDAAyD,GACzD,8CAA8C,GAC9C,gDAAgD,GAChD,qDAAqD,GACrD,uDAAuD,GACvD,4DAA4D,GAC5D,6DAA6D,GAC7D,+CAA+C,GAC/C,+CAA+C,GAC/C,0DAA0D,GAC1D,0DAA0D,GAC1D,oDAAoD,GACpD,2CAA2C,GAC3C,8CAA8C,GAC9C,uCAAuC,GACvC,iDAAiD,GACjD,wDAAwD,GACxD,sCAAsC,GACtC,qDAAqD,GACrD,0CAA0C,CAAC"}
1
+ {"version":3,"file":"SubscriptionController-method-action-types.d.ts","sourceRoot":"","sources":["../src/SubscriptionController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAE1E;;;;GAIG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,sBAAsB,CAAC,YAAY,CAAC,CAAC;CAC/C,CAAC;AAEF,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,sBAAsB,CAAC,k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D,GACpD,2CAA2C,GAC3C,8CAA8C,GAC9C,uCAAuC,GACvC,iDAAiD,GACjD,wDAAwD,GACxD,sCAAsC,GACtC,qDAAqD,GACrD,0CAA0C,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController-method-action-types.js","sourceRoot":"","sources":["../src/SubscriptionController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionController } from './SubscriptionController.js';\n\n/**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\nexport type SubscriptionControllerGetPricingAction = {\n type: `SubscriptionController:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\n\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `SubscriptionController:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\n\n/**\n * Gets and stores the user's subscription benefits.\n *\n * @returns The benefits response.\n * @throws If the user is not an active Money Account Plus subscriber or is\n * not eligible for benefits.\n */\nexport type SubscriptionControllerGetBenefitsAction = {\n type: `SubscriptionController:getBenefits`;\n handler: SubscriptionController['getBenefits'];\n};\n\n/**\n * Get the subscription by product.\n *\n * @param productType - The product type.\n * @returns The subscription.\n */\nexport type SubscriptionControllerGetSubscriptionByProductAction = {\n type: `SubscriptionController:getSubscriptionByProduct`;\n handler: SubscriptionController['getSubscriptionByProduct'];\n};\n\n/**\n * Whether the user is eligible to start a trial for the given product.\n *\n * Shield is eligible when the user has not trialed Shield before.\n * Money Account Plus is eligible when the user has not trialed it before\n * and is authenticated with social login. Only an unlocked wallet can\n * subscribe, so `SeedlessOnboardingController:getIsUserAuthenticated` is a\n * sufficient social-login check.\n *\n * @param productType - The product to check.\n * @returns Whether the user is eligible for a trial.\n */\nexport type SubscriptionControllerIsUserEligibleForTrialAction = {\n type: `SubscriptionController:isUserEligibleForTrial`;\n handler: SubscriptionController['isUserEligibleForTrial'];\n};\n\n/**\n * Get the subscriptions eligibilities.\n *\n * @param request - Optional request object containing user balance to check cohort eligibility.\n * @returns The subscriptions eligibilities.\n */\nexport type SubscriptionControllerGetSubscriptionsEligibilitiesAction = {\n type: `SubscriptionController:getSubscriptionsEligibilities`;\n handler: SubscriptionController['getSubscriptionsEligibilities'];\n};\n\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `SubscriptionController:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\n\nexport type SubscriptionControllerUnCancelSubscriptionAction = {\n type: `SubscriptionController:unCancelSubscription`;\n handler: SubscriptionController['unCancelSubscription'];\n};\n\n/**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\nexport type SubscriptionControllerStartSubscriptionWithCardAction = {\n type: `SubscriptionController:startSubscriptionWithCard`;\n handler: SubscriptionController['startSubscriptionWithCard'];\n};\n\n/**\n * Starts a crypto-paid subscription for the requested products\n * (e.g. Shield or Money Account Plus). Unlike card checkout, this\n * creates the subscription immediately, so local state is refreshed\n * afterwards.\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * @param request - The start crypto subscription request.\n * @returns The start crypto subscription response.\n * @throws If `products` is empty.\n */\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `SubscriptionController:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\n\n/**\n * Submits a Shield ERC-20 crypto approval transaction to start or update a\n * crypto subscription.\n *\n * This handler is Shield / `TransactionType.shieldSubscriptionApprove` only.\n * Delegation-based products (e.g. Money Account) must call\n * `startSubscriptionWithCrypto` instead.\n *\n * @param request - The crypto approval request.\n * @param request.productType - The subscription product. Typed as\n * `typeof PRODUCT_TYPES.SHIELD` only at the moment (future might support more\n * product).\n * @param request.txMeta - The transaction metadata. Must have type\n * `TransactionType.shieldSubscriptionApprove`.\n * @param request.isSponsored - Whether the transaction is sponsored.\n * @param request.rewardAccountId - The account ID of the reward subscription\n * to link.\n * @throws If `productType` is not Shield or `txMeta.type` is not\n * `shieldSubscriptionApprove`.\n * @returns void\n */\nexport type SubscriptionControllerSubmitSubscriptionCryptoApprovalAction = {\n type: `SubscriptionController:submitSubscriptionCryptoApproval`;\n handler: SubscriptionController['submitSubscriptionCryptoApproval'];\n};\n\n/**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `SubscriptionController:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\n\nexport type SubscriptionControllerUpdatePaymentMethodAction = {\n type: `SubscriptionController:updatePaymentMethod`;\n handler: SubscriptionController['updatePaymentMethod'];\n};\n\n/**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\nexport type SubscriptionControllerGetBillingPortalUrlAction = {\n type: `SubscriptionController:getBillingPortalUrl`;\n handler: SubscriptionController['getBillingPortalUrl'];\n};\n\n/**\n * Cache the last selected payment method for a specific product.\n *\n * @param request - The request object.\n * @param request.product - The product to cache the payment method for.\n * @param request.paymentMethod - The payment method to cache.\n * @param request.paymentMethod.type - The type of the payment method.\n * @param request.paymentMethod.paymentTokenAddress - The payment token address.\n * @param request.paymentMethod.plan - The plan of the payment method.\n */\nexport type SubscriptionControllerCacheLastSelectedPaymentMethodAction = {\n type: `SubscriptionController:cacheLastSelectedPaymentMethod`;\n handler: SubscriptionController['cacheLastSelectedPaymentMethod'];\n};\n\n/**\n * Clear the last selected payment method for a specific product.\n *\n * @param product - The product to clear the payment method for.\n */\nexport type SubscriptionControllerClearLastSelectedPaymentMethodAction = {\n type: `SubscriptionController:clearLastSelectedPaymentMethod`;\n handler: SubscriptionController['clearLastSelectedPaymentMethod'];\n};\n\n/**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example {\n * address: '0x1234567890123456789012345678901234567890',\n * products: [ProductType.Shield],\n * recurringInterval: RecurringInterval.Month,\n * billingCycles: 1,\n * }\n * @returns resolves to true if the sponsorship is supported and intents were submitted successfully, false if the chain does not support sponsorship or the user has already trialed\n * @throws If the crypto payment method or chain is missing from pricing\n */\nexport type SubscriptionControllerSubmitSponsorshipIntentsAction = {\n type: `SubscriptionController:submitSponsorshipIntents`;\n handler: SubscriptionController['submitSponsorshipIntents'];\n};\n\n/**\n * Submit a user event from the UI. (e.g. shield modal viewed)\n *\n * @param request - Request object containing the event to submit.\n * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }\n */\nexport type SubscriptionControllerSubmitUserEventAction = {\n type: `SubscriptionController:submitUserEvent`;\n handler: SubscriptionController['submitUserEvent'];\n};\n\n/**\n * Assign user to a cohort.\n *\n * @param request - Request object containing the cohort to assign the user to.\n * @example { cohort: 'post_tx' }\n */\nexport type SubscriptionControllerAssignUserToCohortAction = {\n type: `SubscriptionController:assignUserToCohort`;\n handler: SubscriptionController['assignUserToCohort'];\n};\n\n/**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward subscription ID.\n * @param request.subscriptionId - The ID of the subscription to link rewards to.\n * @param request.rewardAccountId - The account ID of the reward subscription to link to the subscription.\n * @example { subscriptionId: '1234567890', rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns Resolves when the rewards are linked successfully.\n */\nexport type SubscriptionControllerLinkRewardsAction = {\n type: `SubscriptionController:linkRewards`;\n handler: SubscriptionController['linkRewards'];\n};\n\n/**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\nexport type SubscriptionControllerGetTokenApproveAmountAction = {\n type: `SubscriptionController:getTokenApproveAmount`;\n handler: SubscriptionController['getTokenApproveAmount'];\n};\n\n/**\n * Calculate token minimum balance amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token balance amount\n */\nexport type SubscriptionControllerGetTokenMinimumBalanceAmountAction = {\n type: `SubscriptionController:getTokenMinimumBalanceAmount`;\n handler: SubscriptionController['getTokenMinimumBalanceAmount'];\n};\n\n/**\n * Clears the subscription state and resets to default values.\n */\nexport type SubscriptionControllerClearStateAction = {\n type: `SubscriptionController:clearState`;\n handler: SubscriptionController['clearState'];\n};\n\n/**\n * Triggers an access token refresh.\n */\nexport type SubscriptionControllerTriggerAccessTokenRefreshAction = {\n type: `SubscriptionController:triggerAccessTokenRefresh`;\n handler: SubscriptionController['triggerAccessTokenRefresh'];\n};\n\nexport type SubscriptionControllerStopAllPollingAction = {\n type: `SubscriptionController:stopAllPolling`;\n handler: SubscriptionController['stopAllPolling'];\n};\n\n/**\n * Union of all SubscriptionController action types.\n */\nexport type SubscriptionControllerMethodActions =\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerGetBenefitsAction\n | SubscriptionControllerGetSubscriptionByProductAction\n | SubscriptionControllerIsUserEligibleForTrialAction\n | SubscriptionControllerGetSubscriptionsEligibilitiesAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerUnCancelSubscriptionAction\n | SubscriptionControllerStartSubscriptionWithCardAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction\n | SubscriptionControllerSubmitSubscriptionCryptoApprovalAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerUpdatePaymentMethodAction\n | SubscriptionControllerGetBillingPortalUrlAction\n | SubscriptionControllerCacheLastSelectedPaymentMethodAction\n | SubscriptionControllerClearLastSelectedPaymentMethodAction\n | SubscriptionControllerSubmitSponsorshipIntentsAction\n | SubscriptionControllerSubmitUserEventAction\n | SubscriptionControllerAssignUserToCohortAction\n | SubscriptionControllerLinkRewardsAction\n | SubscriptionControllerGetTokenApproveAmountAction\n | SubscriptionControllerGetTokenMinimumBalanceAmountAction\n | SubscriptionControllerClearStateAction\n | SubscriptionControllerTriggerAccessTokenRefreshAction\n | SubscriptionControllerStopAllPollingAction;\n"]}
1
+ {"version":3,"file":"SubscriptionController-method-action-types.js","sourceRoot":"","sources":["../src/SubscriptionController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionController } from './SubscriptionController.js';\n\n/**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\nexport type SubscriptionControllerGetPricingAction = {\n type: `SubscriptionController:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\n\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `SubscriptionController:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\n\n/**\n * Gets and stores the user's subscription benefits.\n *\n * @returns The benefits response.\n * @throws If the user is not an active Money Account Plus subscriber or is\n * not eligible for benefits.\n */\nexport type SubscriptionControllerGetBenefitsAction = {\n type: `SubscriptionController:getBenefits`;\n handler: SubscriptionController['getBenefits'];\n};\n\n/**\n * Get the subscription by product.\n *\n * @param productType - The product type.\n * @returns The subscription.\n */\nexport type SubscriptionControllerGetSubscriptionByProductAction = {\n type: `SubscriptionController:getSubscriptionByProduct`;\n handler: SubscriptionController['getSubscriptionByProduct'];\n};\n\n/**\n * Whether the user is eligible to start a trial for the given product.\n *\n * Shield is eligible when the user has not trialed Shield before.\n * Money Account Plus is eligible when the user has not trialed it before\n * and is authenticated with social login. Only an unlocked wallet can\n * subscribe, so `SeedlessOnboardingController:getIsUserAuthenticated` is a\n * sufficient social-login check.\n *\n * @param productType - The product to check.\n * @returns Whether the user is eligible for a trial.\n */\nexport type SubscriptionControllerIsUserEligibleForTrialAction = {\n type: `SubscriptionController:isUserEligibleForTrial`;\n handler: SubscriptionController['isUserEligibleForTrial'];\n};\n\n/**\n * Get the subscriptions eligibilities.\n *\n * @param request - Optional request object containing user balance to check cohort eligibility.\n * @returns The subscriptions eligibilities.\n */\nexport type SubscriptionControllerGetSubscriptionsEligibilitiesAction = {\n type: `SubscriptionController:getSubscriptionsEligibilities`;\n handler: SubscriptionController['getSubscriptionsEligibilities'];\n};\n\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `SubscriptionController:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\n\nexport type SubscriptionControllerUnCancelSubscriptionAction = {\n type: `SubscriptionController:unCancelSubscription`;\n handler: SubscriptionController['unCancelSubscription'];\n};\n\n/**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * `isEligibleForRefund` is sent as provided. When omitted, it is resolved\n * from geolocation (EU/EEA), or `false` if the lookup fails.\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\nexport type SubscriptionControllerStartSubscriptionWithCardAction = {\n type: `SubscriptionController:startSubscriptionWithCard`;\n handler: SubscriptionController['startSubscriptionWithCard'];\n};\n\n/**\n * Starts a crypto-paid subscription for the requested products\n * (e.g. Shield or Money Account Plus). Unlike card checkout, this\n * creates the subscription immediately, so local state is refreshed\n * afterwards.\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * `isEligibleForRefund` is sent as provided. When omitted, it is resolved\n * from geolocation (EU/EEA), or `false` if the lookup fails.\n *\n * @param request - The start crypto subscription request.\n * @returns The start crypto subscription response.\n * @throws If `products` is empty.\n */\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `SubscriptionController:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\n\n/**\n * Submits a Shield ERC-20 crypto approval transaction to start or update a\n * crypto subscription.\n *\n * This handler is Shield / `TransactionType.shieldSubscriptionApprove` only.\n * Delegation-based products (e.g. Money Account) must call\n * `startSubscriptionWithCrypto` instead.\n *\n * @param request - The crypto approval request.\n * @param request.productType - The subscription product. Typed as\n * `typeof PRODUCT_TYPES.SHIELD` only at the moment (future might support more\n * product).\n * @param request.txMeta - The transaction metadata. Must have type\n * `TransactionType.shieldSubscriptionApprove`.\n * @param request.isSponsored - Whether the transaction is sponsored.\n * @param request.rewardAccountId - The account ID of the reward subscription\n * to link.\n * @throws If `productType` is not Shield or `txMeta.type` is not\n * `shieldSubscriptionApprove`.\n * @returns void\n */\nexport type SubscriptionControllerSubmitSubscriptionCryptoApprovalAction = {\n type: `SubscriptionController:submitSubscriptionCryptoApproval`;\n handler: SubscriptionController['submitSubscriptionCryptoApproval'];\n};\n\n/**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `SubscriptionController:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\n\nexport type SubscriptionControllerUpdatePaymentMethodAction = {\n type: `SubscriptionController:updatePaymentMethod`;\n handler: SubscriptionController['updatePaymentMethod'];\n};\n\n/**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\nexport type SubscriptionControllerGetBillingPortalUrlAction = {\n type: `SubscriptionController:getBillingPortalUrl`;\n handler: SubscriptionController['getBillingPortalUrl'];\n};\n\n/**\n * Cache the last selected payment method for a specific product.\n *\n * @param request - The request object.\n * @param request.product - The product to cache the payment method for.\n * @param request.paymentMethod - The payment method to cache.\n * @param request.paymentMethod.type - The type of the payment method.\n * @param request.paymentMethod.paymentTokenAddress - The payment token address.\n * @param request.paymentMethod.plan - The plan of the payment method.\n */\nexport type SubscriptionControllerCacheLastSelectedPaymentMethodAction = {\n type: `SubscriptionController:cacheLastSelectedPaymentMethod`;\n handler: SubscriptionController['cacheLastSelectedPaymentMethod'];\n};\n\n/**\n * Clear the last selected payment method for a specific product.\n *\n * @param product - The product to clear the payment method for.\n */\nexport type SubscriptionControllerClearLastSelectedPaymentMethodAction = {\n type: `SubscriptionController:clearLastSelectedPaymentMethod`;\n handler: SubscriptionController['clearLastSelectedPaymentMethod'];\n};\n\n/**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example {\n * address: '0x1234567890123456789012345678901234567890',\n * products: [ProductType.Shield],\n * recurringInterval: RecurringInterval.Month,\n * billingCycles: 1,\n * }\n * @returns resolves to true if the sponsorship is supported and intents were submitted successfully, false if the chain does not support sponsorship or the user has already trialed\n * @throws If the crypto payment method or chain is missing from pricing\n */\nexport type SubscriptionControllerSubmitSponsorshipIntentsAction = {\n type: `SubscriptionController:submitSponsorshipIntents`;\n handler: SubscriptionController['submitSponsorshipIntents'];\n};\n\n/**\n * Submit a user event from the UI. (e.g. shield modal viewed)\n *\n * @param request - Request object containing the event to submit.\n * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }\n */\nexport type SubscriptionControllerSubmitUserEventAction = {\n type: `SubscriptionController:submitUserEvent`;\n handler: SubscriptionController['submitUserEvent'];\n};\n\n/**\n * Assign user to a cohort.\n *\n * @param request - Request object containing the cohort to assign the user to.\n * @example { cohort: 'post_tx' }\n */\nexport type SubscriptionControllerAssignUserToCohortAction = {\n type: `SubscriptionController:assignUserToCohort`;\n handler: SubscriptionController['assignUserToCohort'];\n};\n\n/**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward subscription ID.\n * @param request.subscriptionId - The ID of the subscription to link rewards to.\n * @param request.rewardAccountId - The account ID of the reward subscription to link to the subscription.\n * @example { subscriptionId: '1234567890', rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns Resolves when the rewards are linked successfully.\n */\nexport type SubscriptionControllerLinkRewardsAction = {\n type: `SubscriptionController:linkRewards`;\n handler: SubscriptionController['linkRewards'];\n};\n\n/**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\nexport type SubscriptionControllerGetTokenApproveAmountAction = {\n type: `SubscriptionController:getTokenApproveAmount`;\n handler: SubscriptionController['getTokenApproveAmount'];\n};\n\n/**\n * Calculate token minimum balance amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token balance amount\n */\nexport type SubscriptionControllerGetTokenMinimumBalanceAmountAction = {\n type: `SubscriptionController:getTokenMinimumBalanceAmount`;\n handler: SubscriptionController['getTokenMinimumBalanceAmount'];\n};\n\n/**\n * Clears the subscription state and resets to default values.\n */\nexport type SubscriptionControllerClearStateAction = {\n type: `SubscriptionController:clearState`;\n handler: SubscriptionController['clearState'];\n};\n\n/**\n * Triggers an access token refresh.\n */\nexport type SubscriptionControllerTriggerAccessTokenRefreshAction = {\n type: `SubscriptionController:triggerAccessTokenRefresh`;\n handler: SubscriptionController['triggerAccessTokenRefresh'];\n};\n\nexport type SubscriptionControllerStopAllPollingAction = {\n type: `SubscriptionController:stopAllPolling`;\n handler: SubscriptionController['stopAllPolling'];\n};\n\n/**\n * Union of all SubscriptionController action types.\n */\nexport type SubscriptionControllerMethodActions =\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerGetBenefitsAction\n | SubscriptionControllerGetSubscriptionByProductAction\n | SubscriptionControllerIsUserEligibleForTrialAction\n | SubscriptionControllerGetSubscriptionsEligibilitiesAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerUnCancelSubscriptionAction\n | SubscriptionControllerStartSubscriptionWithCardAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction\n | SubscriptionControllerSubmitSubscriptionCryptoApprovalAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerUpdatePaymentMethodAction\n | SubscriptionControllerGetBillingPortalUrlAction\n | SubscriptionControllerCacheLastSelectedPaymentMethodAction\n | SubscriptionControllerClearLastSelectedPaymentMethodAction\n | SubscriptionControllerSubmitSponsorshipIntentsAction\n | SubscriptionControllerSubmitUserEventAction\n | SubscriptionControllerAssignUserToCohortAction\n | SubscriptionControllerLinkRewardsAction\n | SubscriptionControllerGetTokenApproveAmountAction\n | SubscriptionControllerGetTokenMinimumBalanceAmountAction\n | SubscriptionControllerClearStateAction\n | SubscriptionControllerTriggerAccessTokenRefreshAction\n | SubscriptionControllerStopAllPollingAction;\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { ControllerStateChangeEvent, ControllerGetStateAction } from '@metamask/base-controller';
2
+ import type { GeolocationControllerGetGeolocationDataAction } from '@metamask/geolocation-controller';
2
3
  import type { Messenger } from '@metamask/messenger';
3
4
  import type { AuthenticationController } from '@metamask/profile-sync-controller';
4
5
  import type { SeedlessOnboardingControllerGetIsUserAuthenticatedAction } from '@metamask/seedless-onboarding-controller';
@@ -28,7 +29,7 @@ export type SubscriptionControllerState = {
28
29
  };
29
30
  export type SubscriptionControllerGetStateAction = ControllerGetStateAction<typeof controllerName, SubscriptionControllerState>;
30
31
  export type SubscriptionControllerActions = SubscriptionControllerGetStateAction | SubscriptionControllerMethodActions;
31
- type AllowedActions = SubscriptionServiceGetPricingAction | SubscriptionServiceGetSubscriptionsAction | SubscriptionServiceGetBenefitsAction | SubscriptionServiceGetSubscriptionsEligibilitiesAction | SubscriptionServiceCancelSubscriptionAction | SubscriptionServiceUnCancelSubscriptionAction | SubscriptionServiceStartSubscriptionWithCardAction | SubscriptionServiceStartSubscriptionWithCryptoAction | SubscriptionServiceUpdatePaymentMethodCardAction | SubscriptionServiceUpdatePaymentMethodCryptoAction | SubscriptionServiceGetBillingPortalUrlAction | SubscriptionServiceSubmitSponsorshipIntentsAction | SubscriptionServiceSubmitUserEventAction | SubscriptionServiceAssignUserToCohortAction | SubscriptionServiceLinkRewardsAction | AuthenticationController.AuthenticationControllerPerformSignOutAction | SeedlessOnboardingControllerGetIsUserAuthenticatedAction;
32
+ type AllowedActions = SubscriptionServiceGetPricingAction | SubscriptionServiceGetSubscriptionsAction | SubscriptionServiceGetBenefitsAction | SubscriptionServiceGetSubscriptionsEligibilitiesAction | SubscriptionServiceCancelSubscriptionAction | SubscriptionServiceUnCancelSubscriptionAction | SubscriptionServiceStartSubscriptionWithCardAction | SubscriptionServiceStartSubscriptionWithCryptoAction | SubscriptionServiceUpdatePaymentMethodCardAction | SubscriptionServiceUpdatePaymentMethodCryptoAction | SubscriptionServiceGetBillingPortalUrlAction | SubscriptionServiceSubmitSponsorshipIntentsAction | SubscriptionServiceSubmitUserEventAction | SubscriptionServiceAssignUserToCohortAction | SubscriptionServiceLinkRewardsAction | AuthenticationController.AuthenticationControllerPerformSignOutAction | SeedlessOnboardingControllerGetIsUserAuthenticatedAction | GeolocationControllerGetGeolocationDataAction;
32
33
  export type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, SubscriptionControllerState>;
33
34
  export type SubscriptionControllerEvents = SubscriptionControllerStateChangeEvent;
34
35
  type AllowedEvents = never;
@@ -134,6 +135,9 @@ export declare class SubscriptionController extends SubscriptionController_base<
134
135
  * `isTrialRequested` on the request is ignored and overwritten from pricing
135
136
  * (`trialPeriodDays > 0`) and `trialedProducts`.
136
137
  *
138
+ * `isEligibleForRefund` is sent as provided. When omitted, it is resolved
139
+ * from geolocation (EU/EEA), or `false` if the lookup fails.
140
+ *
137
141
  * @param request - The start subscription request.
138
142
  * @returns The checkout session response.
139
143
  */
@@ -147,6 +151,9 @@ export declare class SubscriptionController extends SubscriptionController_base<
147
151
  * `isTrialRequested` on the request is ignored and overwritten from pricing
148
152
  * (`trialPeriodDays > 0`) and `trialedProducts`.
149
153
  *
154
+ * `isEligibleForRefund` is sent as provided. When omitted, it is resolved
155
+ * from geolocation (EU/EEA), or `false` if the lookup fails.
156
+ *
150
157
  * @param request - The start crypto subscription request.
151
158
  * @returns The start crypto subscription response.
152
159
  * @throws If `products` is empty.
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.d.ts","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,0BAA0B,EAC1B,wBAAwB,EACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,KAAK,EAAE,wDAAwD,EAAE,MAAM,0CAA0C,CAAC;AAEzH,OAAO,KAAK,EAAE,aAAa,EAAO,MAAM,iBAAiB,CAAC;AAI1D,OAAO,EAEL,cAAc,EAIf,MAAM,gBAAgB,CAAC;AAExB,OAAO,KAAK,EAAE,mCAAmC,EAAE,MAAM,iDAAiD,CAAC;AAC3G,OAAO,KAAK,EACV,2CAA2C,EAC3C,2CAA2C,EAC3C,4CAA4C,EAC5C,oCAAoC,EACpC,mCAAmC,EACnC,yCAAyC,EACzC,sDAAsD,EACtD,oCAAoC,EACpC,kDAAkD,EAClD,oDAAoD,EACpD,iDAAiD,EACjD,wCAAwC,EACxC,6CAA6C,EAC7C,gDAAgD,EAChD,kDAAkD,EACnD,MAAM,8CAA8C,CAAC;AAOtD,OAAO,KAAK,EACV,mBAAmB,EACnB,qBAAqB,EAErB,kCAAkC,EAClC,mCAAmC,EACnC,oCAAoC,EAEpC,YAAY,EACZ,uBAAuB,EACvB,8BAA8B,EAC9B,uCAAuC,EACvC,sBAAsB,EACtB,gBAAgB,EAChB,+BAA+B,EAC/B,uBAAuB,EACvB,+BAA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CAAC,IAAI,CAAC,CAcf;IAEK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAElC;IAsDD;;;;;;OAMG;IACH,qBAAqB,CACnB,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,gBAAgB,GACjC,MAAM,CAgBR;IAED;;;;;;OAMG;IACH,4BAA4B,CAC1B,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,gBAAgB,GACjC,MAAM,CAiBR;IAED;;OAEG;IACH,UAAU,IAAI,IAAI,CAKjB;IAED;;OAEG;IACH,yBAAyB,IAAI,IAAI,CAKhC;CA2XF"}
1
+ {"version":3,"file":"SubscriptionController.d.ts","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,0BAA0B,EAC1B,wBAAwB,EACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,6CAA6C,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,KAAK,EAAE,wDAAwD,EAAE,MAAM,0CAA0C,CAAC;AAEzH,OAAO,KAAK,EAAE,aAAa,EAAO,MAAM,iBAAiB,CAAC;AAI1D,OAAO,EAEL,cAAc,EAKf,MAAM,gBAAgB,CAAC;AAExB,OAAO,KAAK,EAAE,mCAAmC,EAAE,MAAM,iDAAiD,CAAC;AAC3G,OAAO,KAAK,EACV,2CAA2C,EAC3C,2CAA2C,EAC3C,4CAA4C,EAC5C,oCAAoC,EACpC,mCAAmC,EACnC,yCAAyC,EACzC,sDAAsD,EACtD,oCAAoC,EACpC,kDAAkD,EAClD,oDAAoD,EACpD,iDAAiD,EACjD,wCAAwC,EACxC,6CAA6C,EAC7C,gDAAgD,EAChD,kDAAkD,EACnD,MAAM,8CAA8C,CAAC;AAOtD,OAAO,KAAK,EACV,mBAAmB,E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EpE;IAED;;;;;OAKG;IACG,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAKpE;IAED;;;;;;;;OAQG;IACG,WAAW,CACf,OAAO,EAAE,kBAAkB,GAAG;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,GACvD,OAAO,CAAC,IAAI,CAAC,CAcf;IAEK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAElC;IAsDD;;;;;;OAMG;IACH,qBAAqB,CACnB,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,gBAAgB,GACjC,MAAM,CAgBR;IAED;;;;;;OAMG;IACH,4BAA4B,CAC1B,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,gBAAgB,GACjC,MAAM,CAiBR;IAED;;OAEG;IACH,UAAU,IAAI,IAAI,CAKjB;IAED;;OAEG;IACH,yBAAyB,IAAI,IAAI,CAKhC;CAsZF"}
@@ -2,7 +2,7 @@ import { StaticIntervalPollingController } from '@metamask/polling-controller';
2
2
  import { TransactionType } from '@metamask/transaction-controller';
3
3
  import { BigNumber } from 'bignumber.js';
4
4
  import deepEqual from 'fast-deep-equal';
5
- import { ACTIVE_SUBSCRIPTION_STATUSES, controllerName, DEFAULT_POLLING_INTERVAL, SubscriptionControllerErrorMessage, SubscriptionDelegationServiceErrorMessage, } from './constants.js';
5
+ import { ACTIVE_SUBSCRIPTION_STATUSES, controllerName, DEFAULT_POLLING_INTERVAL, REFUND_ELIGIBLE_COUNTRIES, SubscriptionControllerErrorMessage, SubscriptionDelegationServiceErrorMessage, } from './constants.js';
6
6
  import { createModuleLogger, projectLogger } from './logger.js';
7
7
  import { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES, SUBSCRIPTION_STATUSES, } from './types.js';
8
8
  const log = createModuleLogger(projectLogger, controllerName);
@@ -319,6 +319,9 @@ export class SubscriptionController extends StaticIntervalPollingController() {
319
319
  * `isTrialRequested` on the request is ignored and overwritten from pricing
320
320
  * (`trialPeriodDays > 0`) and `trialedProducts`.
321
321
  *
322
+ * `isEligibleForRefund` is sent as provided. When omitted, it is resolved
323
+ * from geolocation (EU/EEA), or `false` if the lookup fails.
324
+ *
322
325
  * @param request - The start subscription request.
323
326
  * @returns The checkout session response.
324
327
  */
@@ -329,6 +332,7 @@ export class SubscriptionController extends StaticIntervalPollingController() {
329
332
  const response = await this.messenger.call('SubscriptionService:startSubscriptionWithCard', {
330
333
  ...request,
331
334
  isTrialRequested: this.#getIsTrialRequested(request.products, request.recurringInterval),
335
+ isEligibleForRefund: await this.#getIsEligibleForRefund(request.isEligibleForRefund),
332
336
  });
333
337
  // note: no need to trigger access token refresh after startSubscriptionWithCard request because this only return stripe checkout session url, subscription not created yet
334
338
  return response;
@@ -342,6 +346,9 @@ export class SubscriptionController extends StaticIntervalPollingController() {
342
346
  * `isTrialRequested` on the request is ignored and overwritten from pricing
343
347
  * (`trialPeriodDays > 0`) and `trialedProducts`.
344
348
  *
349
+ * `isEligibleForRefund` is sent as provided. When omitted, it is resolved
350
+ * from geolocation (EU/EEA), or `false` if the lookup fails.
351
+ *
345
352
  * @param request - The start crypto subscription request.
346
353
  * @returns The start crypto subscription response.
347
354
  * @throws If `products` is empty.
@@ -362,6 +369,7 @@ export class SubscriptionController extends StaticIntervalPollingController() {
362
369
  const response = await this.messenger.call('SubscriptionService:startSubscriptionWithCrypto', {
363
370
  ...subscriptionRequest,
364
371
  isTrialRequested,
372
+ isEligibleForRefund: await this.#getIsEligibleForRefund(request.isEligibleForRefund),
365
373
  });
366
374
  // Crypto start creates the subscription immediately (unlike card checkout).
367
375
  await this.getSubscriptions();
@@ -839,6 +847,26 @@ export class SubscriptionController extends StaticIntervalPollingController() {
839
847
  return productPrice.trialPeriodDays > 0;
840
848
  });
841
849
  }
850
+ /**
851
+ * Returns the caller-provided refund eligibility when set. Otherwise
852
+ * resolves it from geolocation (EU/EEA), or `false` if the lookup fails.
853
+ *
854
+ * @param isEligibleForRefund - Caller-provided eligibility, if any.
855
+ * @returns Whether the user is eligible for a refund.
856
+ */
857
+ async #getIsEligibleForRefund(isEligibleForRefund) {
858
+ if (isEligibleForRefund !== undefined) {
859
+ return isEligibleForRefund;
860
+ }
861
+ try {
862
+ const { country } = await this.messenger.call('GeolocationController:getGeolocationData');
863
+ return (country !== null && REFUND_ELIGIBLE_COUNTRIES.has(country.toUpperCase()));
864
+ }
865
+ catch (error) {
866
+ log('Failed to resolve geolocation for refund eligibility', error);
867
+ return false;
868
+ }
869
+ }
842
870
  #findCryptoPaymentMethod(productType, cryptoAuthMethod) {
843
871
  const matches = [];
844
872
  for (const paymentMethod of this.state.pricing?.paymentMethods ?? []) {
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.js","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAG/E,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,SAAS,MAAM,iBAAiB,CAAC;AAExC,OAAO,EACL,4BAA4B,EAC5B,cAAc,EACd,wBAAwB,EACxB,kCAAkC,EAClC,yCAAyC,GAC1C,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAmBhE,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,qBAAqB,GACtB,MAAM,YAAY,CAAC;AAsCpB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;AAsF9D;;;;GAIG;AACH,MAAM,UAAU,qCAAqC;IACnD,OAAO;QACL,aAAa,EAAE,EAAE;QACjB,eAAe,EAAE,EAAE;KACpB,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,8BAA8B,GAClC;IACE,aAAa,EAAE;QACb,kBAAk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ACnD,CAAC,CAAC,CAAC;IACL,CAAC;IAED,oBAAoB,CAAC,MAAqB,EAAE,MAAqB;QAC/D,yDAAyD;QACzD,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;gBACvB,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,OAAO,CACL,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,CACpC,CAAC;IACJ,CAAC;IAED,sBAAsB,CAAC,YAA0B;QAC/C,MAAM,sBAAsB,GAAG;YAC7B,GAAG,YAAY;YACf,6BAA6B;YAC7B,QAAQ,EAAE,CAAC,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACjD,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAC7B;SACF,CAAC;QAEF,OAAO,IAAI,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import type {\n StateMetadata,\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport type { SeedlessOnboardingControllerGetIsUserAuthenticatedAction } from '@metamask/seedless-onboarding-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\nimport deepEqual from 'fast-deep-equal';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n controllerName,\n DEFAULT_POLLING_INTERVAL,\n SubscriptionControllerErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from './constants.js';\nimport { createModuleLogger, projectLogger } from './logger.js';\nimport type { SubscriptionControllerMethodActions } from './SubscriptionController-method-action-types.js';\nimport type {\n SubscriptionServiceAssignUserToCohortAction,\n SubscriptionServiceCancelSubscriptionAction,\n SubscriptionServiceGetBillingPortalUrlAction,\n SubscriptionServiceGetBenefitsAction,\n SubscriptionServiceGetPricingAction,\n SubscriptionServiceGetSubscriptionsAction,\n SubscriptionServiceGetSubscriptionsEligibilitiesAction,\n SubscriptionServiceLinkRewardsAction,\n SubscriptionServiceStartSubscriptionWithCardAction,\n SubscriptionServiceStartSubscriptionWithCryptoAction,\n SubscriptionServiceSubmitSponsorshipIntentsAction,\n SubscriptionServiceSubmitUserEventAction,\n SubscriptionServiceUnCancelSubscriptionAction,\n SubscriptionServiceUpdatePaymentMethodCardAction,\n SubscriptionServiceUpdatePaymentMethodCryptoAction,\n} from './SubscriptionService-method-action-types.js';\nimport {\n CRYPTO_AUTH_METHODS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\nimport type {\n AssignCohortRequest,\n BillingPortalResponse,\n CryptoAuthMethod,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n GetSubscriptionsEligibilitiesRequest,\n GetSubscriptionsResponse,\n ProductPrice,\n SubscriptionEligibility,\n StartCryptoSubscriptionRequest,\n SubmitSubscriptionCryptoApprovalRequest,\n SubmitUserEventRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodOpts,\n CachedLastSelectedPaymentMethod,\n CacheLastSelectedPaymentMethodRequest,\n SubmitSponsorshipIntentsMethodParams,\n RecurringInterval,\n SubscriptionStatus,\n LinkRewardsRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionResponse,\n CancelSubscriptionRequest,\n PricingCryptoPaymentMethod,\n SubscriptionBenefitsResponse,\n SubscriptionBenefitsState,\n} from './types.js';\nimport type {\n PricingResponse,\n ProductType,\n ProductEntitlements,\n StartSubscriptionRequest,\n Subscription,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, controllerName);\n\nexport type SubscriptionControllerState = {\n customerId?: string;\n trialedProducts: ProductType[];\n subscriptions: Subscription[];\n productEntitlements?: ProductEntitlements;\n pricing?: PricingResponse;\n benefits?: SubscriptionBenefitsState;\n /** The last subscription that user has subscribed to if any. */\n lastSubscription?: Subscription;\n /** The reward account ID if user has linked rewards to the subscription. */\n rewardAccountId?: CaipAccountId;\n /**\n * The last selected payment method for the user.\n * This is used to display the last selected payment method in the UI.\n * This state is also meant to be used internally to track the last selected payment method for the user. (e.g. for crypto subscriptions)\n */\n lastSelectedPaymentMethod?: Partial<\n Record<ProductType, CachedLastSelectedPaymentMethod>\n >;\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerMethodActions;\n\ntype AllowedActions =\n | SubscriptionServiceGetPricingAction\n | SubscriptionServiceGetSubscriptionsAction\n | SubscriptionServiceGetBenefitsAction\n | SubscriptionServiceGetSubscriptionsEligibilitiesAction\n | SubscriptionServiceCancelSubscriptionAction\n | SubscriptionServiceUnCancelSubscriptionAction\n | SubscriptionServiceStartSubscriptionWithCardAction\n | SubscriptionServiceStartSubscriptionWithCryptoAction\n | SubscriptionServiceUpdatePaymentMethodCardAction\n | SubscriptionServiceUpdatePaymentMethodCryptoAction\n | SubscriptionServiceGetBillingPortalUrlAction\n | SubscriptionServiceSubmitSponsorshipIntentsAction\n | SubscriptionServiceSubmitUserEventAction\n | SubscriptionServiceAssignUserToCohortAction\n | SubscriptionServiceLinkRewardsAction\n | AuthenticationController.AuthenticationControllerPerformSignOutAction\n | SeedlessOnboardingControllerGetIsUserAuthenticatedAction;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\ntype AllowedEvents = never;\n\n// Messenger\nexport type SubscriptionControllerMessenger = Messenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Polling interval to use for the subscription controller.\n *\n * @default 5 minutes.\n */\n pollingInterval?: number;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n trialedProducts: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n productEntitlements: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n lastSubscription: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n customerId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n rewardAccountId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n trialedProducts: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n pricing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n benefits: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n lastSelectedPaymentMethod: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n };\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getPricing',\n 'getSubscriptions',\n 'getBenefits',\n 'getSubscriptionByProduct',\n 'isUserEligibleForTrial',\n 'getSubscriptionsEligibilities',\n 'cancelSubscription',\n 'unCancelSubscription',\n 'startSubscriptionWithCard',\n 'startSubscriptionWithCrypto',\n 'stopAllPolling',\n 'submitSubscriptionCryptoApproval',\n 'getCryptoApproveTransactionParams',\n 'updatePaymentMethod',\n 'getBillingPortalUrl',\n 'cacheLastSelectedPaymentMethod',\n 'clearLastSelectedPaymentMethod',\n 'submitSponsorshipIntents',\n 'submitUserEvent',\n 'assignUserToCohort',\n 'linkRewards',\n 'getTokenApproveAmount',\n 'getTokenMinimumBalanceAmount',\n 'clearState',\n 'triggerAccessTokenRefresh',\n] as const;\n\nexport class SubscriptionController extends StaticIntervalPollingController()<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.pollingInterval - The polling interval to use for the subscription controller.\n */\n constructor(options: SubscriptionControllerOptions) {\n const {\n messenger,\n state,\n pollingInterval = DEFAULT_POLLING_INTERVAL,\n } = options;\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.setIntervalLength(pollingInterval);\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n const pricing = await this.messenger.call('SubscriptionService:getPricing');\n this.update((state) => {\n state.pricing = pricing;\n });\n return pricing;\n }\n\n async getSubscriptions(): Promise<Subscription[]> {\n return await this.#getSubscriptions();\n }\n\n async #getSubscriptions({\n refreshBenefits = true,\n }: { refreshBenefits?: boolean } = {}): Promise<Subscription[]> {\n const currentSubscriptions = this.state.subscriptions;\n const currentTrialedProducts = this.state.trialedProducts;\n const currentCustomerId = this.state.customerId;\n const currentLastSubscription = this.state.lastSubscription;\n const currentRewardAccountId = this.state.rewardAccountId;\n const currentProductEntitlements = this.state.productEntitlements;\n const currentSubscriptionState: GetSubscriptionsResponse = {\n customerId: currentCustomerId,\n subscriptions: currentSubscriptions,\n trialedProducts: currentTrialedProducts,\n lastSubscription: currentLastSubscription,\n rewardAccountId: currentRewardAccountId,\n productEntitlements: currentProductEntitlements,\n };\n\n const newSubscriptionState = await this.messenger.call(\n 'SubscriptionService:getSubscriptions',\n );\n\n this.#updateSubscriptionStateIfChanged(\n currentSubscriptionState,\n newSubscriptionState,\n );\n\n await this.#refreshBenefitsIfActive(refreshBenefits);\n\n return newSubscriptionState.subscriptions;\n }\n\n /**\n * Updates the subscription state and refreshes the access token when the\n * fetched subscription state differs from the current state.\n *\n * @param currentState - The subscription state captured before the request.\n * @param newState - The subscription state returned by the service.\n */\n #updateSubscriptionStateIfChanged(\n currentState: GetSubscriptionsResponse,\n newState: GetSubscriptionsResponse,\n ): void {\n const {\n subscriptions: currentSubscriptions,\n trialedProducts: currentTrialedProducts,\n customerId: currentCustomerId,\n lastSubscription: currentLastSubscription,\n rewardAccountId: currentRewardAccountId,\n productEntitlements: currentProductEntitlements,\n } = currentState;\n const {\n customerId: newCustomerId,\n subscriptions: newSubscriptions,\n trialedProducts: newTrialedProducts,\n lastSubscription: newLastSubscription,\n rewardAccountId: newRewardAccountId,\n productEntitlements: newProductEntitlements,\n } = newState;\n\n const areSubscriptionsEqual = this.#areSubscriptionsEqual(\n currentSubscriptions,\n newSubscriptions,\n );\n const areTrialedProductsEqual = this.#areTrialedProductsEqual(\n currentTrialedProducts,\n newTrialedProducts,\n );\n const isLastSubscriptionEqual = this.#isSubscriptionEqual(\n currentLastSubscription,\n newLastSubscription,\n );\n const areCustomerIdsEqual = currentCustomerId === newCustomerId;\n const areRewardAccountIdsEqual =\n currentRewardAccountId === newRewardAccountId;\n const areProductEntitlementsEqual = this.#areProductEntitlementsEqual(\n currentProductEntitlements,\n newProductEntitlements,\n );\n // only update the state if the subscriptions or trialed products are different\n // this prevents unnecessary state updates events, easier for the clients to handle\n\n // Only update the state if any subscription-related field changed. This\n // prevents unnecessary state change events for clients to handle.\n if (\n !areSubscriptionsEqual ||\n !isLastSubscriptionEqual ||\n !areTrialedProductsEqual ||\n !areCustomerIdsEqual ||\n !areRewardAccountIdsEqual ||\n !areProductEntitlementsEqual\n ) {\n this.update((state) => {\n state.subscriptions = newSubscriptions;\n state.customerId = newCustomerId;\n state.trialedProducts = newTrialedProducts;\n state.lastSubscription = newLastSubscription;\n state.rewardAccountId = newRewardAccountId;\n // Omitted entitlements are an empty map so selectors fail closed\n // instead of keeping last-known paid-feature flags.\n state.productEntitlements = newProductEntitlements ?? {};\n });\n // Trigger an access token refresh to ensure the user has the latest\n // access token after a subscription state change.\n this.triggerAccessTokenRefresh();\n }\n }\n\n /**\n * Gets and stores the user's subscription benefits.\n *\n * @returns The benefits response.\n * @throws If the user is not an active Money Account Plus subscriber or is\n * not eligible for benefits.\n */\n async getBenefits(): Promise<SubscriptionBenefitsResponse> {\n this.#assertIsActiveMoneyAccountPlusSubscriber();\n\n const benefits = await this.messenger.call(\n 'SubscriptionService:getBenefits',\n );\n\n // The subscription may have become inactive while the benefits request\n // was in flight. Re-check before persisting the response so stale\n // benefits cannot be restored after entitlement ends.\n this.#assertIsActiveMoneyAccountPlusSubscriber();\n\n this.update((state) => {\n state.benefits = benefits.eligible\n ? {\n billingPeriodId: benefits.billingPeriodId,\n ...benefits.products,\n }\n : undefined;\n });\n\n if (!benefits.eligible) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n\n return benefits;\n }\n\n /**\n * Get the subscription by product.\n *\n * @param productType - The product type.\n * @returns The subscription.\n */\n getSubscriptionByProduct(productType: ProductType): Subscription | undefined {\n return this.state.subscriptions.find((subscription) =>\n subscription.products.some((product) => product.name === productType),\n );\n }\n\n /**\n * Whether the user is eligible to start a trial for the given product.\n *\n * Shield is eligible when the user has not trialed Shield before.\n * Money Account Plus is eligible when the user has not trialed it before\n * and is authenticated with social login. Only an unlocked wallet can\n * subscribe, so `SeedlessOnboardingController:getIsUserAuthenticated` is a\n * sufficient social-login check.\n *\n * @param productType - The product to check.\n * @returns Whether the user is eligible for a trial.\n */\n async isUserEligibleForTrial(productType: ProductType): Promise<boolean> {\n if (this.state.trialedProducts.includes(productType)) {\n return false;\n }\n\n switch (productType) {\n case PRODUCT_TYPES.SHIELD:\n return true;\n case PRODUCT_TYPES.MONEY_ACCOUNT_PLUS:\n return await this.messenger.call(\n 'SeedlessOnboardingController:getIsUserAuthenticated',\n );\n default: {\n // `productType` is `never` here. A new `PRODUCT_TYPES` member fails\n // compilation until this switch handles it.\n const unexpectedProduct: never = productType;\n throw new Error(\n `Unexpected product type: ${String(unexpectedProduct)}`,\n );\n }\n }\n }\n\n /**\n * Get the subscriptions eligibilities.\n *\n * @param request - Optional request object containing user balance to check cohort eligibility.\n * @returns The subscriptions eligibilities.\n */\n async getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]> {\n return await this.messenger.call(\n 'SubscriptionService:getSubscriptionsEligibilities',\n request,\n );\n }\n\n async cancelSubscription(request: CancelSubscriptionRequest): Promise<void> {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const cancelledSubscription = await this.messenger.call(\n 'SubscriptionService:cancelSubscription',\n request,\n );\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...cancelledSubscription }\n : subscription,\n );\n });\n\n try {\n await this.#getSubscriptions();\n } catch (error) {\n log('Failed to refresh subscriptions after cancellation', error);\n\n // Preserve the existing best-effort benefits refresh behavior if the\n // canonical subscription refresh is unavailable.\n await this.#refreshBenefitsIfActive();\n }\n\n this.triggerAccessTokenRefresh();\n }\n\n async unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<void> {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const uncancelledSubscription = await this.messenger.call(\n 'SubscriptionService:unCancelSubscription',\n {\n subscriptionId: request.subscriptionId,\n },\n );\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...uncancelledSubscription }\n : subscription,\n );\n });\n\n await this.#refreshBenefitsIfActive();\n\n this.triggerAccessTokenRefresh();\n }\n\n /**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n // get the latest subscriptions state before computing trial eligibility\n await this.getSubscriptions();\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCard',\n {\n ...request,\n isTrialRequested: this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\n ),\n },\n );\n // note: no need to trigger access token refresh after startSubscriptionWithCard request because this only return stripe checkout session url, subscription not created yet\n\n return response;\n }\n\n /**\n * Starts a crypto-paid subscription for the requested products\n * (e.g. Shield or Money Account Plus). Unlike card checkout, this\n * creates the subscription immediately, so local state is refreshed\n * afterwards.\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * @param request - The start crypto subscription request.\n * @returns The start crypto subscription response.\n * @throws If `products` is empty.\n */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n // get the latest subscriptions state before computing trial eligibility\n await this.#getSubscriptions({ refreshBenefits: false });\n this.#assertIsUserNotSubscribed({ products: request.products });\n const isTrialRequested = this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\n );\n if (\n request.assertTrialEligibility &&\n request.isTrialRequested !== isTrialRequested\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.TrialEligibilityChanged,\n );\n }\n const {\n assertTrialEligibility: _assertTrialEligibility,\n ...subscriptionRequest\n } = request;\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCrypto',\n {\n ...subscriptionRequest,\n isTrialRequested,\n },\n );\n\n // Crypto start creates the subscription immediately (unlike card checkout).\n await this.getSubscriptions();\n\n return response;\n }\n\n /**\n * Submits a Shield ERC-20 crypto approval transaction to start or update a\n * crypto subscription.\n *\n * This handler is Shield / `TransactionType.shieldSubscriptionApprove` only.\n * Delegation-based products (e.g. Money Account) must call\n * `startSubscriptionWithCrypto` instead.\n *\n * @param request - The crypto approval request.\n * @param request.productType - The subscription product. Typed as\n * `typeof PRODUCT_TYPES.SHIELD` only at the moment (future might support more\n * product).\n * @param request.txMeta - The transaction metadata. Must have type\n * `TransactionType.shieldSubscriptionApprove`.\n * @param request.isSponsored - Whether the transaction is sponsored.\n * @param request.rewardAccountId - The account ID of the reward subscription\n * to link.\n * @throws If `productType` is not Shield or `txMeta.type` is not\n * `shieldSubscriptionApprove`.\n * @returns void\n */\n async submitSubscriptionCryptoApproval(\n request: SubmitSubscriptionCryptoApprovalRequest,\n ): Promise<void> {\n const { productType, txMeta, isSponsored, rewardAccountId } = request;\n if (\n // Widen for the runtime guard: JS / unsound callers may still pass a\n // non-Shield product.\n (productType as ProductType) !== PRODUCT_TYPES.SHIELD ||\n txMeta.type !== TransactionType.shieldSubscriptionApprove\n ) {\n throw new Error(\n SubscriptionControllerErrorMessage.CryptoApprovalRequiresShieldApprove,\n );\n }\n\n const { chainId, rawTx } = txMeta;\n if (!chainId || !rawTx) {\n throw new Error('Chain ID or raw transaction not found');\n }\n\n const { pricing, lastSelectedPaymentMethod } = this.state;\n if (!pricing) {\n throw new Error('Subscription pricing not found');\n }\n if (!lastSelectedPaymentMethod) {\n throw new Error('Last selected payment method not found');\n }\n const lastSelectedPaymentMethodForProduct =\n lastSelectedPaymentMethod[productType];\n this.#assertIsPaymentMethodCrypto(lastSelectedPaymentMethodForProduct);\n\n const productPrice = this.#getProductPriceByProductAndPlan(\n productType,\n lastSelectedPaymentMethodForProduct.plan,\n );\n // get the latest subscriptions state before computing trial eligibility\n await this.#getSubscriptions({ refreshBenefits: false });\n const isTrialRequested = this.#getIsTrialRequested(\n [productType],\n lastSelectedPaymentMethodForProduct.plan,\n );\n const currentSubscription = this.getSubscriptionByProduct(productType);\n\n this.#assertValidSubscriptionStateForCryptoApproval({\n productType,\n });\n // if subscription exists, this transaction is for changing payment method\n const isChangePaymentMethod = Boolean(currentSubscription);\n\n if (isChangePaymentMethod) {\n await this.updatePaymentMethod({\n paymentType: PAYMENT_TYPES.byCrypto,\n subscriptionId: (currentSubscription as Subscription).id,\n chainId,\n payerAddress: txMeta.txParams.from as Hex,\n tokenSymbol: lastSelectedPaymentMethodForProduct.paymentTokenSymbol,\n rawTransaction: rawTx as Hex,\n recurringInterval: productPrice.interval,\n billingCycles: productPrice.minBillingCycles,\n });\n } else {\n const params: StartCryptoSubscriptionRequest = {\n products: [productType],\n isTrialRequested,\n recurringInterval: productPrice.interval,\n billingCycles: productPrice.minBillingCycles,\n chainId,\n payerAddress: txMeta.txParams.from as Hex,\n tokenSymbol: lastSelectedPaymentMethodForProduct.paymentTokenSymbol,\n rawTransaction: rawTx as Hex,\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n isSponsored,\n useTestClock: lastSelectedPaymentMethodForProduct.useTestClock,\n rewardAccountId,\n };\n await this.startSubscriptionWithCrypto(params);\n }\n\n // update the subscriptions state after subscription created in server\n await this.#getSubscriptions({ refreshBenefits: false });\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): GetCryptoApproveTransactionResponse {\n const { pricing } = this.state;\n if (!pricing) {\n throw new Error('Subscription pricing not found');\n }\n const product = pricing.products.find(\n (productInfo) => productInfo.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find(\n (productPrice) => productPrice.interval === request.interval,\n );\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = this.#findCryptoPaymentMethod(\n request.productType,\n CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (chain) => chain.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (token) =>\n token.address.toLowerCase() ===\n request.paymentTokenAddress.toLowerCase(),\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount,\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(\n opts: UpdatePaymentMethodOpts,\n ): Promise<UpdatePaymentMethodCardResponse | Subscription[]> {\n if (opts.paymentType === PAYMENT_TYPES.byCard) {\n const { paymentType, ...cardRequest } = opts;\n return await this.messenger.call(\n 'SubscriptionService:updatePaymentMethodCard',\n cardRequest,\n );\n } else if (opts.paymentType === PAYMENT_TYPES.byCrypto) {\n const { paymentType, ...cryptoRequest } = opts;\n await this.messenger.call(\n 'SubscriptionService:updatePaymentMethodCrypto',\n cryptoRequest,\n );\n return await this.getSubscriptions();\n }\n throw new Error('Invalid payment type');\n }\n\n /**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n return await this.messenger.call('SubscriptionService:getBillingPortalUrl');\n }\n\n /**\n * Cache the last selected payment method for a specific product.\n *\n * @param request - The request object.\n * @param request.product - The product to cache the payment method for.\n * @param request.paymentMethod - The payment method to cache.\n * @param request.paymentMethod.type - The type of the payment method.\n * @param request.paymentMethod.paymentTokenAddress - The payment token address.\n * @param request.paymentMethod.plan - The plan of the payment method.\n */\n cacheLastSelectedPaymentMethod(\n request: CacheLastSelectedPaymentMethodRequest,\n ): void {\n const { product, paymentMethod } = request;\n if (\n paymentMethod.type === PAYMENT_TYPES.byCrypto &&\n (!paymentMethod.paymentTokenAddress || !paymentMethod.paymentTokenSymbol)\n ) {\n throw new Error(\n SubscriptionControllerErrorMessage.PaymentTokenAddressAndSymbolRequiredForCrypto,\n );\n }\n\n this.update((state) => {\n state.lastSelectedPaymentMethod = {\n ...state.lastSelectedPaymentMethod,\n [product]: paymentMethod,\n };\n });\n }\n\n /**\n * Clear the last selected payment method for a specific product.\n *\n * @param product - The product to clear the payment method for.\n */\n clearLastSelectedPaymentMethod(product: ProductType): void {\n this.update((state) => {\n if (state.lastSelectedPaymentMethod) {\n const { [product]: _, ...rest } = state.lastSelectedPaymentMethod;\n state.lastSelectedPaymentMethod = rest;\n }\n });\n }\n\n /**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example {\n * address: '0x1234567890123456789012345678901234567890',\n * products: [ProductType.Shield],\n * recurringInterval: RecurringInterval.Month,\n * billingCycles: 1,\n * }\n * @returns resolves to true if the sponsorship is supported and intents were submitted successfully, false if the chain does not support sponsorship or the user has already trialed\n * @throws If the crypto payment method or chain is missing from pricing\n */\n async submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsMethodParams,\n ): Promise<boolean> {\n if (request.products.length === 0) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const selectedPaymentMethod =\n this.state.lastSelectedPaymentMethod?.[request.products[0]];\n this.#assertIsPaymentMethodCrypto(selectedPaymentMethod);\n\n const cryptoAuthMethod =\n selectedPaymentMethod.cryptoAuthMethod ??\n CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n const isEligibleForTrialedSponsorship =\n this.#getIsEligibleForTrialedSponsorship(\n request.chainId,\n request.products,\n cryptoAuthMethod,\n );\n if (!isEligibleForTrialedSponsorship) {\n return false;\n }\n\n const { paymentTokenSymbol, plan } = selectedPaymentMethod;\n const productPrice = this.#getProductPriceByProductAndPlan(\n // we only support one product at a time for now\n request.products[0],\n plan,\n );\n const billingCycles = productPrice.minBillingCycles;\n\n await this.messenger.call('SubscriptionService:submitSponsorshipIntents', {\n ...request,\n paymentTokenSymbol,\n billingCycles,\n recurringInterval: plan,\n });\n return true;\n }\n\n /**\n * Submit a user event from the UI. (e.g. shield modal viewed)\n *\n * @param request - Request object containing the event to submit.\n * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }\n */\n async submitUserEvent(request: SubmitUserEventRequest): Promise<void> {\n await this.messenger.call('SubscriptionService:submitUserEvent', request);\n }\n\n /**\n * Assign user to a cohort.\n *\n * @param request - Request object containing the cohort to assign the user to.\n * @example { cohort: 'post_tx' }\n */\n async assignUserToCohort(request: AssignCohortRequest): Promise<void> {\n await this.messenger.call(\n 'SubscriptionService:assignUserToCohort',\n request,\n );\n }\n\n /**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward subscription ID.\n * @param request.subscriptionId - The ID of the subscription to link rewards to.\n * @param request.rewardAccountId - The account ID of the reward subscription to link to the subscription.\n * @example { subscriptionId: '1234567890', rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns Resolves when the rewards are linked successfully.\n */\n async linkRewards(\n request: LinkRewardsRequest & { subscriptionId: string },\n ): Promise<void> {\n // assert that the user is subscribed to the subscription\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n // link rewards to the subscription\n const response = await this.messenger.call(\n 'SubscriptionService:linkRewards',\n {\n rewardAccountId: request.rewardAccountId,\n },\n );\n if (!response.success) {\n throw new Error(SubscriptionControllerErrorMessage.LinkRewardsFailed);\n }\n }\n\n async _executePoll(): Promise<void> {\n await this.getSubscriptions();\n }\n\n async #refreshBenefitsIfActive(refreshBenefits = true): Promise<void> {\n if (!this.#hasActiveMoneyAccountPlusSubscription()) {\n if (this.state.benefits) {\n this.update((state) => {\n state.benefits = undefined;\n });\n }\n return;\n }\n\n if (!refreshBenefits) {\n return;\n }\n\n try {\n await this.getBenefits();\n } catch (error) {\n log('Failed to refresh subscription benefits', error);\n }\n }\n\n /**\n * Calculate total subscription price amount (approval amount) from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice): string {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount = new BigNumber(price.unitAmount)\n .div(10 ** price.unitDecimals)\n .multipliedBy(price.minBillingCycles)\n .toString();\n return amount;\n }\n\n /**\n * Calculate minimum subscription balance amount from price info\n *\n * @param price - The price info\n * @returns The balance amount\n */\n #getSubscriptionBalanceAmount(price: ProductPrice): string {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount = new BigNumber(price.unitAmount)\n .div(10 ** price.unitDecimals)\n .multipliedBy(price.minBillingCyclesForBalance)\n .toString();\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ): string {\n const conversionRate =\n tokenPaymentInfo.conversionRate?.[\n price.currency as keyof NonNullable<TokenPaymentInfo['conversionRate']>\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // price of the product\n const priceAmount = new BigNumber(this.#getSubscriptionPriceAmount(price));\n\n const tokenDecimal = new BigNumber(10).pow(tokenPaymentInfo.decimals);\n const tokenAmount = priceAmount\n .multipliedBy(tokenDecimal)\n .div(conversionRate);\n return tokenAmount.toFixed(0);\n }\n\n /**\n * Calculate token minimum balance amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token balance amount\n */\n getTokenMinimumBalanceAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ): string {\n const conversionRate =\n tokenPaymentInfo.conversionRate?.[\n price.currency as keyof NonNullable<TokenPaymentInfo['conversionRate']>\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n const balanceAmount = new BigNumber(\n this.#getSubscriptionBalanceAmount(price),\n );\n\n const tokenDecimal = new BigNumber(10).pow(tokenPaymentInfo.decimals);\n const tokenAmount = balanceAmount\n .multipliedBy(tokenDecimal)\n .div(conversionRate);\n return tokenAmount.toFixed(0);\n }\n\n /**\n * Clears the subscription state and resets to default values.\n */\n clearState(): void {\n const defaultState = getDefaultSubscriptionControllerState();\n this.update(() => {\n return defaultState;\n });\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh(): void {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messenger.call('AuthenticationController:performSignOut');\n }\n\n #getProductPriceByProductAndPlan(\n productType: ProductType,\n plan: RecurringInterval,\n ): ProductPrice {\n const { pricing } = this.state;\n const productPricing = pricing?.products.find(\n (product) => product.name === productType,\n );\n const productPrice = productPricing?.prices.find(\n (price) => price.interval === plan,\n );\n if (!productPrice) {\n throw new Error(SubscriptionControllerErrorMessage.ProductPriceNotFound);\n }\n return productPrice;\n }\n\n #assertValidSubscriptionStateForCryptoApproval({\n productType,\n }: {\n productType: ProductType;\n }): void {\n const subscription = this.state.subscriptions.find((sub) =>\n sub.products.some((product) => product.name === productType),\n );\n\n const isValid =\n !subscription ||\n (\n [\n SUBSCRIPTION_STATUSES.awaitingFunds,\n SUBSCRIPTION_STATUSES.pastDue,\n SUBSCRIPTION_STATUSES.unpaid,\n SUBSCRIPTION_STATUSES.paused,\n SUBSCRIPTION_STATUSES.provisional,\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n ] as SubscriptionStatus[]\n ).includes(subscription.status);\n if (!isValid) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionNotValidForCryptoApproval,\n );\n }\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }): void {\n const subscription = this.state.subscriptions.find((sub) =>\n sub.products.some((product) => products.includes(product.name)),\n );\n\n if (\n subscription &&\n ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status)\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n #assertIsActiveMoneyAccountPlusSubscriber(): void {\n if (!this.#hasActiveMoneyAccountPlusSubscription()) {\n if (this.state.benefits) {\n this.update((state) => {\n state.benefits = undefined;\n });\n }\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }): void {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n\n /**\n * Asserts that the value is a valid crypto payment method.\n *\n * After this assert, `cryptoAuthMethod` and `useTestClock` remain optional\n * because persisted cache entries may omit them.\n *\n * @param value - The value to assert.\n * @throws an error if the value is not a valid crypto payment method.\n */\n #assertIsPaymentMethodCrypto(\n value: CachedLastSelectedPaymentMethod | undefined,\n ): asserts value is CachedLastSelectedPaymentMethod & {\n type: typeof PAYMENT_TYPES.byCrypto;\n paymentTokenAddress: Hex;\n paymentTokenSymbol: string;\n } {\n if (\n value?.type !== PAYMENT_TYPES.byCrypto ||\n !value.paymentTokenAddress ||\n !value.paymentTokenSymbol\n ) {\n throw new Error(\n SubscriptionControllerErrorMessage.PaymentMethodNotCrypto,\n );\n }\n }\n\n #hasActiveMoneyAccountPlusSubscription(): boolean {\n return this.state.subscriptions.some(\n (subscription) =>\n subscription.products.some(\n (product) => product.name === PRODUCT_TYPES.MONEY_ACCOUNT_PLUS,\n ) && ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status),\n );\n }\n\n /**\n * Determines if the user is eligible for trialed sponsorship for the given chain and products.\n * The user is eligible if the chain supports sponsorship and the user has not trialed the provided products before.\n *\n * @param chainId - The chain ID\n * @param products - The products to check eligibility for\n * @param cryptoAuthMethod - The crypto authorization method of the selected payment method\n * @returns True if the user is eligible for trialed sponsorship, false otherwise\n */\n #getIsEligibleForTrialedSponsorship(\n chainId: Hex,\n products: ProductType[],\n cryptoAuthMethod: CryptoAuthMethod,\n ): boolean {\n const isSponsorshipSupported = this.#getChainSupportsSponsorship(\n chainId,\n products[0],\n cryptoAuthMethod,\n );\n\n // verify if the user has trialed the provided products before\n const hasTrialedBefore = this.state.trialedProducts.some((product) =>\n products.includes(product),\n );\n\n return isSponsorshipSupported && !hasTrialedBefore;\n }\n\n /**\n * Whether a trial should be requested for the given products and plan.\n * True only when every product has `trialPeriodDays > 0` and has not\n * already been trialed.\n *\n * @param products - The products to check.\n * @param plan - The recurring interval to look up pricing for.\n * @returns Whether a trial should be requested.\n */\n #getIsTrialRequested(\n products: ProductType[],\n plan: RecurringInterval,\n ): boolean {\n return products.every((productType) => {\n if (this.state.trialedProducts.includes(productType)) {\n return false;\n }\n const productPrice = this.#getProductPriceByProductAndPlan(\n productType,\n plan,\n );\n return productPrice.trialPeriodDays > 0;\n });\n }\n\n #findCryptoPaymentMethod(\n productType: ProductType,\n cryptoAuthMethod: CryptoAuthMethod,\n ): PricingCryptoPaymentMethod | undefined {\n const matches: {\n method: PricingCryptoPaymentMethod;\n explicit: boolean;\n }[] = [];\n\n for (const paymentMethod of this.state.pricing?.paymentMethods ?? []) {\n if (paymentMethod.type !== PAYMENT_TYPES.byCrypto) {\n continue;\n }\n\n const resolved = this.#resolveCryptoPaymentMethodDefaults(paymentMethod);\n if (!resolved) {\n continue;\n }\n\n if (\n resolved.cryptoAuthMethod === cryptoAuthMethod &&\n resolved.products.includes(productType)\n ) {\n matches.push({\n method: paymentMethod,\n explicit: resolved.explicit,\n });\n }\n }\n\n if (matches.length === 0) {\n return undefined;\n }\n\n const explicitMatches = matches.filter((match) => match.explicit);\n const candidates = explicitMatches.length > 0 ? explicitMatches : matches;\n\n if (candidates.length > 1) {\n throw new Error('Multiple matching crypto payment methods found');\n }\n\n return candidates[0].method;\n }\n\n /**\n * Resolves omitted `products` / `cryptoAuthMethod` on a crypto pricing row.\n * Legacy Shield + `erc20_approval` defaults apply only when both fields are\n * absent. If `products` is present, the list must be non-empty and\n * `cryptoAuthMethod` must be explicit; otherwise the row is ignored.\n *\n * @param paymentMethod - The crypto pricing row.\n * @returns Resolved products and auth method, or `undefined` if the row is\n * incomplete.\n */\n #resolveCryptoPaymentMethodDefaults(\n paymentMethod: PricingCryptoPaymentMethod,\n ):\n | {\n products: ProductType[];\n cryptoAuthMethod: CryptoAuthMethod;\n explicit: boolean;\n }\n | undefined {\n const productsPresent = paymentMethod.products !== undefined;\n const authPresent = paymentMethod.cryptoAuthMethod !== undefined;\n\n if (!productsPresent && !authPresent) {\n return {\n products: [PRODUCT_TYPES.SHIELD],\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n explicit: false,\n };\n }\n\n if (!paymentMethod.products?.length || !paymentMethod.cryptoAuthMethod) {\n return undefined;\n }\n\n return {\n products: paymentMethod.products,\n cryptoAuthMethod: paymentMethod.cryptoAuthMethod,\n explicit: true,\n };\n }\n\n /**\n * Whether the given chain supports sponsorship for the product and auth method.\n *\n * @param chainId - The chain ID\n * @param productType - The product type\n * @param cryptoAuthMethod - The crypto authorization method to look up\n * @returns True if the chain row has sponsorship enabled, false if it is explicitly not sponsored\n * @throws If the crypto payment method or chain row is missing from pricing\n */\n #getChainSupportsSponsorship(\n chainId: Hex,\n productType: ProductType,\n cryptoAuthMethod: CryptoAuthMethod,\n ): boolean {\n const cryptoPaymentInfo = this.#findCryptoPaymentMethod(\n productType,\n cryptoAuthMethod,\n );\n if (!cryptoPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n\n const chainPaymentInfo = cryptoPaymentInfo.chains?.find(\n (chain) => chain.chainId === chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n return Boolean(chainPaymentInfo.isSponsorshipSupported);\n }\n\n /**\n * Determines whether two trialed products arrays are equal by comparing all products in the arrays.\n *\n * @param oldTrialedProducts - The first trialed products array to compare.\n * @param newTrialedProducts - The second trialed products array to compare.\n * @returns True if the trialed products arrays are equal, false otherwise.\n */\n #areTrialedProductsEqual(\n oldTrialedProducts: ProductType[],\n newTrialedProducts: ProductType[],\n ): boolean {\n return (\n oldTrialedProducts.length === newTrialedProducts?.length &&\n oldTrialedProducts.every((product) =>\n newTrialedProducts?.includes(product),\n )\n );\n }\n\n /**\n * Compares product entitlement maps without treating object key order as a\n * change. Insertion-order-sensitive `JSON.stringify` can otherwise treat an\n * equivalent API payload as different and trigger `performSignOut`.\n *\n * @param oldProductEntitlements - Stored product entitlements.\n * @param newProductEntitlements - Freshly fetched product entitlements.\n * @returns True if the maps are equal regardless of key order.\n */\n #areProductEntitlementsEqual(\n oldProductEntitlements?: ProductEntitlements,\n newProductEntitlements?: ProductEntitlements,\n ): boolean {\n return deepEqual(\n oldProductEntitlements ?? {},\n newProductEntitlements ?? {},\n );\n }\n\n /**\n * Determines whether two subscription arrays are equal by comparing all properties\n * of each subscription in the arrays.\n *\n * @param oldSubs - The first subscription array to compare.\n * @param newSubs - The second subscription array to compare.\n * @returns True if the subscription arrays are equal, false otherwise.\n */\n #areSubscriptionsEqual(\n oldSubs: Subscription[],\n newSubs: Subscription[],\n ): boolean {\n // Check if arrays have different lengths\n if (oldSubs.length !== newSubs.length) {\n return false;\n }\n\n // Sort both arrays by id to ensure consistent comparison\n const sortedOldSubs = [...oldSubs].sort((a, b) => a.id.localeCompare(b.id));\n const sortedNewSubs = [...newSubs].sort((a, b) => a.id.localeCompare(b.id));\n\n // Check if all subscriptions are equal\n return sortedOldSubs.every((oldSub, index) => {\n const newSub = sortedNewSubs[index];\n return this.#isSubscriptionEqual(oldSub, newSub);\n });\n }\n\n #isSubscriptionEqual(oldSub?: Subscription, newSub?: Subscription): boolean {\n // not equal if one is undefined and the other is defined\n if (!oldSub || !newSub) {\n if (!oldSub && !newSub) {\n return true;\n }\n return false;\n }\n\n return (\n this.#stringifySubscription(oldSub) ===\n this.#stringifySubscription(newSub)\n );\n }\n\n #stringifySubscription(subscription: Subscription): string {\n const subsWithSortedProducts = {\n ...subscription,\n // order the products by name\n products: [...subscription.products].sort((a, b) =>\n a.name.localeCompare(b.name),\n ),\n };\n\n return JSON.stringify(subsWithSortedProducts);\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionController.js","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAG/E,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,SAAS,MAAM,iBAAiB,CAAC;AAExC,OAAO,EACL,4BAA4B,EAC5B,cAAc,EACd,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,yCAAyC,GAC1C,MAAM,gBAAgB,CAAC;AAC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ACvB,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;gBACvB,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,OAAO,CACL,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,CACpC,CAAC;IACJ,CAAC;IAED,sBAAsB,CAAC,YAA0B;QAC/C,MAAM,sBAAsB,GAAG;YAC7B,GAAG,YAAY;YACf,6BAA6B;YAC7B,QAAQ,EAAE,CAAC,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACjD,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAC7B;SACF,CAAC;QAEF,OAAO,IAAI,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import type {\n StateMetadata,\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport type { GeolocationControllerGetGeolocationDataAction } from '@metamask/geolocation-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport type { SeedlessOnboardingControllerGetIsUserAuthenticatedAction } from '@metamask/seedless-onboarding-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\nimport deepEqual from 'fast-deep-equal';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n controllerName,\n DEFAULT_POLLING_INTERVAL,\n REFUND_ELIGIBLE_COUNTRIES,\n SubscriptionControllerErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from './constants.js';\nimport { createModuleLogger, projectLogger } from './logger.js';\nimport type { SubscriptionControllerMethodActions } from './SubscriptionController-method-action-types.js';\nimport type {\n SubscriptionServiceAssignUserToCohortAction,\n SubscriptionServiceCancelSubscriptionAction,\n SubscriptionServiceGetBillingPortalUrlAction,\n SubscriptionServiceGetBenefitsAction,\n SubscriptionServiceGetPricingAction,\n SubscriptionServiceGetSubscriptionsAction,\n SubscriptionServiceGetSubscriptionsEligibilitiesAction,\n SubscriptionServiceLinkRewardsAction,\n SubscriptionServiceStartSubscriptionWithCardAction,\n SubscriptionServiceStartSubscriptionWithCryptoAction,\n SubscriptionServiceSubmitSponsorshipIntentsAction,\n SubscriptionServiceSubmitUserEventAction,\n SubscriptionServiceUnCancelSubscriptionAction,\n SubscriptionServiceUpdatePaymentMethodCardAction,\n SubscriptionServiceUpdatePaymentMethodCryptoAction,\n} from './SubscriptionService-method-action-types.js';\nimport {\n CRYPTO_AUTH_METHODS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\nimport type {\n AssignCohortRequest,\n BillingPortalResponse,\n CryptoAuthMethod,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n GetSubscriptionsEligibilitiesRequest,\n GetSubscriptionsResponse,\n ProductPrice,\n SubscriptionEligibility,\n StartCryptoSubscriptionRequest,\n SubmitSubscriptionCryptoApprovalRequest,\n SubmitUserEventRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodOpts,\n CachedLastSelectedPaymentMethod,\n CacheLastSelectedPaymentMethodRequest,\n SubmitSponsorshipIntentsMethodParams,\n RecurringInterval,\n SubscriptionStatus,\n LinkRewardsRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionResponse,\n CancelSubscriptionRequest,\n PricingCryptoPaymentMethod,\n SubscriptionBenefitsResponse,\n SubscriptionBenefitsState,\n} from './types.js';\nimport type {\n PricingResponse,\n ProductType,\n ProductEntitlements,\n StartSubscriptionRequest,\n Subscription,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, controllerName);\n\nexport type SubscriptionControllerState = {\n customerId?: string;\n trialedProducts: ProductType[];\n subscriptions: Subscription[];\n productEntitlements?: ProductEntitlements;\n pricing?: PricingResponse;\n benefits?: SubscriptionBenefitsState;\n /** The last subscription that user has subscribed to if any. */\n lastSubscription?: Subscription;\n /** The reward account ID if user has linked rewards to the subscription. */\n rewardAccountId?: CaipAccountId;\n /**\n * The last selected payment method for the user.\n * This is used to display the last selected payment method in the UI.\n * This state is also meant to be used internally to track the last selected payment method for the user. (e.g. for crypto subscriptions)\n */\n lastSelectedPaymentMethod?: Partial<\n Record<ProductType, CachedLastSelectedPaymentMethod>\n >;\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerMethodActions;\n\ntype AllowedActions =\n | SubscriptionServiceGetPricingAction\n | SubscriptionServiceGetSubscriptionsAction\n | SubscriptionServiceGetBenefitsAction\n | SubscriptionServiceGetSubscriptionsEligibilitiesAction\n | SubscriptionServiceCancelSubscriptionAction\n | SubscriptionServiceUnCancelSubscriptionAction\n | SubscriptionServiceStartSubscriptionWithCardAction\n | SubscriptionServiceStartSubscriptionWithCryptoAction\n | SubscriptionServiceUpdatePaymentMethodCardAction\n | SubscriptionServiceUpdatePaymentMethodCryptoAction\n | SubscriptionServiceGetBillingPortalUrlAction\n | SubscriptionServiceSubmitSponsorshipIntentsAction\n | SubscriptionServiceSubmitUserEventAction\n | SubscriptionServiceAssignUserToCohortAction\n | SubscriptionServiceLinkRewardsAction\n | AuthenticationController.AuthenticationControllerPerformSignOutAction\n | SeedlessOnboardingControllerGetIsUserAuthenticatedAction\n | GeolocationControllerGetGeolocationDataAction;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\ntype AllowedEvents = never;\n\n// Messenger\nexport type SubscriptionControllerMessenger = Messenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Polling interval to use for the subscription controller.\n *\n * @default 5 minutes.\n */\n pollingInterval?: number;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n trialedProducts: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n productEntitlements: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n lastSubscription: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n customerId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n rewardAccountId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n trialedProducts: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n pricing: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n benefits: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n lastSelectedPaymentMethod: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n };\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getPricing',\n 'getSubscriptions',\n 'getBenefits',\n 'getSubscriptionByProduct',\n 'isUserEligibleForTrial',\n 'getSubscriptionsEligibilities',\n 'cancelSubscription',\n 'unCancelSubscription',\n 'startSubscriptionWithCard',\n 'startSubscriptionWithCrypto',\n 'stopAllPolling',\n 'submitSubscriptionCryptoApproval',\n 'getCryptoApproveTransactionParams',\n 'updatePaymentMethod',\n 'getBillingPortalUrl',\n 'cacheLastSelectedPaymentMethod',\n 'clearLastSelectedPaymentMethod',\n 'submitSponsorshipIntents',\n 'submitUserEvent',\n 'assignUserToCohort',\n 'linkRewards',\n 'getTokenApproveAmount',\n 'getTokenMinimumBalanceAmount',\n 'clearState',\n 'triggerAccessTokenRefresh',\n] as const;\n\nexport class SubscriptionController extends StaticIntervalPollingController()<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.pollingInterval - The polling interval to use for the subscription controller.\n */\n constructor(options: SubscriptionControllerOptions) {\n const {\n messenger,\n state,\n pollingInterval = DEFAULT_POLLING_INTERVAL,\n } = options;\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.setIntervalLength(pollingInterval);\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n const pricing = await this.messenger.call('SubscriptionService:getPricing');\n this.update((state) => {\n state.pricing = pricing;\n });\n return pricing;\n }\n\n async getSubscriptions(): Promise<Subscription[]> {\n return await this.#getSubscriptions();\n }\n\n async #getSubscriptions({\n refreshBenefits = true,\n }: { refreshBenefits?: boolean } = {}): Promise<Subscription[]> {\n const currentSubscriptions = this.state.subscriptions;\n const currentTrialedProducts = this.state.trialedProducts;\n const currentCustomerId = this.state.customerId;\n const currentLastSubscription = this.state.lastSubscription;\n const currentRewardAccountId = this.state.rewardAccountId;\n const currentProductEntitlements = this.state.productEntitlements;\n const currentSubscriptionState: GetSubscriptionsResponse = {\n customerId: currentCustomerId,\n subscriptions: currentSubscriptions,\n trialedProducts: currentTrialedProducts,\n lastSubscription: currentLastSubscription,\n rewardAccountId: currentRewardAccountId,\n productEntitlements: currentProductEntitlements,\n };\n\n const newSubscriptionState = await this.messenger.call(\n 'SubscriptionService:getSubscriptions',\n );\n\n this.#updateSubscriptionStateIfChanged(\n currentSubscriptionState,\n newSubscriptionState,\n );\n\n await this.#refreshBenefitsIfActive(refreshBenefits);\n\n return newSubscriptionState.subscriptions;\n }\n\n /**\n * Updates the subscription state and refreshes the access token when the\n * fetched subscription state differs from the current state.\n *\n * @param currentState - The subscription state captured before the request.\n * @param newState - The subscription state returned by the service.\n */\n #updateSubscriptionStateIfChanged(\n currentState: GetSubscriptionsResponse,\n newState: GetSubscriptionsResponse,\n ): void {\n const {\n subscriptions: currentSubscriptions,\n trialedProducts: currentTrialedProducts,\n customerId: currentCustomerId,\n lastSubscription: currentLastSubscription,\n rewardAccountId: currentRewardAccountId,\n productEntitlements: currentProductEntitlements,\n } = currentState;\n const {\n customerId: newCustomerId,\n subscriptions: newSubscriptions,\n trialedProducts: newTrialedProducts,\n lastSubscription: newLastSubscription,\n rewardAccountId: newRewardAccountId,\n productEntitlements: newProductEntitlements,\n } = newState;\n\n const areSubscriptionsEqual = this.#areSubscriptionsEqual(\n currentSubscriptions,\n newSubscriptions,\n );\n const areTrialedProductsEqual = this.#areTrialedProductsEqual(\n currentTrialedProducts,\n newTrialedProducts,\n );\n const isLastSubscriptionEqual = this.#isSubscriptionEqual(\n currentLastSubscription,\n newLastSubscription,\n );\n const areCustomerIdsEqual = currentCustomerId === newCustomerId;\n const areRewardAccountIdsEqual =\n currentRewardAccountId === newRewardAccountId;\n const areProductEntitlementsEqual = this.#areProductEntitlementsEqual(\n currentProductEntitlements,\n newProductEntitlements,\n );\n // only update the state if the subscriptions or trialed products are different\n // this prevents unnecessary state updates events, easier for the clients to handle\n\n // Only update the state if any subscription-related field changed. This\n // prevents unnecessary state change events for clients to handle.\n if (\n !areSubscriptionsEqual ||\n !isLastSubscriptionEqual ||\n !areTrialedProductsEqual ||\n !areCustomerIdsEqual ||\n !areRewardAccountIdsEqual ||\n !areProductEntitlementsEqual\n ) {\n this.update((state) => {\n state.subscriptions = newSubscriptions;\n state.customerId = newCustomerId;\n state.trialedProducts = newTrialedProducts;\n state.lastSubscription = newLastSubscription;\n state.rewardAccountId = newRewardAccountId;\n // Omitted entitlements are an empty map so selectors fail closed\n // instead of keeping last-known paid-feature flags.\n state.productEntitlements = newProductEntitlements ?? {};\n });\n // Trigger an access token refresh to ensure the user has the latest\n // access token after a subscription state change.\n this.triggerAccessTokenRefresh();\n }\n }\n\n /**\n * Gets and stores the user's subscription benefits.\n *\n * @returns The benefits response.\n * @throws If the user is not an active Money Account Plus subscriber or is\n * not eligible for benefits.\n */\n async getBenefits(): Promise<SubscriptionBenefitsResponse> {\n this.#assertIsActiveMoneyAccountPlusSubscriber();\n\n const benefits = await this.messenger.call(\n 'SubscriptionService:getBenefits',\n );\n\n // The subscription may have become inactive while the benefits request\n // was in flight. Re-check before persisting the response so stale\n // benefits cannot be restored after entitlement ends.\n this.#assertIsActiveMoneyAccountPlusSubscriber();\n\n this.update((state) => {\n state.benefits = benefits.eligible\n ? {\n billingPeriodId: benefits.billingPeriodId,\n ...benefits.products,\n }\n : undefined;\n });\n\n if (!benefits.eligible) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n\n return benefits;\n }\n\n /**\n * Get the subscription by product.\n *\n * @param productType - The product type.\n * @returns The subscription.\n */\n getSubscriptionByProduct(productType: ProductType): Subscription | undefined {\n return this.state.subscriptions.find((subscription) =>\n subscription.products.some((product) => product.name === productType),\n );\n }\n\n /**\n * Whether the user is eligible to start a trial for the given product.\n *\n * Shield is eligible when the user has not trialed Shield before.\n * Money Account Plus is eligible when the user has not trialed it before\n * and is authenticated with social login. Only an unlocked wallet can\n * subscribe, so `SeedlessOnboardingController:getIsUserAuthenticated` is a\n * sufficient social-login check.\n *\n * @param productType - The product to check.\n * @returns Whether the user is eligible for a trial.\n */\n async isUserEligibleForTrial(productType: ProductType): Promise<boolean> {\n if (this.state.trialedProducts.includes(productType)) {\n return false;\n }\n\n switch (productType) {\n case PRODUCT_TYPES.SHIELD:\n return true;\n case PRODUCT_TYPES.MONEY_ACCOUNT_PLUS:\n return await this.messenger.call(\n 'SeedlessOnboardingController:getIsUserAuthenticated',\n );\n default: {\n // `productType` is `never` here. A new `PRODUCT_TYPES` member fails\n // compilation until this switch handles it.\n const unexpectedProduct: never = productType;\n throw new Error(\n `Unexpected product type: ${String(unexpectedProduct)}`,\n );\n }\n }\n }\n\n /**\n * Get the subscriptions eligibilities.\n *\n * @param request - Optional request object containing user balance to check cohort eligibility.\n * @returns The subscriptions eligibilities.\n */\n async getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]> {\n return await this.messenger.call(\n 'SubscriptionService:getSubscriptionsEligibilities',\n request,\n );\n }\n\n async cancelSubscription(request: CancelSubscriptionRequest): Promise<void> {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const cancelledSubscription = await this.messenger.call(\n 'SubscriptionService:cancelSubscription',\n request,\n );\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...cancelledSubscription }\n : subscription,\n );\n });\n\n try {\n await this.#getSubscriptions();\n } catch (error) {\n log('Failed to refresh subscriptions after cancellation', error);\n\n // Preserve the existing best-effort benefits refresh behavior if the\n // canonical subscription refresh is unavailable.\n await this.#refreshBenefitsIfActive();\n }\n\n this.triggerAccessTokenRefresh();\n }\n\n async unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<void> {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const uncancelledSubscription = await this.messenger.call(\n 'SubscriptionService:unCancelSubscription',\n {\n subscriptionId: request.subscriptionId,\n },\n );\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...uncancelledSubscription }\n : subscription,\n );\n });\n\n await this.#refreshBenefitsIfActive();\n\n this.triggerAccessTokenRefresh();\n }\n\n /**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * `isEligibleForRefund` is sent as provided. When omitted, it is resolved\n * from geolocation (EU/EEA), or `false` if the lookup fails.\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n // get the latest subscriptions state before computing trial eligibility\n await this.getSubscriptions();\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCard',\n {\n ...request,\n isTrialRequested: this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\n ),\n isEligibleForRefund: await this.#getIsEligibleForRefund(\n request.isEligibleForRefund,\n ),\n },\n );\n // note: no need to trigger access token refresh after startSubscriptionWithCard request because this only return stripe checkout session url, subscription not created yet\n\n return response;\n }\n\n /**\n * Starts a crypto-paid subscription for the requested products\n * (e.g. Shield or Money Account Plus). Unlike card checkout, this\n * creates the subscription immediately, so local state is refreshed\n * afterwards.\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * `isEligibleForRefund` is sent as provided. When omitted, it is resolved\n * from geolocation (EU/EEA), or `false` if the lookup fails.\n *\n * @param request - The start crypto subscription request.\n * @returns The start crypto subscription response.\n * @throws If `products` is empty.\n */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n // get the latest subscriptions state before computing trial eligibility\n await this.#getSubscriptions({ refreshBenefits: false });\n this.#assertIsUserNotSubscribed({ products: request.products });\n const isTrialRequested = this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\n );\n if (\n request.assertTrialEligibility &&\n request.isTrialRequested !== isTrialRequested\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.TrialEligibilityChanged,\n );\n }\n const {\n assertTrialEligibility: _assertTrialEligibility,\n ...subscriptionRequest\n } = request;\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCrypto',\n {\n ...subscriptionRequest,\n isTrialRequested,\n isEligibleForRefund: await this.#getIsEligibleForRefund(\n request.isEligibleForRefund,\n ),\n },\n );\n\n // Crypto start creates the subscription immediately (unlike card checkout).\n await this.getSubscriptions();\n\n return response;\n }\n\n /**\n * Submits a Shield ERC-20 crypto approval transaction to start or update a\n * crypto subscription.\n *\n * This handler is Shield / `TransactionType.shieldSubscriptionApprove` only.\n * Delegation-based products (e.g. Money Account) must call\n * `startSubscriptionWithCrypto` instead.\n *\n * @param request - The crypto approval request.\n * @param request.productType - The subscription product. Typed as\n * `typeof PRODUCT_TYPES.SHIELD` only at the moment (future might support more\n * product).\n * @param request.txMeta - The transaction metadata. Must have type\n * `TransactionType.shieldSubscriptionApprove`.\n * @param request.isSponsored - Whether the transaction is sponsored.\n * @param request.rewardAccountId - The account ID of the reward subscription\n * to link.\n * @throws If `productType` is not Shield or `txMeta.type` is not\n * `shieldSubscriptionApprove`.\n * @returns void\n */\n async submitSubscriptionCryptoApproval(\n request: SubmitSubscriptionCryptoApprovalRequest,\n ): Promise<void> {\n const { productType, txMeta, isSponsored, rewardAccountId } = request;\n if (\n // Widen for the runtime guard: JS / unsound callers may still pass a\n // non-Shield product.\n (productType as ProductType) !== PRODUCT_TYPES.SHIELD ||\n txMeta.type !== TransactionType.shieldSubscriptionApprove\n ) {\n throw new Error(\n SubscriptionControllerErrorMessage.CryptoApprovalRequiresShieldApprove,\n );\n }\n\n const { chainId, rawTx } = txMeta;\n if (!chainId || !rawTx) {\n throw new Error('Chain ID or raw transaction not found');\n }\n\n const { pricing, lastSelectedPaymentMethod } = this.state;\n if (!pricing) {\n throw new Error('Subscription pricing not found');\n }\n if (!lastSelectedPaymentMethod) {\n throw new Error('Last selected payment method not found');\n }\n const lastSelectedPaymentMethodForProduct =\n lastSelectedPaymentMethod[productType];\n this.#assertIsPaymentMethodCrypto(lastSelectedPaymentMethodForProduct);\n\n const productPrice = this.#getProductPriceByProductAndPlan(\n productType,\n lastSelectedPaymentMethodForProduct.plan,\n );\n // get the latest subscriptions state before computing trial eligibility\n await this.#getSubscriptions({ refreshBenefits: false });\n const isTrialRequested = this.#getIsTrialRequested(\n [productType],\n lastSelectedPaymentMethodForProduct.plan,\n );\n const currentSubscription = this.getSubscriptionByProduct(productType);\n\n this.#assertValidSubscriptionStateForCryptoApproval({\n productType,\n });\n // if subscription exists, this transaction is for changing payment method\n const isChangePaymentMethod = Boolean(currentSubscription);\n\n if (isChangePaymentMethod) {\n await this.updatePaymentMethod({\n paymentType: PAYMENT_TYPES.byCrypto,\n subscriptionId: (currentSubscription as Subscription).id,\n chainId,\n payerAddress: txMeta.txParams.from as Hex,\n tokenSymbol: lastSelectedPaymentMethodForProduct.paymentTokenSymbol,\n rawTransaction: rawTx as Hex,\n recurringInterval: productPrice.interval,\n billingCycles: productPrice.minBillingCycles,\n });\n } else {\n const params: StartCryptoSubscriptionRequest = {\n products: [productType],\n isTrialRequested,\n recurringInterval: productPrice.interval,\n billingCycles: productPrice.minBillingCycles,\n chainId,\n payerAddress: txMeta.txParams.from as Hex,\n tokenSymbol: lastSelectedPaymentMethodForProduct.paymentTokenSymbol,\n rawTransaction: rawTx as Hex,\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n isSponsored,\n useTestClock: lastSelectedPaymentMethodForProduct.useTestClock,\n rewardAccountId,\n };\n await this.startSubscriptionWithCrypto(params);\n }\n\n // update the subscriptions state after subscription created in server\n await this.#getSubscriptions({ refreshBenefits: false });\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): GetCryptoApproveTransactionResponse {\n const { pricing } = this.state;\n if (!pricing) {\n throw new Error('Subscription pricing not found');\n }\n const product = pricing.products.find(\n (productInfo) => productInfo.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find(\n (productPrice) => productPrice.interval === request.interval,\n );\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = this.#findCryptoPaymentMethod(\n request.productType,\n CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (chain) => chain.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (token) =>\n token.address.toLowerCase() ===\n request.paymentTokenAddress.toLowerCase(),\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount,\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(\n opts: UpdatePaymentMethodOpts,\n ): Promise<UpdatePaymentMethodCardResponse | Subscription[]> {\n if (opts.paymentType === PAYMENT_TYPES.byCard) {\n const { paymentType, ...cardRequest } = opts;\n return await this.messenger.call(\n 'SubscriptionService:updatePaymentMethodCard',\n cardRequest,\n );\n } else if (opts.paymentType === PAYMENT_TYPES.byCrypto) {\n const { paymentType, ...cryptoRequest } = opts;\n await this.messenger.call(\n 'SubscriptionService:updatePaymentMethodCrypto',\n cryptoRequest,\n );\n return await this.getSubscriptions();\n }\n throw new Error('Invalid payment type');\n }\n\n /**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n return await this.messenger.call('SubscriptionService:getBillingPortalUrl');\n }\n\n /**\n * Cache the last selected payment method for a specific product.\n *\n * @param request - The request object.\n * @param request.product - The product to cache the payment method for.\n * @param request.paymentMethod - The payment method to cache.\n * @param request.paymentMethod.type - The type of the payment method.\n * @param request.paymentMethod.paymentTokenAddress - The payment token address.\n * @param request.paymentMethod.plan - The plan of the payment method.\n */\n cacheLastSelectedPaymentMethod(\n request: CacheLastSelectedPaymentMethodRequest,\n ): void {\n const { product, paymentMethod } = request;\n if (\n paymentMethod.type === PAYMENT_TYPES.byCrypto &&\n (!paymentMethod.paymentTokenAddress || !paymentMethod.paymentTokenSymbol)\n ) {\n throw new Error(\n SubscriptionControllerErrorMessage.PaymentTokenAddressAndSymbolRequiredForCrypto,\n );\n }\n\n this.update((state) => {\n state.lastSelectedPaymentMethod = {\n ...state.lastSelectedPaymentMethod,\n [product]: paymentMethod,\n };\n });\n }\n\n /**\n * Clear the last selected payment method for a specific product.\n *\n * @param product - The product to clear the payment method for.\n */\n clearLastSelectedPaymentMethod(product: ProductType): void {\n this.update((state) => {\n if (state.lastSelectedPaymentMethod) {\n const { [product]: _, ...rest } = state.lastSelectedPaymentMethod;\n state.lastSelectedPaymentMethod = rest;\n }\n });\n }\n\n /**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example {\n * address: '0x1234567890123456789012345678901234567890',\n * products: [ProductType.Shield],\n * recurringInterval: RecurringInterval.Month,\n * billingCycles: 1,\n * }\n * @returns resolves to true if the sponsorship is supported and intents were submitted successfully, false if the chain does not support sponsorship or the user has already trialed\n * @throws If the crypto payment method or chain is missing from pricing\n */\n async submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsMethodParams,\n ): Promise<boolean> {\n if (request.products.length === 0) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const selectedPaymentMethod =\n this.state.lastSelectedPaymentMethod?.[request.products[0]];\n this.#assertIsPaymentMethodCrypto(selectedPaymentMethod);\n\n const cryptoAuthMethod =\n selectedPaymentMethod.cryptoAuthMethod ??\n CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n const isEligibleForTrialedSponsorship =\n this.#getIsEligibleForTrialedSponsorship(\n request.chainId,\n request.products,\n cryptoAuthMethod,\n );\n if (!isEligibleForTrialedSponsorship) {\n return false;\n }\n\n const { paymentTokenSymbol, plan } = selectedPaymentMethod;\n const productPrice = this.#getProductPriceByProductAndPlan(\n // we only support one product at a time for now\n request.products[0],\n plan,\n );\n const billingCycles = productPrice.minBillingCycles;\n\n await this.messenger.call('SubscriptionService:submitSponsorshipIntents', {\n ...request,\n paymentTokenSymbol,\n billingCycles,\n recurringInterval: plan,\n });\n return true;\n }\n\n /**\n * Submit a user event from the UI. (e.g. shield modal viewed)\n *\n * @param request - Request object containing the event to submit.\n * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }\n */\n async submitUserEvent(request: SubmitUserEventRequest): Promise<void> {\n await this.messenger.call('SubscriptionService:submitUserEvent', request);\n }\n\n /**\n * Assign user to a cohort.\n *\n * @param request - Request object containing the cohort to assign the user to.\n * @example { cohort: 'post_tx' }\n */\n async assignUserToCohort(request: AssignCohortRequest): Promise<void> {\n await this.messenger.call(\n 'SubscriptionService:assignUserToCohort',\n request,\n );\n }\n\n /**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward subscription ID.\n * @param request.subscriptionId - The ID of the subscription to link rewards to.\n * @param request.rewardAccountId - The account ID of the reward subscription to link to the subscription.\n * @example { subscriptionId: '1234567890', rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns Resolves when the rewards are linked successfully.\n */\n async linkRewards(\n request: LinkRewardsRequest & { subscriptionId: string },\n ): Promise<void> {\n // assert that the user is subscribed to the subscription\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n // link rewards to the subscription\n const response = await this.messenger.call(\n 'SubscriptionService:linkRewards',\n {\n rewardAccountId: request.rewardAccountId,\n },\n );\n if (!response.success) {\n throw new Error(SubscriptionControllerErrorMessage.LinkRewardsFailed);\n }\n }\n\n async _executePoll(): Promise<void> {\n await this.getSubscriptions();\n }\n\n async #refreshBenefitsIfActive(refreshBenefits = true): Promise<void> {\n if (!this.#hasActiveMoneyAccountPlusSubscription()) {\n if (this.state.benefits) {\n this.update((state) => {\n state.benefits = undefined;\n });\n }\n return;\n }\n\n if (!refreshBenefits) {\n return;\n }\n\n try {\n await this.getBenefits();\n } catch (error) {\n log('Failed to refresh subscription benefits', error);\n }\n }\n\n /**\n * Calculate total subscription price amount (approval amount) from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice): string {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount = new BigNumber(price.unitAmount)\n .div(10 ** price.unitDecimals)\n .multipliedBy(price.minBillingCycles)\n .toString();\n return amount;\n }\n\n /**\n * Calculate minimum subscription balance amount from price info\n *\n * @param price - The price info\n * @returns The balance amount\n */\n #getSubscriptionBalanceAmount(price: ProductPrice): string {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount = new BigNumber(price.unitAmount)\n .div(10 ** price.unitDecimals)\n .multipliedBy(price.minBillingCyclesForBalance)\n .toString();\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ): string {\n const conversionRate =\n tokenPaymentInfo.conversionRate?.[\n price.currency as keyof NonNullable<TokenPaymentInfo['conversionRate']>\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // price of the product\n const priceAmount = new BigNumber(this.#getSubscriptionPriceAmount(price));\n\n const tokenDecimal = new BigNumber(10).pow(tokenPaymentInfo.decimals);\n const tokenAmount = priceAmount\n .multipliedBy(tokenDecimal)\n .div(conversionRate);\n return tokenAmount.toFixed(0);\n }\n\n /**\n * Calculate token minimum balance amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token balance amount\n */\n getTokenMinimumBalanceAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ): string {\n const conversionRate =\n tokenPaymentInfo.conversionRate?.[\n price.currency as keyof NonNullable<TokenPaymentInfo['conversionRate']>\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n const balanceAmount = new BigNumber(\n this.#getSubscriptionBalanceAmount(price),\n );\n\n const tokenDecimal = new BigNumber(10).pow(tokenPaymentInfo.decimals);\n const tokenAmount = balanceAmount\n .multipliedBy(tokenDecimal)\n .div(conversionRate);\n return tokenAmount.toFixed(0);\n }\n\n /**\n * Clears the subscription state and resets to default values.\n */\n clearState(): void {\n const defaultState = getDefaultSubscriptionControllerState();\n this.update(() => {\n return defaultState;\n });\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh(): void {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messenger.call('AuthenticationController:performSignOut');\n }\n\n #getProductPriceByProductAndPlan(\n productType: ProductType,\n plan: RecurringInterval,\n ): ProductPrice {\n const { pricing } = this.state;\n const productPricing = pricing?.products.find(\n (product) => product.name === productType,\n );\n const productPrice = productPricing?.prices.find(\n (price) => price.interval === plan,\n );\n if (!productPrice) {\n throw new Error(SubscriptionControllerErrorMessage.ProductPriceNotFound);\n }\n return productPrice;\n }\n\n #assertValidSubscriptionStateForCryptoApproval({\n productType,\n }: {\n productType: ProductType;\n }): void {\n const subscription = this.state.subscriptions.find((sub) =>\n sub.products.some((product) => product.name === productType),\n );\n\n const isValid =\n !subscription ||\n (\n [\n SUBSCRIPTION_STATUSES.awaitingFunds,\n SUBSCRIPTION_STATUSES.pastDue,\n SUBSCRIPTION_STATUSES.unpaid,\n SUBSCRIPTION_STATUSES.paused,\n SUBSCRIPTION_STATUSES.provisional,\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n ] as SubscriptionStatus[]\n ).includes(subscription.status);\n if (!isValid) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionNotValidForCryptoApproval,\n );\n }\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }): void {\n const subscription = this.state.subscriptions.find((sub) =>\n sub.products.some((product) => products.includes(product.name)),\n );\n\n if (\n subscription &&\n ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status)\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n #assertIsActiveMoneyAccountPlusSubscriber(): void {\n if (!this.#hasActiveMoneyAccountPlusSubscription()) {\n if (this.state.benefits) {\n this.update((state) => {\n state.benefits = undefined;\n });\n }\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }): void {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n\n /**\n * Asserts that the value is a valid crypto payment method.\n *\n * After this assert, `cryptoAuthMethod` and `useTestClock` remain optional\n * because persisted cache entries may omit them.\n *\n * @param value - The value to assert.\n * @throws an error if the value is not a valid crypto payment method.\n */\n #assertIsPaymentMethodCrypto(\n value: CachedLastSelectedPaymentMethod | undefined,\n ): asserts value is CachedLastSelectedPaymentMethod & {\n type: typeof PAYMENT_TYPES.byCrypto;\n paymentTokenAddress: Hex;\n paymentTokenSymbol: string;\n } {\n if (\n value?.type !== PAYMENT_TYPES.byCrypto ||\n !value.paymentTokenAddress ||\n !value.paymentTokenSymbol\n ) {\n throw new Error(\n SubscriptionControllerErrorMessage.PaymentMethodNotCrypto,\n );\n }\n }\n\n #hasActiveMoneyAccountPlusSubscription(): boolean {\n return this.state.subscriptions.some(\n (subscription) =>\n subscription.products.some(\n (product) => product.name === PRODUCT_TYPES.MONEY_ACCOUNT_PLUS,\n ) && ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status),\n );\n }\n\n /**\n * Determines if the user is eligible for trialed sponsorship for the given chain and products.\n * The user is eligible if the chain supports sponsorship and the user has not trialed the provided products before.\n *\n * @param chainId - The chain ID\n * @param products - The products to check eligibility for\n * @param cryptoAuthMethod - The crypto authorization method of the selected payment method\n * @returns True if the user is eligible for trialed sponsorship, false otherwise\n */\n #getIsEligibleForTrialedSponsorship(\n chainId: Hex,\n products: ProductType[],\n cryptoAuthMethod: CryptoAuthMethod,\n ): boolean {\n const isSponsorshipSupported = this.#getChainSupportsSponsorship(\n chainId,\n products[0],\n cryptoAuthMethod,\n );\n\n // verify if the user has trialed the provided products before\n const hasTrialedBefore = this.state.trialedProducts.some((product) =>\n products.includes(product),\n );\n\n return isSponsorshipSupported && !hasTrialedBefore;\n }\n\n /**\n * Whether a trial should be requested for the given products and plan.\n * True only when every product has `trialPeriodDays > 0` and has not\n * already been trialed.\n *\n * @param products - The products to check.\n * @param plan - The recurring interval to look up pricing for.\n * @returns Whether a trial should be requested.\n */\n #getIsTrialRequested(\n products: ProductType[],\n plan: RecurringInterval,\n ): boolean {\n return products.every((productType) => {\n if (this.state.trialedProducts.includes(productType)) {\n return false;\n }\n const productPrice = this.#getProductPriceByProductAndPlan(\n productType,\n plan,\n );\n return productPrice.trialPeriodDays > 0;\n });\n }\n\n /**\n * Returns the caller-provided refund eligibility when set. Otherwise\n * resolves it from geolocation (EU/EEA), or `false` if the lookup fails.\n *\n * @param isEligibleForRefund - Caller-provided eligibility, if any.\n * @returns Whether the user is eligible for a refund.\n */\n async #getIsEligibleForRefund(\n isEligibleForRefund?: boolean,\n ): Promise<boolean> {\n if (isEligibleForRefund !== undefined) {\n return isEligibleForRefund;\n }\n\n try {\n const { country } = await this.messenger.call(\n 'GeolocationController:getGeolocationData',\n );\n return (\n country !== null && REFUND_ELIGIBLE_COUNTRIES.has(country.toUpperCase())\n );\n } catch (error) {\n log('Failed to resolve geolocation for refund eligibility', error);\n return false;\n }\n }\n\n #findCryptoPaymentMethod(\n productType: ProductType,\n cryptoAuthMethod: CryptoAuthMethod,\n ): PricingCryptoPaymentMethod | undefined {\n const matches: {\n method: PricingCryptoPaymentMethod;\n explicit: boolean;\n }[] = [];\n\n for (const paymentMethod of this.state.pricing?.paymentMethods ?? []) {\n if (paymentMethod.type !== PAYMENT_TYPES.byCrypto) {\n continue;\n }\n\n const resolved = this.#resolveCryptoPaymentMethodDefaults(paymentMethod);\n if (!resolved) {\n continue;\n }\n\n if (\n resolved.cryptoAuthMethod === cryptoAuthMethod &&\n resolved.products.includes(productType)\n ) {\n matches.push({\n method: paymentMethod,\n explicit: resolved.explicit,\n });\n }\n }\n\n if (matches.length === 0) {\n return undefined;\n }\n\n const explicitMatches = matches.filter((match) => match.explicit);\n const candidates = explicitMatches.length > 0 ? explicitMatches : matches;\n\n if (candidates.length > 1) {\n throw new Error('Multiple matching crypto payment methods found');\n }\n\n return candidates[0].method;\n }\n\n /**\n * Resolves omitted `products` / `cryptoAuthMethod` on a crypto pricing row.\n * Legacy Shield + `erc20_approval` defaults apply only when both fields are\n * absent. If `products` is present, the list must be non-empty and\n * `cryptoAuthMethod` must be explicit; otherwise the row is ignored.\n *\n * @param paymentMethod - The crypto pricing row.\n * @returns Resolved products and auth method, or `undefined` if the row is\n * incomplete.\n */\n #resolveCryptoPaymentMethodDefaults(\n paymentMethod: PricingCryptoPaymentMethod,\n ):\n | {\n products: ProductType[];\n cryptoAuthMethod: CryptoAuthMethod;\n explicit: boolean;\n }\n | undefined {\n const productsPresent = paymentMethod.products !== undefined;\n const authPresent = paymentMethod.cryptoAuthMethod !== undefined;\n\n if (!productsPresent && !authPresent) {\n return {\n products: [PRODUCT_TYPES.SHIELD],\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n explicit: false,\n };\n }\n\n if (!paymentMethod.products?.length || !paymentMethod.cryptoAuthMethod) {\n return undefined;\n }\n\n return {\n products: paymentMethod.products,\n cryptoAuthMethod: paymentMethod.cryptoAuthMethod,\n explicit: true,\n };\n }\n\n /**\n * Whether the given chain supports sponsorship for the product and auth method.\n *\n * @param chainId - The chain ID\n * @param productType - The product type\n * @param cryptoAuthMethod - The crypto authorization method to look up\n * @returns True if the chain row has sponsorship enabled, false if it is explicitly not sponsored\n * @throws If the crypto payment method or chain row is missing from pricing\n */\n #getChainSupportsSponsorship(\n chainId: Hex,\n productType: ProductType,\n cryptoAuthMethod: CryptoAuthMethod,\n ): boolean {\n const cryptoPaymentInfo = this.#findCryptoPaymentMethod(\n productType,\n cryptoAuthMethod,\n );\n if (!cryptoPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n\n const chainPaymentInfo = cryptoPaymentInfo.chains?.find(\n (chain) => chain.chainId === chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n return Boolean(chainPaymentInfo.isSponsorshipSupported);\n }\n\n /**\n * Determines whether two trialed products arrays are equal by comparing all products in the arrays.\n *\n * @param oldTrialedProducts - The first trialed products array to compare.\n * @param newTrialedProducts - The second trialed products array to compare.\n * @returns True if the trialed products arrays are equal, false otherwise.\n */\n #areTrialedProductsEqual(\n oldTrialedProducts: ProductType[],\n newTrialedProducts: ProductType[],\n ): boolean {\n return (\n oldTrialedProducts.length === newTrialedProducts?.length &&\n oldTrialedProducts.every((product) =>\n newTrialedProducts?.includes(product),\n )\n );\n }\n\n /**\n * Compares product entitlement maps without treating object key order as a\n * change. Insertion-order-sensitive `JSON.stringify` can otherwise treat an\n * equivalent API payload as different and trigger `performSignOut`.\n *\n * @param oldProductEntitlements - Stored product entitlements.\n * @param newProductEntitlements - Freshly fetched product entitlements.\n * @returns True if the maps are equal regardless of key order.\n */\n #areProductEntitlementsEqual(\n oldProductEntitlements?: ProductEntitlements,\n newProductEntitlements?: ProductEntitlements,\n ): boolean {\n return deepEqual(\n oldProductEntitlements ?? {},\n newProductEntitlements ?? {},\n );\n }\n\n /**\n * Determines whether two subscription arrays are equal by comparing all properties\n * of each subscription in the arrays.\n *\n * @param oldSubs - The first subscription array to compare.\n * @param newSubs - The second subscription array to compare.\n * @returns True if the subscription arrays are equal, false otherwise.\n */\n #areSubscriptionsEqual(\n oldSubs: Subscription[],\n newSubs: Subscription[],\n ): boolean {\n // Check if arrays have different lengths\n if (oldSubs.length !== newSubs.length) {\n return false;\n }\n\n // Sort both arrays by id to ensure consistent comparison\n const sortedOldSubs = [...oldSubs].sort((a, b) => a.id.localeCompare(b.id));\n const sortedNewSubs = [...newSubs].sort((a, b) => a.id.localeCompare(b.id));\n\n // Check if all subscriptions are equal\n return sortedOldSubs.every((oldSub, index) => {\n const newSub = sortedNewSubs[index];\n return this.#isSubscriptionEqual(oldSub, newSub);\n });\n }\n\n #isSubscriptionEqual(oldSub?: Subscription, newSub?: Subscription): boolean {\n // not equal if one is undefined and the other is defined\n if (!oldSub || !newSub) {\n if (!oldSub && !newSub) {\n return true;\n }\n return false;\n }\n\n return (\n this.#stringifySubscription(oldSub) ===\n this.#stringifySubscription(newSub)\n );\n }\n\n #stringifySubscription(subscription: Subscription): string {\n const subsWithSortedProducts = {\n ...subscription,\n // order the products by name\n products: [...subscription.products].sort((a, b) =>\n a.name.localeCompare(b.name),\n ),\n };\n\n return JSON.stringify(subsWithSortedProducts);\n }\n}\n"]}
@@ -78,5 +78,11 @@ export declare enum SubscriptionDelegationServiceErrorMessage {
78
78
  }
79
79
  export declare const DEFAULT_POLLING_INTERVAL: number;
80
80
  export declare const ACTIVE_SUBSCRIPTION_STATUSES: string[];
81
+ /**
82
+ * ISO 3166-1 alpha-2 country codes eligible for refund (EU 27 + EEA).
83
+ *
84
+ * Used to set `isEligibleForRefund` when starting a subscription.
85
+ */
86
+ export declare const REFUND_ELIGIBLE_COUNTRIES: ReadonlySet<string>;
81
87
  export {};
82
88
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD;;GAEG;AACH,eAAO,MAAM,oBAAoB;aAE/B,aAAa,EAAE,eAAe;aAE9B,kBAAkB,EAAE,oBAAoB;aAExC,wBAAwB,EAAE,0BAA0B;aAEpD,sBAAsB,EAAE,wBAAwB;aAEhD,oBAAoB,EAAE,sBAAsB;aAE5C,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,oBAAY,GAAG;IACb,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,GAAG,QAAQ;CACZ;AAED,KAAK,YAAY,GAAG;IAClB,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAcF;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,YAAY,CAKjD;AAED,oBAAY,kCAAkC;IAC5C,qBAAqB,wDAAmD;IACxE,iBAAiB,oDAA+C;IAChE,yBAAyB,yEAAoE;I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EAAgE;IAClF,8BAA8B,4DAA4D;IAC1F,2BAA2B,8EAA8E;IACzG,4BAA4B,gEAAgE;IAC5F,uBAAuB,sEAAsE;IAC7F,mBAAmB,mFAAmF;IACtG,uBAAuB,+CAA+C;IACtE,0BAA0B,4DAA4D;IACtF,2BAA2B,mFAAmF;IAC9G,aAAa,yEAAyE;IACtF,yBAAyB,2DAA2D;IACpF,uBAAuB,+DAA+D;IACtF,oBAAoB,4CAA4C;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,EAIpC,MAAM,EAAE,CAAC;AAEd;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,EAAE,WAAW,CAAC,MAAM,CAiCxD,CAAC"}
package/dist/constants.js CHANGED
@@ -106,4 +106,43 @@ export const ACTIVE_SUBSCRIPTION_STATUSES = [
106
106
  SUBSCRIPTION_STATUSES.trialing,
107
107
  SUBSCRIPTION_STATUSES.provisional,
108
108
  ];
109
+ /**
110
+ * ISO 3166-1 alpha-2 country codes eligible for refund (EU 27 + EEA).
111
+ *
112
+ * Used to set `isEligibleForRefund` when starting a subscription.
113
+ */
114
+ export const REFUND_ELIGIBLE_COUNTRIES = new Set([
115
+ // EU 27
116
+ 'AT',
117
+ 'BE',
118
+ 'BG',
119
+ 'HR',
120
+ 'CY',
121
+ 'CZ',
122
+ 'DK',
123
+ 'EE',
124
+ 'FI',
125
+ 'FR',
126
+ 'DE',
127
+ 'GR',
128
+ 'HU',
129
+ 'IE',
130
+ 'IT',
131
+ 'LV',
132
+ 'LT',
133
+ 'LU',
134
+ 'MT',
135
+ 'NL',
136
+ 'PL',
137
+ 'PT',
138
+ 'RO',
139
+ 'SK',
140
+ 'SI',
141
+ 'ES',
142
+ 'SE',
143
+ // EEA (non-EU)
144
+ 'IS',
145
+ 'LI',
146
+ 'NO',
147
+ ]);
109
148
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","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":["import { SUBSCRIPTION_STATUSES } from './types.js';\n\nexport const controllerName = 'SubscriptionController';\n\n/**\n * API cancellation reason values and their client-facing text.\n */\nexport const CANCELLATION_REASONS = {\n // Costs more than it's worth\n TOO_EXPENSIVE: 'too_expensive',\n // I wasn't using the benefits\n NOT_USING_BENEFITS: 'not_using_benefits',\n // The benefits weren't what I expected\n BENEFITS_NOT_AS_EXPECTED: 'benefits_not_as_expected',\n // Something didn't work\n SOMETHING_DID_NOT_WORK: 'something_did_not_work',\n // Unhappy with support\n UNHAPPY_WITH_SUPPORT: 'unhappy_with_support',\n // Other\n OTHER: 'other',\n} as const;\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n CryptoApprovalRequiresShieldApprove = `${controllerName} - Crypto approval is only supported for Shield ERC-20 approve transactions`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport enum SubscriptionServiceErrorMessage {\n FailedToGetSubscriptions = 'Failed to get subscriptions',\n FailedToGetBenefits = 'Failed to get benefits',\n FailedToCancelSubscription = 'Failed to cancel subscription',\n FailedToUncancelSubscription = 'Failed to uncancel subscription',\n FailedToStartSubscriptionWithCard = 'Failed to start subscription with card',\n FailedToStartSubscriptionWithCrypto = 'Failed to start subscription with crypto',\n InvalidCryptoAuthCombo = 'Crypto subscription requires exactly one of rawTransaction (erc20_approval) or delegationHash (delegation)',\n FailedToUpdatePaymentMethodCard = 'Failed to update payment method card',\n FailedToUpdatePaymentMethodCrypto = 'Failed to update payment method crypto',\n FailedToGetSubscriptionsEligibilities = 'Failed to get subscriptions eligibilities',\n FailedToSubmitUserEvent = 'Failed to submit user event',\n FailedToAssignUserToCohort = 'Failed to assign user to cohort',\n FailedToSubmitSponsorshipIntents = 'Failed to submit sponsorship intents',\n FailedToLinkRewards = 'Failed to link rewards',\n FailedToGetPricing = 'Failed to get pricing',\n FailedToGetBillingPortalUrl = 'Failed to get billing portal url',\n}\n\nexport enum SubscriptionDelegationServiceErrorMessage {\n InvalidAmount = 'Subscription delegation amount must be a non-negative integer',\n InvalidDecimals = 'Subscription delegation decimals must be a non-negative integer',\n InvalidTrialPeriodDays = 'Subscription delegation trial period days must be a non-negative integer',\n InvalidMinimumFundingCycles = 'Subscription delegation minimum funding cycles must be a positive integer',\n LossyAmountScale = 'Subscription delegation amount cannot be scaled to token decimals without remainder',\n UnsupportedRecurringInterval = 'Unsupported subscription recurring interval',\n UnsupportedProduct = 'Subscription delegation is only supported for Money Account',\n MissingMoneyAccountVaultConfig = 'Money Account vault configuration is missing or invalid',\n DelegationContractsNotFound = 'Subscription delegation contracts were not found for the configured chain',\n PricingConfigurationNotFound = 'Subscription delegation pricing configuration was not found',\n InvalidRecipientAddress = 'Subscription delegation recipient must be a valid 20-byte address',\n InsufficientBalance = 'Money Account balance is insufficient for the subscription funding requirement',\n ChompRejectedDelegation = 'CHOMP rejected the subscription delegation',\n ChompMissingDelegationHash = 'CHOMP verify response did not include a delegation hash',\n ChompDelegationHashMismatch = 'CHOMP verify response delegation hash does not match the locally computed hash',\n ChainMismatch = 'Subscription delegation chain does not match the Money Account chain',\n ReusableDelegationInvalid = 'Reusable subscription delegation is missing or invalid',\n TrialEligibilityChanged = 'Subscription trial eligibility changed after authorization',\n ChompIntentNotActive = 'CHOMP subscription intent is not active',\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEnD,MAAM,CAAC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,6BAA6B;IAC7B,aAAa,EAAE,eAAe;IAC9B,8BAA8B;IAC9B,kBAAkB,EAAE,oBAAoB;IACxC,uCAAuC;IACvC,wBAAwB,EAAE,0BAA0B;IACpD,wBAAwB;IACxB,sBAAsB,EAAE,wBAAwB;IAChD,uBAAuB;IACvB,oBAAoB,EAAE,sBAAsB;IAC5C,QAAQ;IACR,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,MAAM,CAAN,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,KAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;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AA4E,CAAA;IAC5E,+HAAkF,CAAA;IAClF,uIAA0F,CAAA;IAC1F,sJAAyG,CAAA;IACzG,yIAA4F,CAAA;IAC5F,0IAA6F,CAAA;IAC7F,mJAAsG,CAAA;IACtG,mHAAsE,CAAA;IACtE,mIAAsF,CAAA;IACtF,2JAA8G,CAAA;IAC9G,mIAAsF,CAAA;IACtF,iIAAoF,CAAA;IACpF,mIAAsF,CAAA;IACtF,6GAAgE,CAAA;AAClE,CAAC,EApBW,yCAAyC,KAAzC,yCAAyC,QAoBpD;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC,YAAY;AAEpE,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC1C,qBAAqB,CAAC,MAAM;IAC5B,qBAAqB,CAAC,QAAQ;IAC9B,qBAAqB,CAAC,WAAW;CACtB,CAAC;AAEd;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAwB,IAAI,GAAG,CAAC;IACpE,QAAQ;IACR,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,eAAe;IACf,IAAI;IACJ,IAAI;IACJ,IAAI;CACL,CAAC,CAAC","sourcesContent":["import { SUBSCRIPTION_STATUSES } from './types.js';\n\nexport const controllerName = 'SubscriptionController';\n\n/**\n * API cancellation reason values and their client-facing text.\n */\nexport const CANCELLATION_REASONS = {\n // Costs more than it's worth\n TOO_EXPENSIVE: 'too_expensive',\n // I wasn't using the benefits\n NOT_USING_BENEFITS: 'not_using_benefits',\n // The benefits weren't what I expected\n BENEFITS_NOT_AS_EXPECTED: 'benefits_not_as_expected',\n // Something didn't work\n SOMETHING_DID_NOT_WORK: 'something_did_not_work',\n // Unhappy with support\n UNHAPPY_WITH_SUPPORT: 'unhappy_with_support',\n // Other\n OTHER: 'other',\n} as const;\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n CryptoApprovalRequiresShieldApprove = `${controllerName} - Crypto approval is only supported for Shield ERC-20 approve transactions`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport enum SubscriptionServiceErrorMessage {\n FailedToGetSubscriptions = 'Failed to get subscriptions',\n FailedToGetBenefits = 'Failed to get benefits',\n FailedToCancelSubscription = 'Failed to cancel subscription',\n FailedToUncancelSubscription = 'Failed to uncancel subscription',\n FailedToStartSubscriptionWithCard = 'Failed to start subscription with card',\n FailedToStartSubscriptionWithCrypto = 'Failed to start subscription with crypto',\n InvalidCryptoAuthCombo = 'Crypto subscription requires exactly one of rawTransaction (erc20_approval) or delegationHash (delegation)',\n FailedToUpdatePaymentMethodCard = 'Failed to update payment method card',\n FailedToUpdatePaymentMethodCrypto = 'Failed to update payment method crypto',\n FailedToGetSubscriptionsEligibilities = 'Failed to get subscriptions eligibilities',\n FailedToSubmitUserEvent = 'Failed to submit user event',\n FailedToAssignUserToCohort = 'Failed to assign user to cohort',\n FailedToSubmitSponsorshipIntents = 'Failed to submit sponsorship intents',\n FailedToLinkRewards = 'Failed to link rewards',\n FailedToGetPricing = 'Failed to get pricing',\n FailedToGetBillingPortalUrl = 'Failed to get billing portal url',\n}\n\nexport enum SubscriptionDelegationServiceErrorMessage {\n InvalidAmount = 'Subscription delegation amount must be a non-negative integer',\n InvalidDecimals = 'Subscription delegation decimals must be a non-negative integer',\n InvalidTrialPeriodDays = 'Subscription delegation trial period days must be a non-negative integer',\n InvalidMinimumFundingCycles = 'Subscription delegation minimum funding cycles must be a positive integer',\n LossyAmountScale = 'Subscription delegation amount cannot be scaled to token decimals without remainder',\n UnsupportedRecurringInterval = 'Unsupported subscription recurring interval',\n UnsupportedProduct = 'Subscription delegation is only supported for Money Account',\n MissingMoneyAccountVaultConfig = 'Money Account vault configuration is missing or invalid',\n DelegationContractsNotFound = 'Subscription delegation contracts were not found for the configured chain',\n PricingConfigurationNotFound = 'Subscription delegation pricing configuration was not found',\n InvalidRecipientAddress = 'Subscription delegation recipient must be a valid 20-byte address',\n InsufficientBalance = 'Money Account balance is insufficient for the subscription funding requirement',\n ChompRejectedDelegation = 'CHOMP rejected the subscription delegation',\n ChompMissingDelegationHash = 'CHOMP verify response did not include a delegation hash',\n ChompDelegationHashMismatch = 'CHOMP verify response delegation hash does not match the locally computed hash',\n ChainMismatch = 'Subscription delegation chain does not match the Money Account chain',\n ReusableDelegationInvalid = 'Reusable subscription delegation is missing or invalid',\n TrialEligibilityChanged = 'Subscription trial eligibility changed after authorization',\n ChompIntentNotActive = 'CHOMP subscription intent is not active',\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n\n/**\n * ISO 3166-1 alpha-2 country codes eligible for refund (EU 27 + EEA).\n *\n * Used to set `isEligibleForRefund` when starting a subscription.\n */\nexport const REFUND_ELIGIBLE_COUNTRIES: ReadonlySet<string> = new Set([\n // EU 27\n 'AT',\n 'BE',\n 'BG',\n 'HR',\n 'CY',\n 'CZ',\n 'DK',\n 'EE',\n 'FI',\n 'FR',\n 'DE',\n 'GR',\n 'HU',\n 'IE',\n 'IT',\n 'LV',\n 'LT',\n 'LU',\n 'MT',\n 'NL',\n 'PL',\n 'PT',\n 'RO',\n 'SK',\n 'SI',\n 'ES',\n 'SE',\n // EEA (non-EU)\n 'IS',\n 'LI',\n 'NO',\n]);\n"]}
package/dist/types.d.ts CHANGED
@@ -254,6 +254,13 @@ export type StartSubscriptionRequest = {
254
254
  successUrl?: string;
255
255
  cancelUrl?: string;
256
256
  useTestClock?: boolean;
257
+ /**
258
+ * Whether the user is eligible for a refund (e.g. EU/EEA withdrawal rights).
259
+ *
260
+ * When provided, this value is sent as-is and the geolocation check is
261
+ * skipped. When omitted, the controller resolves it from geolocation.
262
+ */
263
+ isEligibleForRefund?: boolean;
257
264
  /**
258
265
  * Optional CAIP account ID of the rewards account to opt in alongside this
259
266
  * subscription. Required when the user wants to link rewards during
@@ -285,6 +292,13 @@ type StartCryptoSubscriptionRequestBase = {
285
292
  assertTrialEligibility?: boolean;
286
293
  isSponsored?: boolean;
287
294
  useTestClock?: boolean;
295
+ /**
296
+ * Whether the user is eligible for a refund (e.g. EU/EEA withdrawal rights).
297
+ *
298
+ * When provided, this value is sent as-is and the geolocation check is
299
+ * skipped. When omitted, the controller resolves it from geolocation.
300
+ */
301
+ isEligibleForRefund?: boolean;
288
302
  /**
289
303
  * Optional CAIP account ID of the rewards account to opt in alongside this
290
304
  * subscription. Required when the user wants to link rewards during
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAE3D;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa;IACxB;;OAEG;aACH,MAAM,EAAE,QAAQ;IAChB;;OAEG;aACH,kBAAkB,EAAE,oBAAoB;CAChC,CAAC;AAEX,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,OAAO,aAAa,CAAC,CAAC;AAE7E,eAAO,MAAM,mBAAmB;aAC9B,aAAa,EAAE,eAAe;aAC9B,cAAc,EAAE,gBAAgB;aAChC,aAAa,EAAE,eAAe;aAC9B,UAAU,EAAE,YAAY;CAChB,CAAC;AAEX,MAAM,MAAM,mBAAmB,GAC7B,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,OAAO,mBAAmB,CAAC,CAAC;AAEjE,MAAM,MAAM,wBAAwB,GAAG,MAAM,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;AAE5E,eAAO,MAAM,aAAa;aACxB,WAAW,EAAE,aAAa;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C5C,kBAAkB,EAAE,oBAAoB;IACxC,yBAAyB,EAAE,2BAA2B;IACtD,qBAAqB,EAAE,uBAAuB;CACtC,CAAC;AAKX,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,CAAC,EAAE,GAAG;IACN,CAAC,EAAE,GAAG;CACE,CAAC;AAkTX;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,SAAS;CACV,CAAC;AAmCX;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAuB;IAEvB,OAAQ,KAA+B,CAAC,iBAAiB,KAAK,SAAS,CAAC;AAC1E,CAAC;AA6GD,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,OAAO,EAAE,SAAS;IAClB,WAAW,EAAE,aAAa;CAClB,CAAC;AAIX,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,UAAU,EAAE,MAAM;IAClB,aAAa,EAAE,SAAS;IACxB,aAAa,EAAE,SAAS;IACxB,eAAe,EAAE,WAAW;IAC5B,iBAAiB,EAAE,aAAa;IAChC,aAAa,EAAE,KAAK;CACZ,CAAC;AAsBX,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,sBAAsB,EAAE,2BAA2B;IACnD,oBAAoB,EAAE,wBAAwB;CACtC,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\n\nimport type { CANCELLATION_REASONS } from './constants.js';\n\n/**\n * Error response from the Subscription API.\n */\nexport type SubscriptionApiError = {\n errorCode?: string;\n message?: string;\n statusCode?: number;\n};\n\n/**\n * Supported subscription products.\n */\nexport const PRODUCT_TYPES = {\n /**\n * MetaMask Shield.\n */\n SHIELD: 'shield',\n /**\n * Money Account Plus (delegation-based crypto billing).\n */\n MONEY_ACCOUNT_PLUS: 'money_account_plus',\n} as const;\n\nexport type ProductType = (typeof PRODUCT_TYPES)[keyof typeof PRODUCT_TYPES];\n\nexport const MoneyAccountFeature = {\n SwapFeeWaiver: 'swapFeeWaiver',\n PerpsFeeWaiver: 'perpsFeeWaiver',\n PredictFreeTx: 'predictFreeTx',\n PremiumApy: 'premiumApy',\n} as const;\n\nexport type MoneyAccountFeature =\n (typeof MoneyAccountFeature)[keyof typeof MoneyAccountFeature];\n\nexport type MoneyAccountEntitlements = Record<MoneyAccountFeature, boolean>;\n\nexport const ShieldFeature = {\n ShieldClaim: 'shieldClaim',\n PrioritySupport: 'prioritySupport',\n} as const;\n\nexport type ShieldFeature = (typeof ShieldFeature)[keyof typeof ShieldFeature];\n\nexport type ShieldEntitlements = Record<ShieldFeature, boolean>;\n\nexport type MoneyAccountPlusClaim = {\n plan: string;\n entitlements: MoneyAccountEntitlements;\n};\n\nexport type ProductEntitlements = {\n [PRODUCT_TYPES.SHIELD]?: {\n entitlements: ShieldEntitlements;\n };\n [PRODUCT_TYPES.MONEY_ACCOUNT_PLUS]?: MoneyAccountPlusClaim;\n};\n\nexport type ProductEntitlementFeatureMap = {\n [PRODUCT_TYPES.SHIELD]: ShieldFeature;\n [PRODUCT_TYPES.MONEY_ACCOUNT_PLUS]: MoneyAccountFeature;\n};\n\n/**\n * How a crypto subscription is authorized.\n *\n * Use `erc20_approval` with `rawTransaction` (e.g. Shield). Use `delegation`\n * with `delegationHash` (e.g. Money Account Plus).\n */\nexport const CRYPTO_AUTH_METHODS = {\n /**\n * User signs an ERC-20 approve transaction.\n */\n ERC20_APPROVAL: 'erc20_approval',\n /**\n * User authorizes via a stored delegation hash.\n */\n DELEGATION: 'delegation',\n} as const;\n\nexport type CryptoAuthMethod =\n (typeof CRYPTO_AUTH_METHODS)[keyof typeof CRYPTO_AUTH_METHODS];\n\nexport const PAYMENT_TYPES = {\n byCard: 'card',\n byCrypto: 'crypto',\n} as const;\n\nexport type PaymentType = (typeof PAYMENT_TYPES)[keyof typeof PAYMENT_TYPES];\n\nexport const RECURRING_INTERVALS = {\n month: 'month',\n year: 'year',\n} as const;\n\nexport type RecurringInterval =\n (typeof RECURRING_INTERVALS)[keyof typeof RECURRING_INTERVALS];\n\nexport const SUBSCRIPTION_STATUSES = {\n // Initial states\n incomplete: 'incomplete',\n incompleteExpired: 'incomplete_expired',\n /** Crypto subscription created, waiting for the payer to fund the first invoice. */\n awaitingFunds: 'awaiting_funds',\n // Active states\n provisional: 'provisional',\n trialing: 'trialing',\n active: 'active',\n // Payment issues\n pastDue: 'past_due',\n unpaid: 'unpaid',\n // Cancelled states\n canceled: 'canceled',\n // Paused states\n paused: 'paused',\n} as const;\n\nexport type SubscriptionStatus =\n (typeof SUBSCRIPTION_STATUSES)[keyof typeof SUBSCRIPTION_STATUSES];\n\nexport const INVOICE_PAYMENT_STATUSES = {\n PROCESSING: 'PROCESSING',\n SUCCEEDED: 'SUCCEEDED',\n FAILED: 'FAILED',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\nexport type InvoicePaymentStatus =\n (typeof INVOICE_PAYMENT_STATUSES)[keyof typeof INVOICE_PAYMENT_STATUSES];\n\nexport const CANCEL_TYPES = {\n ALLOWED_IMMEDIATE: 'allowed_immediate',\n ALLOWED_AT_PERIOD_END: 'allowed_at_period_end',\n NOT_ALLOWED: 'not_allowed',\n NOT_ALLOWED_PENDING_VERIFICATION: 'not_allowed_pending_verification',\n} as const;\n\nexport type CancelType = (typeof CANCEL_TYPES)[keyof typeof CANCEL_TYPES];\n\nexport type CancellationReasonCode =\n (typeof CANCELLATION_REASONS)[keyof typeof CANCELLATION_REASONS];\n\nexport const CRYPTO_PAYMENT_METHOD_ERRORS = {\n APPROVAL_TRANSACTION_TOO_OLD: 'approval_transaction_too_old',\n APPROVAL_TRANSACTION_REVERTED: 'approval_transaction_reverted',\n APPROVAL_TRANSACTION_MAX_VERIFICATION_ATTEMPTS_REACHED:\n 'approval_transaction_max_verification_attempts_reached',\n INSUFFICIENT_BALANCE: 'insufficient_balance',\n INSUFFICIENT_ALLOWANCE: 'insufficient_allowance',\n} as const;\n\nexport type CryptoPaymentMethodError =\n (typeof CRYPTO_PAYMENT_METHOD_ERRORS)[keyof typeof CRYPTO_PAYMENT_METHOD_ERRORS];\n\n/**\n * Errors returned by the Subscription API after crypto payment execution.\n *\n * These are distinct from {@link CRYPTO_PAYMENT_METHOD_ERRORS}, which describe\n * approval/payment-method failures.\n */\nexport const CRYPTO_PAYMENT_ERRORS = {\n INSUFFICIENT_BALANCE: 'insufficient_balance',\n INSUFFICIENT_ALLOWANCE: 'insufficient_allowance',\n EXCEEDS_DELEGATION_ALLOWANCE: 'exceeds_delegation_allowance',\n DELEGATION_NOT_FOUND: 'delegation_not_found',\n DELEGATION_REVOKED: 'delegation_revoked',\n RECIPIENT_NOT_ALLOWLISTED: 'recipient_not_allowlisted',\n INTERNAL_SERVER_ERROR: 'internal_server_error',\n} as const;\n\nexport type CryptoPaymentError =\n (typeof CRYPTO_PAYMENT_ERRORS)[keyof typeof CRYPTO_PAYMENT_ERRORS];\n\nexport const MODAL_TYPE = {\n A: 'A',\n B: 'B',\n} as const;\n\nexport type ModalType = (typeof MODAL_TYPE)[keyof typeof MODAL_TYPE];\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n currency: Currency;\n unitAmount: number;\n unitDecimals: number;\n};\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart?: string; // ISO 8601\n currentPeriodEnd?: string; // ISO 8601\n /** is subscription scheduled for cancellation */\n cancelAtPeriodEnd?: boolean;\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n trialPeriodDays?: number;\n trialStart?: string; // ISO 8601\n trialEnd?: string; // ISO 8601\n /** Crypto payment only: next billing cycle date (e.g after 12 months) */\n endDate?: string; // ISO 8601\n /** The date the subscription was canceled. */\n canceledAt?: string; // ISO 8601\n /** The cancellation type indicating what cancellation options are available for this subscription. */\n cancelType?: CancelType;\n /** The date the subscription was marked as inactive (paused/past_due/canceled). */\n inactiveAt?: string; // ISO 8601\n /** Whether the user is eligible for support features (priority support and filing claims). True for active subscriptions and inactive subscriptions within grace period. */\n isEligibleForSupport?: boolean;\n billingCycles?: number;\n /** The most recent invoice associated with the subscription. */\n lastInvoice?: SubscriptionInvoice;\n};\n\nexport type SubscriptionInvoice = {\n id: string;\n status: InvoicePaymentStatus;\n errorCode?: CryptoPaymentError;\n updatedAt?: string; // ISO 8601\n};\n\nexport type SubscriptionCardPaymentMethod = {\n type: Extract<PaymentType, 'card'>;\n card: {\n brand: string;\n /** display brand account for dual brand card */\n displayBrand?: string;\n last4: string;\n };\n};\n\nexport type SubscriptionCryptoPaymentMethod = {\n type: Extract<PaymentType, 'crypto'>;\n crypto: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n error?: CryptoPaymentMethodError;\n };\n};\n\nexport type SubscriptionPaymentMethod =\n | SubscriptionCardPaymentMethod\n | SubscriptionCryptoPaymentMethod;\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n productEntitlements?: ProductEntitlements;\n /** The last subscription that user has subscribed to if any. */\n lastSubscription?: Subscription;\n /** The reward account ID if user has linked rewards to the subscription. */\n rewardAccountId?: CaipAccountId;\n};\n\n/**\n * Benefits available to a subscription user.\n */\nexport type SwapsBenefitUsage = {\n feeBips: string | null;\n capMicroUsd?: number;\n consumedMicroUsd?: number;\n remainingMicroUsd: number | null;\n exhausted: boolean;\n};\n\nexport type PerpsBenefitUsage = {\n builderFeeBips: string | null;\n builderCode: string | null;\n capMicroUsd?: number;\n consumedMicroUsd?: number;\n remainingMicroUsd: number | null;\n exhausted: boolean;\n};\n\nexport type PredictBenefitUsage = {\n builderCode: string | null;\n capTxCount?: number;\n consumedTxCount?: number;\n remainingTxCount: number | null;\n exhausted: boolean;\n};\n\ntype SubscriptionBenefitsProducts = {\n swaps: SwapsBenefitUsage;\n perps: PerpsBenefitUsage;\n predict: PredictBenefitUsage;\n};\n\nexport type SubscriptionBenefitsResponse = {\n eligible: boolean;\n billingPeriodId: string | null;\n products: SubscriptionBenefitsProducts;\n};\n\n/**\n * Benefits state exposed to the UI.\n */\nexport type SubscriptionBenefitsState = SubscriptionBenefitsProducts & {\n billingPeriodId: string | null;\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n successUrl?: string;\n cancelUrl?: string;\n useTestClock?: boolean;\n\n /**\n * Optional CAIP account ID of the rewards account to opt in alongside this\n * subscription. Required when the user wants to link rewards during\n * subscription creation.\n *\n * @example {\n * rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890',\n * }\n */\n rewardAccountId?: CaipAccountId;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\ntype StartCryptoSubscriptionRequestBase = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n /**\n * Reject if authoritative trial eligibility changed since authorization.\n */\n assertTrialEligibility?: boolean;\n isSponsored?: boolean;\n useTestClock?: boolean;\n /**\n * Optional CAIP account ID of the rewards account to opt in alongside this\n * subscription. Required when the user wants to link rewards during\n * subscription creation.\n *\n * @example {\n * rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890',\n * }\n */\n rewardAccountId?: CaipAccountId;\n};\n\n/**\n * ERC-20 approval crypto subscription request (e.g. Shield).\n *\n * `cryptoAuthMethod` defaults to `CRYPTO_AUTH_METHODS.ERC20_APPROVAL` when\n * omitted.\n */\nexport type StartErc20CryptoSubscriptionRequest =\n StartCryptoSubscriptionRequestBase & {\n cryptoAuthMethod?: typeof CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n rawTransaction: Hex;\n delegationHash?: never;\n };\n\n/**\n * Delegation-based crypto subscription request (e.g. Money Account Plus).\n */\nexport type StartDelegationCryptoSubscriptionRequest =\n StartCryptoSubscriptionRequestBase & {\n cryptoAuthMethod: typeof CRYPTO_AUTH_METHODS.DELEGATION;\n delegationHash: Hex;\n rawTransaction?: never;\n };\n\n/**\n * Request to start a crypto subscription.\n *\n * Discriminated union of ERC-20 approval vs delegation. Provide\n * `rawTransaction` for ERC-20 approval (the default when `cryptoAuthMethod` is\n * omitted), or `delegationHash` with `cryptoAuthMethod: 'delegation'`.\n * Combining or omitting both is a type error, and is also rejected at runtime\n * by `startSubscriptionWithCrypto`.\n */\nexport type StartCryptoSubscriptionRequest =\n | StartErc20CryptoSubscriptionRequest\n | StartDelegationCryptoSubscriptionRequest;\n\n/**\n * Response of `POST /subscriptions/crypto`.\n *\n * Unlike card checkout, a crypto start creates the subscription immediately,\n * so the Subscription API returns the created {@link Subscription} itself.\n */\nexport type StartCryptoSubscriptionResponse = Subscription;\n\n/**\n * General response type for the subscription API requests\n * which doesn't require any specific response data.\n */\nexport type SubscriptionApiGeneralResponse = {\n /**\n * Whether the request was successful.\n */\n success: boolean;\n /**\n * The message of the response.\n */\n message?: string;\n};\n\nexport type CancelSubscriptionRequest = {\n subscriptionId: string;\n /** Whether to cancel at the end of the current period */\n cancelAtPeriodEnd?: boolean;\n /** Stable reason code for the cancellation. */\n cancellationReason?: CancellationReasonCode;\n /** Optional free-text feedback for the cancellation. */\n cancellationFeedback?: string;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n /** min billing cycles for approval */\n minBillingCycles: number;\n /** min billing cycles for account balance check */\n minBillingCyclesForBalance: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\ntype TokenPaymentInfoBase = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate?: {\n usd: string;\n };\n /**\n * Source tokens that can be converted into this settlement token.\n */\n sources?: TokenPaymentInfo[];\n};\n\n/**\n * Named vault a vault-share settlement token belongs to, e.g. `base` or\n * `premium`. Distinguishes which vault to withdraw from.\n *\n * Deliberately a plain `string` rather than a union: the set of vaults is\n * server-driven and grows without a client release, so narrowing it here would\n * make the pricing response fail validation the first time the API adds a\n * vault. Compare against `VAULT_NAMES` instead of raw literals, and always\n * handle the unknown case.\n */\nexport type VaultName = string;\n\n/**\n * The vault names known at the time of writing. Not exhaustive — see\n * {@link VaultName}.\n */\nexport const VAULT_NAMES = {\n base: 'base',\n premium: 'premium',\n} as const;\n\n/**\n * Spot (non-vault) settlement token. Priced via `conversionRate` when provided.\n * Neither `accountantAddress` nor `vault` is present on this variant.\n */\nexport type SpotTokenPaymentInfo = TokenPaymentInfoBase;\n\n/**\n * Yield-bearing vault share priced via an accountant rate.\n */\nexport type VaultTokenPaymentInfo = TokenPaymentInfoBase & {\n /**\n * Veda accountant address used to value this vault share. Every vault has\n * its own accountant, so this is present on every vault-share token — which\n * is what makes it the discriminant for this variant.\n */\n accountantAddress: Hex;\n /**\n * Named vault this token is a share of. Sent only for vault-share tokens.\n */\n vault?: VaultName;\n};\n\n/**\n * A settlement token in a pricing chain. Discriminated by the presence of\n * `accountantAddress`: vault shares carry it (and may carry `vault`), spot\n * tokens carry neither.\n *\n * The API previously sent an explicit `isVaultShare` boolean. It no longer\n * does, so do not reintroduce a dependency on it — use\n * {@link isVaultShareToken}.\n */\nexport type TokenPaymentInfo = SpotTokenPaymentInfo | VaultTokenPaymentInfo;\n\n/**\n * Whether a settlement token is a yield-bearing vault share, which must be\n * valued through its accountant rate rather than at face value.\n *\n * @param token - The settlement token to check.\n * @returns True if the token is a vault share.\n */\nexport function isVaultShareToken(\n token: TokenPaymentInfo,\n): token is VaultTokenPaymentInfo {\n return (token as VaultTokenPaymentInfo).accountantAddress !== undefined;\n}\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n /**\n * Delegate address clients authorize when using the delegation auth method.\n */\n delegateAddress?: Hex;\n tokens: TokenPaymentInfo[];\n /**\n * Whether the chain supports sponsorship for the trialed subscription approval transaction.\n * This is used to determine if the user can be sponsored for the gas fees for the trialed subscription approval transaction.\n */\n isSponsorshipSupported?: boolean;\n};\n\nexport type PricingCardPaymentMethod = {\n type: Extract<PaymentType, 'card'>;\n /**\n * Products that support this payment method.\n */\n products?: ProductType[];\n};\n\nexport type PricingCryptoPaymentMethod = {\n type: Extract<PaymentType, 'crypto'>;\n /**\n * Crypto authorization method. Omitted together with `products` on persisted\n * pre-multi-product pricing rows; those rows are treated as Shield + `erc20_approval`.\n * If `products` is set, this field must be explicit.\n */\n cryptoAuthMethod?: CryptoAuthMethod;\n /**\n * Products that support this payment method. Omitted together with\n * `cryptoAuthMethod` on persisted pre-multi-product pricing rows (treated as Shield).\n * If present, must be non-empty and paired with an explicit `cryptoAuthMethod`.\n */\n products?: ProductType[];\n chains?: ChainPaymentInfo[];\n};\n\n/**\n * A pricing payment-method row. Discriminated by `type`: card rows have no\n * crypto fields; crypto rows may include `cryptoAuthMethod` and `chains`.\n */\nexport type PricingPaymentMethod =\n | PricingCardPaymentMethod\n | PricingCryptoPaymentMethod;\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\n/**\n * Request to submit a Shield ERC-20 crypto approval transaction.\n */\nexport type SubmitSubscriptionCryptoApprovalRequest = {\n /**\n * The subscription product. Typed as `typeof PRODUCT_TYPES.SHIELD` only at\n * the moment (future might support more product).\n */\n productType: typeof PRODUCT_TYPES.SHIELD;\n /**\n * The transaction metadata. Must have type\n * `TransactionType.shieldSubscriptionApprove`.\n */\n txMeta: TransactionMeta;\n /**\n * Whether the transaction is sponsored.\n */\n isSponsored?: boolean;\n /**\n * The account ID of the reward subscription to link.\n */\n rewardAccountId?: CaipAccountId;\n};\n\nexport const COHORT_NAMES = {\n POST_TX: 'post_tx',\n WALLET_HOME: 'wallet_home',\n} as const;\n\nexport type CohortName = (typeof COHORT_NAMES)[keyof typeof COHORT_NAMES];\n\nexport const BALANCE_CATEGORIES = {\n RANGE_0_99: '0-99',\n RANGE_100_999: '100-999',\n RANGE_1K_9_9K: '1k-9.9k',\n RANGE_10K_99_9K: '10k-99.9k',\n RANGE_100K_999_9K: '100k-999.9k',\n RANGE_1M_PLUS: '1M+',\n} as const;\n\nexport type BalanceCategory =\n (typeof BALANCE_CATEGORIES)[keyof typeof BALANCE_CATEGORIES];\n\nexport type Cohort = {\n cohort: string;\n eligibilityRate: number; // 0-1 probability of being assigned to this cohort\n priority: number; // lower number = higher priority\n eligible: boolean;\n};\n\nexport type SubscriptionEligibility = {\n product: ProductType;\n canSubscribe: boolean;\n canViewEntryModal: boolean;\n modalType?: ModalType;\n cohorts: Cohort[];\n assignedCohort: string | null;\n hasAssignedCohortExpired: boolean;\n};\n\nexport const SubscriptionUserEvent = {\n ShieldEntryModalViewed: 'shield_entry_modal_viewed',\n ShieldCohortAssigned: 'shield_cohort_assigned',\n} as const;\n\nexport type SubscriptionUserEventType =\n (typeof SubscriptionUserEvent)[keyof typeof SubscriptionUserEvent];\n\nexport type SubmitUserEventRequest = {\n event: SubscriptionUserEventType;\n cohort?: string;\n};\n\nexport type AssignCohortRequest = {\n cohort: string;\n};\n\nexport type GetSubscriptionsEligibilitiesRequest = {\n balanceCategory?: BalanceCategory;\n};\n\n/**\n * Request object for submitting sponsorship intents.\n */\nexport type SubmitSponsorshipIntentsRequest = {\n chainId: Hex;\n address: Hex;\n products: ProductType[];\n paymentTokenSymbol: string;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n\nexport type SubmitSponsorshipIntentsMethodParams = Pick<\n SubmitSponsorshipIntentsRequest,\n 'chainId' | 'address' | 'products'\n>;\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n getBenefits(): Promise<SubscriptionBenefitsResponse>;\n cancelSubscription(request: CancelSubscriptionRequest): Promise<Subscription>;\n unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<Subscription>;\n /**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getBillingPortalUrl(): Promise<BillingPortalResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<UpdatePaymentMethodCardResponse>;\n updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void>;\n getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]>;\n submitUserEvent(request: SubmitUserEventRequest): Promise<void>;\n assignUserToCohort(request: AssignCohortRequest): Promise<void>;\n\n /**\n * Link rewards to a subscription.\n */\n linkRewards(\n request: LinkRewardsRequest,\n ): Promise<SubscriptionApiGeneralResponse>;\n\n /**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example {\n * address: '0x1234567890123456789012345678901234567890',\n * products: [ProductType.Shield],\n * recurringInterval: RecurringInterval.Month,\n * billingCycles: 1,\n * }\n */\n submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsRequest,\n ): Promise<void>;\n};\n\nexport type UpdatePaymentMethodOpts =\n | ({\n paymentType: Extract<PaymentType, 'card'>;\n } & UpdatePaymentMethodCardRequest)\n | ({\n paymentType: Extract<PaymentType, 'crypto'>;\n } & UpdatePaymentMethodCryptoRequest);\n\nexport type UpdatePaymentMethodCardRequest = {\n /**\n * Subscription ID\n */\n subscriptionId: string;\n\n /**\n * Recurring interval\n */\n recurringInterval: RecurringInterval;\n successUrl?: string;\n cancelUrl?: string;\n};\n\nexport type UpdatePaymentMethodCardResponse = {\n redirectUrl: string;\n};\n\ntype UpdatePaymentMethodCryptoRequestBase = {\n subscriptionId: string;\n chainId: Hex;\n payerAddress: Hex;\n tokenSymbol: string;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n\n/**\n * ERC-20 approval crypto payment-method update request.\n *\n * `rawTransaction` may be omitted when retrying after a balance top-up.\n */\nexport type UpdateErc20PaymentMethodCryptoRequest =\n UpdatePaymentMethodCryptoRequestBase & {\n cryptoAuthMethod?: typeof CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n /**\n * The raw transaction to pay for the subscription.\n */\n rawTransaction?: Hex;\n delegationHash?: never;\n };\n\n/**\n * Delegation crypto payment-method update request used to rotate an active\n * subscription to a replacement delegation.\n */\nexport type UpdateDelegationPaymentMethodCryptoRequest =\n UpdatePaymentMethodCryptoRequestBase & {\n cryptoAuthMethod: typeof CRYPTO_AUTH_METHODS.DELEGATION;\n delegationHash: Hex;\n rawTransaction?: never;\n };\n\n/**\n * Request to update a subscription's crypto payment method.\n *\n * Provide `rawTransaction` for the existing ERC-20 approval path, or provide\n * `cryptoAuthMethod: 'delegation'` and `delegationHash` to rotate a delegation.\n */\nexport type UpdatePaymentMethodCryptoRequest =\n | UpdateErc20PaymentMethodCryptoRequest\n | UpdateDelegationPaymentMethodCryptoRequest;\n\nexport type BillingPortalResponse = {\n url: string;\n};\n\n/**\n * The cached result of last selected payment methods for the user.\n * These details are being cached to be used internally to track the last selected payment method for the user. (e.g. for crypto subscriptions)\n */\nexport type CachedLastSelectedPaymentMethod = {\n type: PaymentType;\n paymentTokenAddress?: Hex;\n paymentTokenSymbol?: string;\n plan: RecurringInterval;\n useTestClock?: boolean;\n /**\n * Crypto authorization method. Omitted on persisted cache entries written\n * before this field existed; treat as `erc20_approval` when missing.\n */\n cryptoAuthMethod?: CryptoAuthMethod;\n};\n\n/**\n * Request to cache the last selected payment method for a product.\n */\nexport type CacheLastSelectedPaymentMethodRequest = {\n /**\n * The product to cache the payment method for.\n */\n product: ProductType;\n /**\n * The payment method to cache.\n */\n paymentMethod: CachedLastSelectedPaymentMethod;\n};\n\n/**\n * Request object for linking rewards to a subscription.\n */\nexport type LinkRewardsRequest = {\n /**\n * The ID of the reward subscription to be linked to the subscription.\n *\n * @example {\n * rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890',\n * }\n */\n rewardAccountId: CaipAccountId;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAcA;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B;;OAEG;IACH,MAAM,EAAE,QAAQ;IAChB;;OAEG;IACH,kBAAkB,EAAE,oBAAoB;CAChC,CAAC;AAIX,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,aAAa,EAAE,eAAe;IAC9B,cAAc,EAAE,gBAAgB;IAChC,aAAa,EAAE,eAAe;IAC9B,UAAU,EAAE,YAAY;CAChB,CAAC;AAOX,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,WAAW,EAAE,aAAa;IAC1B,eAAe,EAAE,iBAAiB;CAC1B,CAAC;AAuBX;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC;;OAEG;IACH,cAAc,EAAE,gBAAgB;IAChC;;OAEG;IACH,UAAU,EAAE,YAA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4BAA4B,EAAE,8BAA8B;IAC5D,oBAAoB,EAAE,sBAAsB;IAC5C,kBAAkB,EAAE,oBAAoB;IACxC,yBAAyB,EAAE,2BAA2B;IACtD,qBAAqB,EAAE,uBAAuB;CACtC,CAAC;AAKX,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,CAAC,EAAE,GAAG;IACN,CAAC,EAAE,GAAG;CACE,CAAC;AAmUX;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,SAAS;CACV,CAAC;AAmCX;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAuB;IAEvB,OAAQ,KAA+B,CAAC,iBAAiB,KAAK,SAAS,CAAC;AAC1E,CAAC;AA6GD,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,OAAO,EAAE,SAAS;IAClB,WAAW,EAAE,aAAa;CAClB,CAAC;AAIX,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,UAAU,EAAE,MAAM;IAClB,aAAa,EAAE,SAAS;IACxB,aAAa,EAAE,SAAS;IACxB,eAAe,EAAE,WAAW;IAC5B,iBAAiB,EAAE,aAAa;IAChC,aAAa,EAAE,KAAK;CACZ,CAAC;AAsBX,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,sBAAsB,EAAE,2BAA2B;IACnD,oBAAoB,EAAE,wBAAwB;CACtC,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\n\nimport type { CANCELLATION_REASONS } from './constants.js';\n\n/**\n * Error response from the Subscription API.\n */\nexport type SubscriptionApiError = {\n errorCode?: string;\n message?: string;\n statusCode?: number;\n};\n\n/**\n * Supported subscription products.\n */\nexport const PRODUCT_TYPES = {\n /**\n * MetaMask Shield.\n */\n SHIELD: 'shield',\n /**\n * Money Account Plus (delegation-based crypto billing).\n */\n MONEY_ACCOUNT_PLUS: 'money_account_plus',\n} as const;\n\nexport type ProductType = (typeof PRODUCT_TYPES)[keyof typeof PRODUCT_TYPES];\n\nexport const MoneyAccountFeature = {\n SwapFeeWaiver: 'swapFeeWaiver',\n PerpsFeeWaiver: 'perpsFeeWaiver',\n PredictFreeTx: 'predictFreeTx',\n PremiumApy: 'premiumApy',\n} as const;\n\nexport type MoneyAccountFeature =\n (typeof MoneyAccountFeature)[keyof typeof MoneyAccountFeature];\n\nexport type MoneyAccountEntitlements = Record<MoneyAccountFeature, boolean>;\n\nexport const ShieldFeature = {\n ShieldClaim: 'shieldClaim',\n PrioritySupport: 'prioritySupport',\n} as const;\n\nexport type ShieldFeature = (typeof ShieldFeature)[keyof typeof ShieldFeature];\n\nexport type ShieldEntitlements = Record<ShieldFeature, boolean>;\n\nexport type MoneyAccountPlusClaim = {\n plan: string;\n entitlements: MoneyAccountEntitlements;\n};\n\nexport type ProductEntitlements = {\n [PRODUCT_TYPES.SHIELD]?: {\n entitlements: ShieldEntitlements;\n };\n [PRODUCT_TYPES.MONEY_ACCOUNT_PLUS]?: MoneyAccountPlusClaim;\n};\n\nexport type ProductEntitlementFeatureMap = {\n [PRODUCT_TYPES.SHIELD]: ShieldFeature;\n [PRODUCT_TYPES.MONEY_ACCOUNT_PLUS]: MoneyAccountFeature;\n};\n\n/**\n * How a crypto subscription is authorized.\n *\n * Use `erc20_approval` with `rawTransaction` (e.g. Shield). Use `delegation`\n * with `delegationHash` (e.g. Money Account Plus).\n */\nexport const CRYPTO_AUTH_METHODS = {\n /**\n * User signs an ERC-20 approve transaction.\n */\n ERC20_APPROVAL: 'erc20_approval',\n /**\n * User authorizes via a stored delegation hash.\n */\n DELEGATION: 'delegation',\n} as const;\n\nexport type CryptoAuthMethod =\n (typeof CRYPTO_AUTH_METHODS)[keyof typeof CRYPTO_AUTH_METHODS];\n\nexport const PAYMENT_TYPES = {\n byCard: 'card',\n byCrypto: 'crypto',\n} as const;\n\nexport type PaymentType = (typeof PAYMENT_TYPES)[keyof typeof PAYMENT_TYPES];\n\nexport const RECURRING_INTERVALS = {\n month: 'month',\n year: 'year',\n} as const;\n\nexport type RecurringInterval =\n (typeof RECURRING_INTERVALS)[keyof typeof RECURRING_INTERVALS];\n\nexport const SUBSCRIPTION_STATUSES = {\n // Initial states\n incomplete: 'incomplete',\n incompleteExpired: 'incomplete_expired',\n /** Crypto subscription created, waiting for the payer to fund the first invoice. */\n awaitingFunds: 'awaiting_funds',\n // Active states\n provisional: 'provisional',\n trialing: 'trialing',\n active: 'active',\n // Payment issues\n pastDue: 'past_due',\n unpaid: 'unpaid',\n // Cancelled states\n canceled: 'canceled',\n // Paused states\n paused: 'paused',\n} as const;\n\nexport type SubscriptionStatus =\n (typeof SUBSCRIPTION_STATUSES)[keyof typeof SUBSCRIPTION_STATUSES];\n\nexport const INVOICE_PAYMENT_STATUSES = {\n PROCESSING: 'PROCESSING',\n SUCCEEDED: 'SUCCEEDED',\n FAILED: 'FAILED',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\nexport type InvoicePaymentStatus =\n (typeof INVOICE_PAYMENT_STATUSES)[keyof typeof INVOICE_PAYMENT_STATUSES];\n\nexport const CANCEL_TYPES = {\n ALLOWED_IMMEDIATE: 'allowed_immediate',\n ALLOWED_AT_PERIOD_END: 'allowed_at_period_end',\n NOT_ALLOWED: 'not_allowed',\n NOT_ALLOWED_PENDING_VERIFICATION: 'not_allowed_pending_verification',\n} as const;\n\nexport type CancelType = (typeof CANCEL_TYPES)[keyof typeof CANCEL_TYPES];\n\nexport type CancellationReasonCode =\n (typeof CANCELLATION_REASONS)[keyof typeof CANCELLATION_REASONS];\n\nexport const CRYPTO_PAYMENT_METHOD_ERRORS = {\n APPROVAL_TRANSACTION_TOO_OLD: 'approval_transaction_too_old',\n APPROVAL_TRANSACTION_REVERTED: 'approval_transaction_reverted',\n APPROVAL_TRANSACTION_MAX_VERIFICATION_ATTEMPTS_REACHED:\n 'approval_transaction_max_verification_attempts_reached',\n INSUFFICIENT_BALANCE: 'insufficient_balance',\n INSUFFICIENT_ALLOWANCE: 'insufficient_allowance',\n} as const;\n\nexport type CryptoPaymentMethodError =\n (typeof CRYPTO_PAYMENT_METHOD_ERRORS)[keyof typeof CRYPTO_PAYMENT_METHOD_ERRORS];\n\n/**\n * Errors returned by the Subscription API after crypto payment execution.\n *\n * These are distinct from {@link CRYPTO_PAYMENT_METHOD_ERRORS}, which describe\n * approval/payment-method failures.\n */\nexport const CRYPTO_PAYMENT_ERRORS = {\n INSUFFICIENT_BALANCE: 'insufficient_balance',\n INSUFFICIENT_ALLOWANCE: 'insufficient_allowance',\n EXCEEDS_DELEGATION_ALLOWANCE: 'exceeds_delegation_allowance',\n DELEGATION_NOT_FOUND: 'delegation_not_found',\n DELEGATION_REVOKED: 'delegation_revoked',\n RECIPIENT_NOT_ALLOWLISTED: 'recipient_not_allowlisted',\n INTERNAL_SERVER_ERROR: 'internal_server_error',\n} as const;\n\nexport type CryptoPaymentError =\n (typeof CRYPTO_PAYMENT_ERRORS)[keyof typeof CRYPTO_PAYMENT_ERRORS];\n\nexport const MODAL_TYPE = {\n A: 'A',\n B: 'B',\n} as const;\n\nexport type ModalType = (typeof MODAL_TYPE)[keyof typeof MODAL_TYPE];\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n currency: Currency;\n unitAmount: number;\n unitDecimals: number;\n};\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart?: string; // ISO 8601\n currentPeriodEnd?: string; // ISO 8601\n /** is subscription scheduled for cancellation */\n cancelAtPeriodEnd?: boolean;\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n trialPeriodDays?: number;\n trialStart?: string; // ISO 8601\n trialEnd?: string; // ISO 8601\n /** Crypto payment only: next billing cycle date (e.g after 12 months) */\n endDate?: string; // ISO 8601\n /** The date the subscription was canceled. */\n canceledAt?: string; // ISO 8601\n /** The cancellation type indicating what cancellation options are available for this subscription. */\n cancelType?: CancelType;\n /** The date the subscription was marked as inactive (paused/past_due/canceled). */\n inactiveAt?: string; // ISO 8601\n /** Whether the user is eligible for support features (priority support and filing claims). True for active subscriptions and inactive subscriptions within grace period. */\n isEligibleForSupport?: boolean;\n billingCycles?: number;\n /** The most recent invoice associated with the subscription. */\n lastInvoice?: SubscriptionInvoice;\n};\n\nexport type SubscriptionInvoice = {\n id: string;\n status: InvoicePaymentStatus;\n errorCode?: CryptoPaymentError;\n updatedAt?: string; // ISO 8601\n};\n\nexport type SubscriptionCardPaymentMethod = {\n type: Extract<PaymentType, 'card'>;\n card: {\n brand: string;\n /** display brand account for dual brand card */\n displayBrand?: string;\n last4: string;\n };\n};\n\nexport type SubscriptionCryptoPaymentMethod = {\n type: Extract<PaymentType, 'crypto'>;\n crypto: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n error?: CryptoPaymentMethodError;\n };\n};\n\nexport type SubscriptionPaymentMethod =\n | SubscriptionCardPaymentMethod\n | SubscriptionCryptoPaymentMethod;\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n productEntitlements?: ProductEntitlements;\n /** The last subscription that user has subscribed to if any. */\n lastSubscription?: Subscription;\n /** The reward account ID if user has linked rewards to the subscription. */\n rewardAccountId?: CaipAccountId;\n};\n\n/**\n * Benefits available to a subscription user.\n */\nexport type SwapsBenefitUsage = {\n feeBips: string | null;\n capMicroUsd?: number;\n consumedMicroUsd?: number;\n remainingMicroUsd: number | null;\n exhausted: boolean;\n};\n\nexport type PerpsBenefitUsage = {\n builderFeeBips: string | null;\n builderCode: string | null;\n capMicroUsd?: number;\n consumedMicroUsd?: number;\n remainingMicroUsd: number | null;\n exhausted: boolean;\n};\n\nexport type PredictBenefitUsage = {\n builderCode: string | null;\n capTxCount?: number;\n consumedTxCount?: number;\n remainingTxCount: number | null;\n exhausted: boolean;\n};\n\ntype SubscriptionBenefitsProducts = {\n swaps: SwapsBenefitUsage;\n perps: PerpsBenefitUsage;\n predict: PredictBenefitUsage;\n};\n\nexport type SubscriptionBenefitsResponse = {\n eligible: boolean;\n billingPeriodId: string | null;\n products: SubscriptionBenefitsProducts;\n};\n\n/**\n * Benefits state exposed to the UI.\n */\nexport type SubscriptionBenefitsState = SubscriptionBenefitsProducts & {\n billingPeriodId: string | null;\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n successUrl?: string;\n cancelUrl?: string;\n useTestClock?: boolean;\n\n /**\n * Whether the user is eligible for a refund (e.g. EU/EEA withdrawal rights).\n *\n * When provided, this value is sent as-is and the geolocation check is\n * skipped. When omitted, the controller resolves it from geolocation.\n */\n isEligibleForRefund?: boolean;\n\n /**\n * Optional CAIP account ID of the rewards account to opt in alongside this\n * subscription. Required when the user wants to link rewards during\n * subscription creation.\n *\n * @example {\n * rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890',\n * }\n */\n rewardAccountId?: CaipAccountId;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\ntype StartCryptoSubscriptionRequestBase = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n /**\n * Reject if authoritative trial eligibility changed since authorization.\n */\n assertTrialEligibility?: boolean;\n isSponsored?: boolean;\n useTestClock?: boolean;\n\n /**\n * Whether the user is eligible for a refund (e.g. EU/EEA withdrawal rights).\n *\n * When provided, this value is sent as-is and the geolocation check is\n * skipped. When omitted, the controller resolves it from geolocation.\n */\n isEligibleForRefund?: boolean;\n\n /**\n * Optional CAIP account ID of the rewards account to opt in alongside this\n * subscription. Required when the user wants to link rewards during\n * subscription creation.\n *\n * @example {\n * rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890',\n * }\n */\n rewardAccountId?: CaipAccountId;\n};\n\n/**\n * ERC-20 approval crypto subscription request (e.g. Shield).\n *\n * `cryptoAuthMethod` defaults to `CRYPTO_AUTH_METHODS.ERC20_APPROVAL` when\n * omitted.\n */\nexport type StartErc20CryptoSubscriptionRequest =\n StartCryptoSubscriptionRequestBase & {\n cryptoAuthMethod?: typeof CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n rawTransaction: Hex;\n delegationHash?: never;\n };\n\n/**\n * Delegation-based crypto subscription request (e.g. Money Account Plus).\n */\nexport type StartDelegationCryptoSubscriptionRequest =\n StartCryptoSubscriptionRequestBase & {\n cryptoAuthMethod: typeof CRYPTO_AUTH_METHODS.DELEGATION;\n delegationHash: Hex;\n rawTransaction?: never;\n };\n\n/**\n * Request to start a crypto subscription.\n *\n * Discriminated union of ERC-20 approval vs delegation. Provide\n * `rawTransaction` for ERC-20 approval (the default when `cryptoAuthMethod` is\n * omitted), or `delegationHash` with `cryptoAuthMethod: 'delegation'`.\n * Combining or omitting both is a type error, and is also rejected at runtime\n * by `startSubscriptionWithCrypto`.\n */\nexport type StartCryptoSubscriptionRequest =\n | StartErc20CryptoSubscriptionRequest\n | StartDelegationCryptoSubscriptionRequest;\n\n/**\n * Response of `POST /subscriptions/crypto`.\n *\n * Unlike card checkout, a crypto start creates the subscription immediately,\n * so the Subscription API returns the created {@link Subscription} itself.\n */\nexport type StartCryptoSubscriptionResponse = Subscription;\n\n/**\n * General response type for the subscription API requests\n * which doesn't require any specific response data.\n */\nexport type SubscriptionApiGeneralResponse = {\n /**\n * Whether the request was successful.\n */\n success: boolean;\n /**\n * The message of the response.\n */\n message?: string;\n};\n\nexport type CancelSubscriptionRequest = {\n subscriptionId: string;\n /** Whether to cancel at the end of the current period */\n cancelAtPeriodEnd?: boolean;\n /** Stable reason code for the cancellation. */\n cancellationReason?: CancellationReasonCode;\n /** Optional free-text feedback for the cancellation. */\n cancellationFeedback?: string;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n /** min billing cycles for approval */\n minBillingCycles: number;\n /** min billing cycles for account balance check */\n minBillingCyclesForBalance: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\ntype TokenPaymentInfoBase = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate?: {\n usd: string;\n };\n /**\n * Source tokens that can be converted into this settlement token.\n */\n sources?: TokenPaymentInfo[];\n};\n\n/**\n * Named vault a vault-share settlement token belongs to, e.g. `base` or\n * `premium`. Distinguishes which vault to withdraw from.\n *\n * Deliberately a plain `string` rather than a union: the set of vaults is\n * server-driven and grows without a client release, so narrowing it here would\n * make the pricing response fail validation the first time the API adds a\n * vault. Compare against `VAULT_NAMES` instead of raw literals, and always\n * handle the unknown case.\n */\nexport type VaultName = string;\n\n/**\n * The vault names known at the time of writing. Not exhaustive — see\n * {@link VaultName}.\n */\nexport const VAULT_NAMES = {\n base: 'base',\n premium: 'premium',\n} as const;\n\n/**\n * Spot (non-vault) settlement token. Priced via `conversionRate` when provided.\n * Neither `accountantAddress` nor `vault` is present on this variant.\n */\nexport type SpotTokenPaymentInfo = TokenPaymentInfoBase;\n\n/**\n * Yield-bearing vault share priced via an accountant rate.\n */\nexport type VaultTokenPaymentInfo = TokenPaymentInfoBase & {\n /**\n * Veda accountant address used to value this vault share. Every vault has\n * its own accountant, so this is present on every vault-share token — which\n * is what makes it the discriminant for this variant.\n */\n accountantAddress: Hex;\n /**\n * Named vault this token is a share of. Sent only for vault-share tokens.\n */\n vault?: VaultName;\n};\n\n/**\n * A settlement token in a pricing chain. Discriminated by the presence of\n * `accountantAddress`: vault shares carry it (and may carry `vault`), spot\n * tokens carry neither.\n *\n * The API previously sent an explicit `isVaultShare` boolean. It no longer\n * does, so do not reintroduce a dependency on it — use\n * {@link isVaultShareToken}.\n */\nexport type TokenPaymentInfo = SpotTokenPaymentInfo | VaultTokenPaymentInfo;\n\n/**\n * Whether a settlement token is a yield-bearing vault share, which must be\n * valued through its accountant rate rather than at face value.\n *\n * @param token - The settlement token to check.\n * @returns True if the token is a vault share.\n */\nexport function isVaultShareToken(\n token: TokenPaymentInfo,\n): token is VaultTokenPaymentInfo {\n return (token as VaultTokenPaymentInfo).accountantAddress !== undefined;\n}\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n /**\n * Delegate address clients authorize when using the delegation auth method.\n */\n delegateAddress?: Hex;\n tokens: TokenPaymentInfo[];\n /**\n * Whether the chain supports sponsorship for the trialed subscription approval transaction.\n * This is used to determine if the user can be sponsored for the gas fees for the trialed subscription approval transaction.\n */\n isSponsorshipSupported?: boolean;\n};\n\nexport type PricingCardPaymentMethod = {\n type: Extract<PaymentType, 'card'>;\n /**\n * Products that support this payment method.\n */\n products?: ProductType[];\n};\n\nexport type PricingCryptoPaymentMethod = {\n type: Extract<PaymentType, 'crypto'>;\n /**\n * Crypto authorization method. Omitted together with `products` on persisted\n * pre-multi-product pricing rows; those rows are treated as Shield + `erc20_approval`.\n * If `products` is set, this field must be explicit.\n */\n cryptoAuthMethod?: CryptoAuthMethod;\n /**\n * Products that support this payment method. Omitted together with\n * `cryptoAuthMethod` on persisted pre-multi-product pricing rows (treated as Shield).\n * If present, must be non-empty and paired with an explicit `cryptoAuthMethod`.\n */\n products?: ProductType[];\n chains?: ChainPaymentInfo[];\n};\n\n/**\n * A pricing payment-method row. Discriminated by `type`: card rows have no\n * crypto fields; crypto rows may include `cryptoAuthMethod` and `chains`.\n */\nexport type PricingPaymentMethod =\n | PricingCardPaymentMethod\n | PricingCryptoPaymentMethod;\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\n/**\n * Request to submit a Shield ERC-20 crypto approval transaction.\n */\nexport type SubmitSubscriptionCryptoApprovalRequest = {\n /**\n * The subscription product. Typed as `typeof PRODUCT_TYPES.SHIELD` only at\n * the moment (future might support more product).\n */\n productType: typeof PRODUCT_TYPES.SHIELD;\n /**\n * The transaction metadata. Must have type\n * `TransactionType.shieldSubscriptionApprove`.\n */\n txMeta: TransactionMeta;\n /**\n * Whether the transaction is sponsored.\n */\n isSponsored?: boolean;\n /**\n * The account ID of the reward subscription to link.\n */\n rewardAccountId?: CaipAccountId;\n};\n\nexport const COHORT_NAMES = {\n POST_TX: 'post_tx',\n WALLET_HOME: 'wallet_home',\n} as const;\n\nexport type CohortName = (typeof COHORT_NAMES)[keyof typeof COHORT_NAMES];\n\nexport const BALANCE_CATEGORIES = {\n RANGE_0_99: '0-99',\n RANGE_100_999: '100-999',\n RANGE_1K_9_9K: '1k-9.9k',\n RANGE_10K_99_9K: '10k-99.9k',\n RANGE_100K_999_9K: '100k-999.9k',\n RANGE_1M_PLUS: '1M+',\n} as const;\n\nexport type BalanceCategory =\n (typeof BALANCE_CATEGORIES)[keyof typeof BALANCE_CATEGORIES];\n\nexport type Cohort = {\n cohort: string;\n eligibilityRate: number; // 0-1 probability of being assigned to this cohort\n priority: number; // lower number = higher priority\n eligible: boolean;\n};\n\nexport type SubscriptionEligibility = {\n product: ProductType;\n canSubscribe: boolean;\n canViewEntryModal: boolean;\n modalType?: ModalType;\n cohorts: Cohort[];\n assignedCohort: string | null;\n hasAssignedCohortExpired: boolean;\n};\n\nexport const SubscriptionUserEvent = {\n ShieldEntryModalViewed: 'shield_entry_modal_viewed',\n ShieldCohortAssigned: 'shield_cohort_assigned',\n} as const;\n\nexport type SubscriptionUserEventType =\n (typeof SubscriptionUserEvent)[keyof typeof SubscriptionUserEvent];\n\nexport type SubmitUserEventRequest = {\n event: SubscriptionUserEventType;\n cohort?: string;\n};\n\nexport type AssignCohortRequest = {\n cohort: string;\n};\n\nexport type GetSubscriptionsEligibilitiesRequest = {\n balanceCategory?: BalanceCategory;\n};\n\n/**\n * Request object for submitting sponsorship intents.\n */\nexport type SubmitSponsorshipIntentsRequest = {\n chainId: Hex;\n address: Hex;\n products: ProductType[];\n paymentTokenSymbol: string;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n\nexport type SubmitSponsorshipIntentsMethodParams = Pick<\n SubmitSponsorshipIntentsRequest,\n 'chainId' | 'address' | 'products'\n>;\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n getBenefits(): Promise<SubscriptionBenefitsResponse>;\n cancelSubscription(request: CancelSubscriptionRequest): Promise<Subscription>;\n unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<Subscription>;\n /**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getBillingPortalUrl(): Promise<BillingPortalResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<UpdatePaymentMethodCardResponse>;\n updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void>;\n getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]>;\n submitUserEvent(request: SubmitUserEventRequest): Promise<void>;\n assignUserToCohort(request: AssignCohortRequest): Promise<void>;\n\n /**\n * Link rewards to a subscription.\n */\n linkRewards(\n request: LinkRewardsRequest,\n ): Promise<SubscriptionApiGeneralResponse>;\n\n /**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example {\n * address: '0x1234567890123456789012345678901234567890',\n * products: [ProductType.Shield],\n * recurringInterval: RecurringInterval.Month,\n * billingCycles: 1,\n * }\n */\n submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsRequest,\n ): Promise<void>;\n};\n\nexport type UpdatePaymentMethodOpts =\n | ({\n paymentType: Extract<PaymentType, 'card'>;\n } & UpdatePaymentMethodCardRequest)\n | ({\n paymentType: Extract<PaymentType, 'crypto'>;\n } & UpdatePaymentMethodCryptoRequest);\n\nexport type UpdatePaymentMethodCardRequest = {\n /**\n * Subscription ID\n */\n subscriptionId: string;\n\n /**\n * Recurring interval\n */\n recurringInterval: RecurringInterval;\n successUrl?: string;\n cancelUrl?: string;\n};\n\nexport type UpdatePaymentMethodCardResponse = {\n redirectUrl: string;\n};\n\ntype UpdatePaymentMethodCryptoRequestBase = {\n subscriptionId: string;\n chainId: Hex;\n payerAddress: Hex;\n tokenSymbol: string;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n\n/**\n * ERC-20 approval crypto payment-method update request.\n *\n * `rawTransaction` may be omitted when retrying after a balance top-up.\n */\nexport type UpdateErc20PaymentMethodCryptoRequest =\n UpdatePaymentMethodCryptoRequestBase & {\n cryptoAuthMethod?: typeof CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n /**\n * The raw transaction to pay for the subscription.\n */\n rawTransaction?: Hex;\n delegationHash?: never;\n };\n\n/**\n * Delegation crypto payment-method update request used to rotate an active\n * subscription to a replacement delegation.\n */\nexport type UpdateDelegationPaymentMethodCryptoRequest =\n UpdatePaymentMethodCryptoRequestBase & {\n cryptoAuthMethod: typeof CRYPTO_AUTH_METHODS.DELEGATION;\n delegationHash: Hex;\n rawTransaction?: never;\n };\n\n/**\n * Request to update a subscription's crypto payment method.\n *\n * Provide `rawTransaction` for the existing ERC-20 approval path, or provide\n * `cryptoAuthMethod: 'delegation'` and `delegationHash` to rotate a delegation.\n */\nexport type UpdatePaymentMethodCryptoRequest =\n | UpdateErc20PaymentMethodCryptoRequest\n | UpdateDelegationPaymentMethodCryptoRequest;\n\nexport type BillingPortalResponse = {\n url: string;\n};\n\n/**\n * The cached result of last selected payment methods for the user.\n * These details are being cached to be used internally to track the last selected payment method for the user. (e.g. for crypto subscriptions)\n */\nexport type CachedLastSelectedPaymentMethod = {\n type: PaymentType;\n paymentTokenAddress?: Hex;\n paymentTokenSymbol?: string;\n plan: RecurringInterval;\n useTestClock?: boolean;\n /**\n * Crypto authorization method. Omitted on persisted cache entries written\n * before this field existed; treat as `erc20_approval` when missing.\n */\n cryptoAuthMethod?: CryptoAuthMethod;\n};\n\n/**\n * Request to cache the last selected payment method for a product.\n */\nexport type CacheLastSelectedPaymentMethodRequest = {\n /**\n * The product to cache the payment method for.\n */\n product: ProductType;\n /**\n * The payment method to cache.\n */\n paymentMethod: CachedLastSelectedPaymentMethod;\n};\n\n/**\n * Request object for linking rewards to a subscription.\n */\nexport type LinkRewardsRequest = {\n /**\n * The ID of the reward subscription to be linked to the subscription.\n *\n * @example {\n * rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890',\n * }\n */\n rewardAccountId: CaipAccountId;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/subscription-controller",
3
- "version": "12.0.1-preview-2bc848240",
3
+ "version": "12.0.1-preview-136f5f1",
4
4
  "description": "Handle user subscription",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -59,6 +59,7 @@
59
59
  "@metamask/delegation-controller": "^4.0.0",
60
60
  "@metamask/delegation-core": "^2.2.1",
61
61
  "@metamask/delegation-deployments": "^1.4.0",
62
+ "@metamask/geolocation-controller": "^2.0.0",
62
63
  "@metamask/messenger": "^3.0.0",
63
64
  "@metamask/money-account-balance-service": "^3.1.2",
64
65
  "@metamask/money-account-upgrade-controller": "^5.1.0",