@metamask-previews/subscription-controller 13.0.0-preview-b59bc5b6f → 14.0.0-preview-373786801
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 +7 -1
- package/dist/SubscriptionController-method-action-types.d.ts +8 -4
- package/dist/SubscriptionController-method-action-types.d.ts.map +1 -1
- package/dist/SubscriptionController-method-action-types.js.map +1 -1
- package/dist/SubscriptionController.d.ts +8 -4
- package/dist/SubscriptionController.d.ts.map +1 -1
- package/dist/SubscriptionController.js +19 -13
- package/dist/SubscriptionController.js.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts +2 -2
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService.js +2 -3
- package/dist/subscription-delegation/SubscriptionDelegationService.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,14 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [14.0.0]
|
|
11
|
+
|
|
10
12
|
### Changed
|
|
11
13
|
|
|
14
|
+
- **BREAKING:** `SubscriptionDelegationServiceMessenger` now requires `SubscriptionController:isUserEligibleForTrial` ([#10795](https://github.com/MetaMask/core/pull/10795))
|
|
15
|
+
- Clients that construct this messenger must delegate `SubscriptionController:isUserEligibleForTrial`.
|
|
12
16
|
- Bump `@metamask/profile-sync-controller` from `^34.0.2` to `^34.0.3` ([#10761](https://github.com/MetaMask/core/pull/10761))
|
|
13
17
|
- Require `Subscription.currentPeriodStart`, `currentPeriodEnd`, `cancelType`, and `isEligibleForSupport` in the subscription response and runtime validation. ([#10765](https://github.com/MetaMask/core/pull/10765))
|
|
14
18
|
- Bump `@metamask/transaction-controller` from `^72.1.0` to `^72.2.0` ([#10772](https://github.com/MetaMask/core/pull/10772))
|
|
15
19
|
|
|
16
20
|
### Fixed
|
|
17
21
|
|
|
22
|
+
- Fixed Money Account Plus checkout requesting a trial for a user `isUserEligibleForTrial` rejects ([#10795](https://github.com/MetaMask/core/pull/10795))
|
|
18
23
|
- `SubscriptionController:unCancelSubscription` refreshes subscriptions after a successful uncancel. ([#10802](https://github.com/MetaMask/core/pull/10802))
|
|
19
24
|
- The stored subscription is replaced with the uncancel response instead of merged with it, so optional fields the response omits (such as `cancelAtPeriodEnd` and `canceledAt`) no longer keep stale values, including when the subscription refresh fails.
|
|
20
25
|
|
|
@@ -641,7 +646,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
641
646
|
- Bump `@metamask/controller-utils` from `^11.12.0` to `^11.14.0` ([#6620](https://github.com/MetaMask/core/pull/6620), [#6629](https://github.com/MetaMask/core/pull/6629))
|
|
642
647
|
- Bump `@metamask/utils` from `^11.4.2` to `^11.8.0` ([#6588](https://github.com/MetaMask/core/pull/6588))
|
|
643
648
|
|
|
644
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@
|
|
649
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@14.0.0...HEAD
|
|
650
|
+
[14.0.0]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@13.0.0...@metamask/subscription-controller@14.0.0
|
|
645
651
|
[13.0.0]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@12.0.1...@metamask/subscription-controller@13.0.0
|
|
646
652
|
[12.0.1]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@12.0.0...@metamask/subscription-controller@12.0.1
|
|
647
653
|
[12.0.0]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@11.0.0...@metamask/subscription-controller@12.0.0
|
|
@@ -75,8 +75,10 @@ export type SubscriptionControllerUnCancelSubscriptionAction = {
|
|
|
75
75
|
* Starts a card-paid subscription checkout session for the requested products
|
|
76
76
|
* (e.g. Shield or Money Account Plus).
|
|
77
77
|
*
|
|
78
|
-
* `isTrialRequested` on the request is ignored and overwritten from
|
|
79
|
-
*
|
|
78
|
+
* `isTrialRequested` on the request is ignored and overwritten from
|
|
79
|
+
* `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible
|
|
80
|
+
* when it has not been trialed. Money Account Plus is eligible when it has
|
|
81
|
+
* not been trialed and the user is authenticated with social login.
|
|
80
82
|
*
|
|
81
83
|
* `isEligibleForRefund` is sent as provided. When omitted, it is resolved
|
|
82
84
|
* from geolocation (EU/EEA), or `false` if the lookup fails.
|
|
@@ -94,8 +96,10 @@ export type SubscriptionControllerStartSubscriptionWithCardAction = {
|
|
|
94
96
|
* creates the subscription immediately, so local state is refreshed
|
|
95
97
|
* afterwards.
|
|
96
98
|
*
|
|
97
|
-
* `isTrialRequested` on the request is ignored and overwritten from
|
|
98
|
-
*
|
|
99
|
+
* `isTrialRequested` on the request is ignored and overwritten from
|
|
100
|
+
* `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible
|
|
101
|
+
* when it has not been trialed. Money Account Plus is eligible when it has
|
|
102
|
+
* not been trialed and the user is authenticated with social login.
|
|
99
103
|
*
|
|
100
104
|
* `isEligibleForRefund` is sent as provided. When omitted, it is resolved
|
|
101
105
|
* from geolocation (EU/EEA), or `false` if the lookup fails.
|
|
@@ -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,IAAI,EAAE,sDAAsD,CAAC;IAC7D,OAAO,EAAE,sBAAsB,CAAC,+BAA+B,CAAC,CAAC;CAClE,CAAC;AAEF,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,2CAA2C,CAAC;IAClD,OAAO,EAAE,sBAAsB,CAAC,oBAAoB,CAAC,CAAC;CACvD,CAAC;AAEF,MAAM,MAAM,gDAAgD,GAAG;IAC7D,IAAI,EAAE,6CAA6C,CAAC;IACpD,OAAO,EAAE,sBAAsB,CAAC,sBAAsB,CAAC,CAAC;CACzD,CAAC;AAEF
|
|
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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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 +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 * `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
|
+
{"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\n * `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible\n * when it has not been trialed. Money Account Plus is eligible when it has\n * not been trialed and the user is authenticated with social login.\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\n * `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible\n * when it has not been trialed. Money Account Plus is eligible when it has\n * not been trialed and the user is authenticated with social login.\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"]}
|
|
@@ -132,8 +132,10 @@ export declare class SubscriptionController extends SubscriptionController_base<
|
|
|
132
132
|
* Starts a card-paid subscription checkout session for the requested products
|
|
133
133
|
* (e.g. Shield or Money Account Plus).
|
|
134
134
|
*
|
|
135
|
-
* `isTrialRequested` on the request is ignored and overwritten from
|
|
136
|
-
*
|
|
135
|
+
* `isTrialRequested` on the request is ignored and overwritten from
|
|
136
|
+
* `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible
|
|
137
|
+
* when it has not been trialed. Money Account Plus is eligible when it has
|
|
138
|
+
* not been trialed and the user is authenticated with social login.
|
|
137
139
|
*
|
|
138
140
|
* `isEligibleForRefund` is sent as provided. When omitted, it is resolved
|
|
139
141
|
* from geolocation (EU/EEA), or `false` if the lookup fails.
|
|
@@ -148,8 +150,10 @@ export declare class SubscriptionController extends SubscriptionController_base<
|
|
|
148
150
|
* creates the subscription immediately, so local state is refreshed
|
|
149
151
|
* afterwards.
|
|
150
152
|
*
|
|
151
|
-
* `isTrialRequested` on the request is ignored and overwritten from
|
|
152
|
-
*
|
|
153
|
+
* `isTrialRequested` on the request is ignored and overwritten from
|
|
154
|
+
* `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible
|
|
155
|
+
* when it has not been trialed. Money Account Plus is eligible when it has
|
|
156
|
+
* not been trialed and the user is authenticated with social login.
|
|
153
157
|
*
|
|
154
158
|
* `isEligibleForRefund` is sent as provided. When omitted, it is resolved
|
|
155
159
|
* from geolocation (EU/EEA), or `false` if the lookup fails.
|
|
@@ -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,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,mCAA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AI,CAiBN;IAED;;;;OAIG;IACH,8BAA8B,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAOzD;IAED;;;;;;;;;;;;;;;OAeG;IACG,wBAAwB,CAC5B,OAAO,EAAE,oCAAoC,GAC5C,OAAO,CAAC,OAAO,CAAC,CAyClB;IAED;;;;;OAKG;IACG,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEpE;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;CA2ZF"}
|
|
@@ -327,8 +327,10 @@ export class SubscriptionController extends StaticIntervalPollingController() {
|
|
|
327
327
|
* Starts a card-paid subscription checkout session for the requested products
|
|
328
328
|
* (e.g. Shield or Money Account Plus).
|
|
329
329
|
*
|
|
330
|
-
* `isTrialRequested` on the request is ignored and overwritten from
|
|
331
|
-
*
|
|
330
|
+
* `isTrialRequested` on the request is ignored and overwritten from
|
|
331
|
+
* `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible
|
|
332
|
+
* when it has not been trialed. Money Account Plus is eligible when it has
|
|
333
|
+
* not been trialed and the user is authenticated with social login.
|
|
332
334
|
*
|
|
333
335
|
* `isEligibleForRefund` is sent as provided. When omitted, it is resolved
|
|
334
336
|
* from geolocation (EU/EEA), or `false` if the lookup fails.
|
|
@@ -340,9 +342,10 @@ export class SubscriptionController extends StaticIntervalPollingController() {
|
|
|
340
342
|
// get the latest subscriptions state before computing trial eligibility
|
|
341
343
|
await this.getSubscriptions();
|
|
342
344
|
this.#assertIsUserNotSubscribed({ products: request.products });
|
|
345
|
+
const isTrialRequested = await this.#getIsTrialRequested(request.products, request.recurringInterval);
|
|
343
346
|
const response = await this.messenger.call('SubscriptionService:startSubscriptionWithCard', {
|
|
344
347
|
...request,
|
|
345
|
-
isTrialRequested
|
|
348
|
+
isTrialRequested,
|
|
346
349
|
isEligibleForRefund: await this.#getIsEligibleForRefund(request.isEligibleForRefund),
|
|
347
350
|
});
|
|
348
351
|
// note: no need to trigger access token refresh after startSubscriptionWithCard request because this only return stripe checkout session url, subscription not created yet
|
|
@@ -354,8 +357,10 @@ export class SubscriptionController extends StaticIntervalPollingController() {
|
|
|
354
357
|
* creates the subscription immediately, so local state is refreshed
|
|
355
358
|
* afterwards.
|
|
356
359
|
*
|
|
357
|
-
* `isTrialRequested` on the request is ignored and overwritten from
|
|
358
|
-
*
|
|
360
|
+
* `isTrialRequested` on the request is ignored and overwritten from
|
|
361
|
+
* `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible
|
|
362
|
+
* when it has not been trialed. Money Account Plus is eligible when it has
|
|
363
|
+
* not been trialed and the user is authenticated with social login.
|
|
359
364
|
*
|
|
360
365
|
* `isEligibleForRefund` is sent as provided. When omitted, it is resolved
|
|
361
366
|
* from geolocation (EU/EEA), or `false` if the lookup fails.
|
|
@@ -371,7 +376,7 @@ export class SubscriptionController extends StaticIntervalPollingController() {
|
|
|
371
376
|
// get the latest subscriptions state before computing trial eligibility
|
|
372
377
|
await this.#getSubscriptions({ refreshBenefits: false });
|
|
373
378
|
this.#assertIsUserNotSubscribed({ products: request.products });
|
|
374
|
-
const isTrialRequested = this.#getIsTrialRequested(request.products, request.recurringInterval);
|
|
379
|
+
const isTrialRequested = await this.#getIsTrialRequested(request.products, request.recurringInterval);
|
|
375
380
|
if (request.assertTrialEligibility &&
|
|
376
381
|
request.isTrialRequested !== isTrialRequested) {
|
|
377
382
|
throw new Error(SubscriptionDelegationServiceErrorMessage.TrialEligibilityChanged);
|
|
@@ -432,7 +437,7 @@ export class SubscriptionController extends StaticIntervalPollingController() {
|
|
|
432
437
|
const productPrice = this.#getProductPriceByProductAndPlan(productType, lastSelectedPaymentMethodForProduct.plan);
|
|
433
438
|
// get the latest subscriptions state before computing trial eligibility
|
|
434
439
|
await this.#getSubscriptions({ refreshBenefits: false });
|
|
435
|
-
const isTrialRequested = this.#getIsTrialRequested([productType], lastSelectedPaymentMethodForProduct.plan);
|
|
440
|
+
const isTrialRequested = await this.#getIsTrialRequested([productType], lastSelectedPaymentMethodForProduct.plan);
|
|
436
441
|
const currentSubscription = this.getSubscriptionByProduct(productType);
|
|
437
442
|
this.#assertValidSubscriptionStateForCryptoApproval({
|
|
438
443
|
productType,
|
|
@@ -842,21 +847,22 @@ export class SubscriptionController extends StaticIntervalPollingController() {
|
|
|
842
847
|
}
|
|
843
848
|
/**
|
|
844
849
|
* Whether a trial should be requested for the given products and plan.
|
|
845
|
-
* True only when every product
|
|
846
|
-
*
|
|
850
|
+
* True only when every product is eligible via `isUserEligibleForTrial`
|
|
851
|
+
* and its price has `trialPeriodDays > 0`.
|
|
847
852
|
*
|
|
848
853
|
* @param products - The products to check.
|
|
849
854
|
* @param plan - The recurring interval to look up pricing for.
|
|
850
855
|
* @returns Whether a trial should be requested.
|
|
851
856
|
*/
|
|
852
|
-
#getIsTrialRequested(products, plan) {
|
|
853
|
-
|
|
854
|
-
if (this.
|
|
857
|
+
async #getIsTrialRequested(products, plan) {
|
|
858
|
+
const results = await Promise.all(products.map(async (productType) => {
|
|
859
|
+
if (!(await this.isUserEligibleForTrial(productType))) {
|
|
855
860
|
return false;
|
|
856
861
|
}
|
|
857
862
|
const productPrice = this.#getProductPriceByProductAndPlan(productType, plan);
|
|
858
863
|
return productPrice.trialPeriodDays > 0;
|
|
859
|
-
});
|
|
864
|
+
}));
|
|
865
|
+
return results.every(Boolean);
|
|
860
866
|
}
|
|
861
867
|
/**
|
|
862
868
|
* Returns the caller-provided refund eligibility when set. Otherwise
|
|
@@ -1 +1 @@
|
|
|
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;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;AAuF9D;;;;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,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,mBAAmB,EAAE;QACnB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;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AAQ,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 // Replace rather than merge: optional fields the response omits (e.g.\n // `cancelAtPeriodEnd`, `canceledAt`) must not survive from the\n // pending-cancellation state.\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? uncancelledSubscription\n : subscription,\n );\n });\n\n try {\n await this.#getSubscriptions();\n } catch (error) {\n log('Failed to refresh subscriptions after uncancellation', 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 /**\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"]}
|
|
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;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;AAuF9D;;;;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,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,mBAAmB,EAAE;QACnB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,UAAU,EAAE;QACV,k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AC,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 // Replace rather than merge: optional fields the response omits (e.g.\n // `cancelAtPeriodEnd`, `canceledAt`) must not survive from the\n // pending-cancellation state.\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? uncancelledSubscription\n : subscription,\n );\n });\n\n try {\n await this.#getSubscriptions();\n } catch (error) {\n log('Failed to refresh subscriptions after uncancellation', 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 /**\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\n * `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible\n * when it has not been trialed. Money Account Plus is eligible when it has\n * not been trialed and the user is authenticated with social login.\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 const isTrialRequested = await this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\n );\n\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCard',\n {\n ...request,\n isTrialRequested,\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\n * `isUserEligibleForTrial` and `trialPeriodDays > 0`. Shield is eligible\n * when it has not been trialed. Money Account Plus is eligible when it has\n * not been trialed and the user is authenticated with social login.\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 = await 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 = await 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 is eligible via `isUserEligibleForTrial`\n * and its price has `trialPeriodDays > 0`.\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 async #getIsTrialRequested(\n products: ProductType[],\n plan: RecurringInterval,\n ): Promise<boolean> {\n const results = await Promise.all(\n products.map(async (productType) => {\n if (!(await this.isUserEligibleForTrial(productType))) {\n return false;\n }\n\n const productPrice = this.#getProductPriceByProductAndPlan(\n productType,\n plan,\n );\n return productPrice.trialPeriodDays > 0;\n }),\n );\n\n return results.every(Boolean);\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"]}
|
|
@@ -5,7 +5,7 @@ import type { Messenger } from '@metamask/messenger';
|
|
|
5
5
|
import type { MoneyAccountBalanceServiceFetchBalanceWithFallbackAction } from '@metamask/money-account-balance-service';
|
|
6
6
|
import type { MoneyAccountUpgradeControllerForceUpgradeAccountAction } from '@metamask/money-account-upgrade-controller';
|
|
7
7
|
import type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';
|
|
8
|
-
import type { SubscriptionControllerGetPricingAction, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerStartSubscriptionWithCryptoAction } from '../SubscriptionController-method-action-types.js';
|
|
8
|
+
import type { SubscriptionControllerGetPricingAction, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerIsUserEligibleForTrialAction, SubscriptionControllerStartSubscriptionWithCryptoAction } from '../SubscriptionController-method-action-types.js';
|
|
9
9
|
import type { SubscriptionControllerGetStateAction } from '../SubscriptionController.js';
|
|
10
10
|
import type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';
|
|
11
11
|
import type { MoneyAccountBalanceCheckRequest, MoneyAccountBalanceCheckResult, PrepareSubscriptionDelegationRequest, PreparedSubscriptionDelegation, StartSubscriptionWithDelegationRequest, StartSubscriptionWithDelegationResult } from './types.js';
|
|
@@ -21,7 +21,7 @@ export type SubscriptionDelegationServiceActions = SubscriptionDelegationService
|
|
|
21
21
|
/**
|
|
22
22
|
* Actions from other messengers that {@link SubscriptionDelegationServiceMessenger} calls.
|
|
23
23
|
*/
|
|
24
|
-
type AllowedActions = AuthenticatedUserStorageServiceListDelegationsAction | AuthenticatedUserStorageServiceCreateDelegationAction | ChompApiServiceVerifyDelegationAction | ChompApiServiceCreateIntentsAction | ChompApiServiceGetIntentsByAddressAction | DelegationControllerSignDelegationAction | MoneyAccountUpgradeControllerForceUpgradeAccountAction | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction | RemoteFeatureFlagControllerGetStateAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerStartSubscriptionWithCryptoAction;
|
|
24
|
+
type AllowedActions = AuthenticatedUserStorageServiceListDelegationsAction | AuthenticatedUserStorageServiceCreateDelegationAction | ChompApiServiceVerifyDelegationAction | ChompApiServiceCreateIntentsAction | ChompApiServiceGetIntentsByAddressAction | DelegationControllerSignDelegationAction | MoneyAccountUpgradeControllerForceUpgradeAccountAction | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction | RemoteFeatureFlagControllerGetStateAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerIsUserEligibleForTrialAction | SubscriptionControllerStartSubscriptionWithCryptoAction;
|
|
25
25
|
/**
|
|
26
26
|
* Events that {@link SubscriptionDelegationService} exposes to other consumers.
|
|
27
27
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,qDAAqD,EACrD,oDAAoD,EACrD,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EACV,kCAAkC,EAClC,wCAAwC,EACxC,qCAAqC,EACtC,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,wCAAwC,EAAE,MAAM,iCAAiC,CAAC;AAGhG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,wDAAwD,EAAE,MAAM,yCAAyC,CAAC;AACxH,O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Y,OAAO,EAAE,oCAAoC,EAOxD;IAED;;;;;;OAMG;IACG,wBAAwB,CAC5B,OAAO,EAAE,+BAA+B,GACvC,OAAO,CAAC,8BAA8B,CAAC,CAMzC;IA+BD;;;;;;;;;;;;;;;;OAgBG;IACG,+BAA+B,CACnC,OAAO,EAAE,sCAAsC,GAC9C,OAAO,CAAC,qCAAqC,CAAC,CA+DhD;IA2PD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,iBAAiB,CACrB,OAAO,EAAE,oCAAoC,EAC7C,QAAQ,UAAQ,GACf,OAAO,CAAC,8BAA8B,CAAC,CAoKzC;CAiJF"}
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,qDAAqD,EACrD,oDAAoD,EACrD,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EACV,kCAAkC,EAClC,wCAAwC,EACxC,qCAAqC,EACtC,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,wCAAwC,EAAE,MAAM,iCAAiC,CAAC;AAGhG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,wDAAwD,EAAE,MAAM,yCAAyC,CAAC;AACxH,OAAO,KAAK,EAAE,sDAAsD,EAAE,MAAM,4CAA4C,CAAC;AAKzH,OAAO,KAAK,EAAE,yCAAyC,EAAE,MAAM,0CAA0C,CAAC;AAS1G,OAAO,KAAK,EACV,sCAAsC,EACtC,4CAA4C,EAC5C,kDAAkD,EAClD,uDAAuD,EACxD,MAAM,kDAAkD,CAAC;AAC1D,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,8BAA8B,CAAC;AAsBzF,OAAO,KAAK,EAAE,0CAA0C,EAAE,MAAM,wDAAwD,CAAC;AAKzH,OAAO,KAAK,EACV,+BAA+B,EAC/B,8BAA8B,EAC9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AA8B,CAAC,CAoKzC;CAiJF"}
|
|
@@ -112,9 +112,8 @@ export class SubscriptionDelegationService {
|
|
|
112
112
|
}
|
|
113
113
|
const subscriptions = await this.#messenger.call('SubscriptionController:getSubscriptions');
|
|
114
114
|
this.#assertUserNotSubscribed(subscriptions, request.product);
|
|
115
|
-
const
|
|
116
|
-
const isTrialRequested = config.price.trialPeriodDays > 0 &&
|
|
117
|
-
!trialedProducts.includes(request.product);
|
|
115
|
+
const isEligibleForTrial = await this.#messenger.call('SubscriptionController:isUserEligibleForTrial', request.product);
|
|
116
|
+
const isTrialRequested = config.price.trialPeriodDays > 0 && isEligibleForTrial;
|
|
118
117
|
await this.#messenger.call('MoneyAccountUpgradeController:forceUpgradeAccount', request.payerAddress);
|
|
119
118
|
const paymentPermission = await this.#preparePaymentPermission(request, config, isTrialRequested);
|
|
120
119
|
const paymentDelegation = await this.#signPaymentPermissionIfRequired(paymentPermission, config);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAIvE,OAAO,EACL,0BAA0B,EAC1B,aAAa,GACd,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGrD,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,yCAAyC,GAC1C,MAAM,iBAAiB,CAAC;AAOzB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAShF,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mCAAmC,EAAE,MAAM,cAAc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cAAc,EAAE,MAAM,CAAC,cAAc;gBACrC,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,QAAQ,EAAE;oBACR,SAAS,EAAE,MAAM,CAAC,SAAS;oBAC3B,WAAW,EAAE,MAAM,CAAC,WAAW;oBAC/B,YAAY,EAAE,MAAM,CAAC,YAAY;oBACjC,IAAI,EAAE,iCAAiC;iBACxC;aACF;SACF,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n DelegationResponse,\n AuthenticatedUserStorageServiceCreateDelegationAction,\n AuthenticatedUserStorageServiceListDelegationsAction,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ChompApiServiceCreateIntentsAction,\n ChompApiServiceGetIntentsByAddressAction,\n ChompApiServiceVerifyDelegationAction,\n} from '@metamask/chomp-api-service';\nimport type { DelegationControllerSignDelegationAction } from '@metamask/delegation-controller';\nimport { hashDelegation } from '@metamask/delegation-core';\nimport { DELEGATOR_CONTRACTS } from '@metamask/delegation-deployments';\nimport type { Messenger } from '@metamask/messenger';\nimport type { MoneyAccountBalanceServiceFetchBalanceWithFallbackAction } from '@metamask/money-account-balance-service';\nimport type { MoneyAccountUpgradeControllerForceUpgradeAccountAction } from '@metamask/money-account-upgrade-controller';\nimport {\n getMoneyAccountVaultConfig,\n MUSD_DECIMALS,\n} from '@metamask/money-account-utils';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport { add0x, hexToNumber } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n SubscriptionControllerErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from '../constants.js';\nimport type {\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n} from '../SubscriptionController-method-action-types.js';\nimport type { SubscriptionControllerGetStateAction } from '../SubscriptionController.js';\nimport { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';\nimport type {\n ProductPrice,\n ProductType,\n PricingCryptoPaymentMethod,\n RecurringInterval,\n Subscription,\n TokenPaymentInfo,\n} from '../types.js';\nimport {\n assertPositiveInteger,\n calculatePeriodAmount,\n getDelegationStartDate,\n getPeriodDuration,\n} from './amount.js';\nimport { buildUnsignedSubscriptionDelegation } from './caveats.js';\nimport {\n equalsIgnoreCase,\n makeMatchesSubscriptionDelegation,\n pickLatestMatchingSubscriptionDelegation,\n} from './fingerprint.js';\nimport type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';\nimport {\n buildDelegationTypedData,\n decodeSubscriptionAuthority,\n} from './typed-data.js';\nimport type {\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PreparedSubscriptionPermission,\n PreparedSubscriptionDelegation,\n SignedSubscriptionDelegation,\n StartSubscriptionWithDelegationRequest,\n StartSubscriptionWithDelegationResult,\n SubscriptionDelegationEnforcers,\n UnsignedSubscriptionDelegation,\n} from './types.js';\nimport { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';\n\n/**\n * The name of the {@link SubscriptionDelegationService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'SubscriptionDelegationService';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'prepareDelegation',\n 'checkMoneyAccountBalance',\n 'startSubscriptionWithDelegation',\n] as const;\n\nconst DELEGATION_FRAMEWORK_VERSION = '1.3.0';\n\nfunction resolveEnforcers(chainId: Hex): SubscriptionDelegationEnforcers {\n const contracts =\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION]?.[hexToNumber(chainId)];\n\n if (\n !contracts?.ERC20PeriodTransferEnforcer ||\n !contracts.AllowedCalldataEnforcer\n ) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.DelegationContractsNotFound}: ${chainId}`,\n );\n }\n\n return {\n erc20TokenPeriodTransfer: contracts.ERC20PeriodTransferEnforcer,\n allowedCalldata: contracts.AllowedCalldataEnforcer,\n };\n}\n\nfunction removeDelegationSignature(\n delegation: SignedSubscriptionDelegation,\n): UnsignedSubscriptionDelegation {\n const { signature: _signature, ...unsignedDelegation } = delegation;\n return unsignedDelegation;\n}\n\n/**\n * Actions that {@link SubscriptionDelegationService} exposes to other consumers.\n */\nexport type SubscriptionDelegationServiceActions =\n SubscriptionDelegationServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link SubscriptionDelegationServiceMessenger} calls.\n */\ntype AllowedActions =\n | AuthenticatedUserStorageServiceListDelegationsAction\n | AuthenticatedUserStorageServiceCreateDelegationAction\n | ChompApiServiceVerifyDelegationAction\n | ChompApiServiceCreateIntentsAction\n | ChompApiServiceGetIntentsByAddressAction\n | DelegationControllerSignDelegationAction\n | MoneyAccountUpgradeControllerForceUpgradeAccountAction\n | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction\n | RemoteFeatureFlagControllerGetStateAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction;\n\n/**\n * Events that {@link SubscriptionDelegationService} exposes to other consumers.\n */\nexport type SubscriptionDelegationServiceEvents = never;\n\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link SubscriptionDelegationService}.\n */\nexport type SubscriptionDelegationServiceMessenger = Messenger<\n typeof serviceName,\n SubscriptionDelegationServiceActions | AllowedActions,\n SubscriptionDelegationServiceEvents | AllowedEvents\n>;\n\n/**\n * Options for constructing {@link SubscriptionDelegationService}.\n */\nexport type SubscriptionDelegationServiceOptions = {\n messenger: SubscriptionDelegationServiceMessenger;\n};\n\ntype SubscriptionIntentParams = {\n account: Hex;\n chainId: Hex;\n delegationHash: Hex;\n allowance: Hex;\n tokenSymbol: string;\n tokenAddress: Hex;\n};\n\ntype ResolvedSubscriptionDelegationConfig = {\n chainId: Hex;\n delegateAddress: Hex;\n delegationManager: Hex;\n paymentAddress: Hex;\n enforcers: SubscriptionDelegationEnforcers;\n price: ProductPrice;\n token: TokenPaymentInfo;\n};\n\n/**\n * Stateless orchestrator for cash-subscription delegation setup.\n *\n * Owns the workflow: size periodic caveats → sign → CHOMP verify → persist to\n * Authenticated User Storage → register CHOMP intent. Returns a verified\n * `delegationHash` for `SubscriptionController.startSubscriptionWithCrypto`.\n *\n * Pass `skipChompInteractions: true` to skip CHOMP verify and intent\n * registration and return a locally computed delegation hash.\n *\n * Each call resolves the Money Account chain from remote feature flags, then\n * resolves its price, payment token, and delegate from `SubscriptionController`\n * pricing. The pricing `delegateAddress` is used as the delegation `delegate`.\n *\n * Does not own subscription state; `SubscriptionController` does not depend on\n * this service. Only Money Account Plus is supported.\n */\nexport class SubscriptionDelegationService {\n readonly name: typeof serviceName = serviceName;\n\n readonly #messenger: SubscriptionDelegationServiceMessenger;\n\n constructor(options: SubscriptionDelegationServiceOptions) {\n this.#messenger = options.messenger;\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Checks whether the Money Account holds enough convertible mUSD value to\n * cover pricing `unitAmount × minBillingCyclesForBalance`.\n *\n * @param request - Payer address and pricing amount fields.\n * @returns Balance comparison in mUSD base units (6 decimals).\n */\n async checkMoneyAccountBalance(\n request: MoneyAccountBalanceCheckRequest,\n ): Promise<MoneyAccountBalanceCheckResult> {\n const { price } = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n return this.#compareMoneyAccountBalance(request.payerAddress, price);\n }\n\n async #compareMoneyAccountBalance(\n payerAddress: Hex,\n price: ProductPrice,\n ): Promise<MoneyAccountBalanceCheckResult> {\n assertPositiveInteger(\n price.minBillingCyclesForBalance,\n SubscriptionDelegationServiceErrorMessage.InvalidMinimumFundingCycles,\n );\n\n const periodAmount = calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: MUSD_DECIMALS,\n });\n const requiredBalance =\n periodAmount * BigInt(price.minBillingCyclesForBalance);\n\n const { totalBalance } = await this.#messenger.call(\n 'MoneyAccountBalanceService:fetchBalanceWithFallback',\n payerAddress,\n );\n\n return {\n hasSufficientBalance: BigInt(totalBalance) >= requiredBalance,\n balance: totalBalance,\n requiredBalance: requiredBalance.toString(),\n };\n }\n\n /**\n * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade, delegation signing, persistence,\n * or CHOMP registration.\n *\n * The caller must obtain user consent and initiate funding before calling.\n * `MoneyAccountUpgradeController` ensures the Money Account vault\n * delegations and CHOMP intents exist. The Subscription API validates those\n * delegations and the Money Account balance server-side. No payment\n * delegation signing, persistence, or intent mutation occurs before the\n * account is upgraded.\n *\n * @param request - Product selection and Money Account identity.\n * @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.\n */\n async startSubscriptionWithDelegation(\n request: StartSubscriptionWithDelegationRequest,\n ): Promise<StartSubscriptionWithDelegationResult> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const config = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n if (!equalsIgnoreCase(request.chainId, config.chainId)) {\n throw new Error(SubscriptionDelegationServiceErrorMessage.ChainMismatch);\n }\n const subscriptions = await this.#messenger.call(\n 'SubscriptionController:getSubscriptions',\n );\n this.#assertUserNotSubscribed(subscriptions, request.product);\n const { trialedProducts } = this.#messenger.call(\n 'SubscriptionController:getState',\n );\n const isTrialRequested =\n config.price.trialPeriodDays > 0 &&\n !trialedProducts.includes(request.product);\n\n await this.#messenger.call(\n 'MoneyAccountUpgradeController:forceUpgradeAccount',\n request.payerAddress,\n );\n\n const paymentPermission = await this.#preparePaymentPermission(\n request,\n config,\n isTrialRequested,\n );\n const paymentDelegation = await this.#signPaymentPermissionIfRequired(\n paymentPermission,\n config,\n );\n const paymentDelegationHash = await this.#commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n });\n return await this.#messenger.call(\n 'SubscriptionController:startSubscriptionWithCrypto',\n {\n products: [request.product],\n isTrialRequested,\n recurringInterval: request.recurringInterval,\n billingCycles: config.price.minBillingCycles,\n chainId: request.chainId,\n payerAddress: request.payerAddress,\n tokenSymbol: config.token.symbol,\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.DELEGATION,\n delegationHash: paymentDelegationHash,\n // Reject if eligibility changed during checkout, because the signed\n // delegation start date was derived from the original trial state.\n // This local guard is removed before the backend request.\n assertTrialEligibility: true,\n },\n );\n }\n\n /**\n * Rejects when the refreshed list already contains an active subscription\n * for the product. Active includes `active`, `trialing`, and `provisional`.\n *\n * @param subscriptions - Subscriptions returned by the latest refresh.\n * @param product - Product the caller is trying to start.\n */\n #assertUserNotSubscribed(\n subscriptions: Subscription[],\n product: ProductType,\n ): void {\n const alreadySubscribed = subscriptions.some(\n (subscription) =>\n ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status) &&\n subscription.products.some((entry) => entry.name === product),\n );\n if (alreadySubscribed) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n async #preparePaymentPermission(\n request: StartSubscriptionWithDelegationRequest,\n config: ResolvedSubscriptionDelegationConfig,\n isTrialRequested: boolean,\n ): Promise<PreparedSubscriptionPermission> {\n const periodAmount = calculatePeriodAmount({\n unitAmount: config.price.unitAmount,\n unitDecimals: config.price.unitDecimals,\n tokenDecimals: config.token.decimals,\n });\n const periodDuration = getPeriodDuration(request.recurringInterval);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const startDate = getDelegationStartDate({\n nowSeconds,\n trialPeriodDays: isTrialRequested\n ? config.price.trialPeriodDays\n : undefined,\n });\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress: config.delegateAddress,\n chainId: request.chainId,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred: startDate > nowSeconds,\n enforcers: config.enforcers,\n });\n const reusable = pickLatestMatchingSubscriptionDelegation(\n (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).filter(matches),\n config.enforcers,\n );\n const delegation = reusable\n ? removeDelegationSignature(reusable.signedDelegation)\n : buildUnsignedSubscriptionDelegation({\n delegateAddress: config.delegateAddress,\n delegatorAddress: request.payerAddress,\n enforcers: config.enforcers,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n const typedData = buildDelegationTypedData({\n delegation,\n chainId: request.chainId,\n delegationManager: config.delegationManager,\n });\n\n return {\n id: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n owner: 'subscription',\n disposition: reusable ? 'reused' : 'new',\n delegation,\n typedData,\n decodedAuthority: decodeSubscriptionAuthority(\n delegation,\n config.enforcers,\n ),\n ...(reusable\n ? { existingDelegationHash: reusable.metadata.delegationHash }\n : {}),\n };\n }\n\n async #signPaymentPermissionIfRequired(\n permission: PreparedSubscriptionPermission,\n config: ResolvedSubscriptionDelegationConfig,\n ): Promise<SignedSubscriptionDelegation | undefined> {\n if (permission.disposition === 'reused') {\n return undefined;\n }\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n {\n delegation: permission.delegation,\n chainId: config.chainId,\n },\n )) as Hex;\n return { ...permission.delegation, signature };\n }\n\n async #commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n }: {\n request: StartSubscriptionWithDelegationRequest;\n paymentPermission: PreparedSubscriptionPermission;\n paymentDelegation?: SignedSubscriptionDelegation;\n config: ResolvedSubscriptionDelegationConfig;\n }): Promise<Hex> {\n if (paymentPermission.disposition === 'reused') {\n const delegationHash = paymentPermission.existingDelegationHash as Hex;\n const storedDelegation = (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).find(({ metadata }) =>\n equalsIgnoreCase(metadata.delegationHash, delegationHash),\n );\n if (!storedDelegation) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n await this.#verifySignedPaymentDelegation(\n storedDelegation.signedDelegation,\n delegationHash,\n request.chainId,\n );\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance: add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n ),\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n const signedDelegation = paymentDelegation as SignedSubscriptionDelegation;\n const delegationHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n await this.#verifySignedPaymentDelegation(\n signedDelegation,\n delegationHash,\n request.chainId,\n );\n\n const allowance = add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n );\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: request.chainId,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n await this.#createIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n async #assertIntentActive(account: Hex, delegationHash: Hex): Promise<void> {\n const intents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n account,\n );\n const intent = intents.find((candidate) =>\n equalsIgnoreCase(candidate.delegationHash, delegationHash),\n );\n if (intent?.status !== 'active') {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompIntentNotActive,\n );\n }\n }\n\n async #verifySignedPaymentDelegation(\n signedDelegation: SignedSubscriptionDelegation,\n expectedDelegationHash: Hex,\n chainId: Hex,\n ): Promise<void> {\n const localHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n if (!equalsIgnoreCase(localHash, expectedDelegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n { signedDelegation, chainId },\n );\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (\n !equalsIgnoreCase(verifyResult.delegationHash, expectedDelegationHash)\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\n }\n }\n\n /**\n * Prepares a cash-subscription delegation and returns its hash.\n *\n * Reuses a stored AUS delegation that matches the semantic fingerprint when\n * one exists (ensuring a CHOMP intent is active for its hash, unless\n * `skipChompInteractions` is true). Reuse classifies period `startDate` as\n * trial-deferred (`> now`) vs immediately redeemable, matching creation.\n * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\n * If there is no match, builds, signs, optionally verifies with CHOMP,\n * persists, and optionally registers a new delegation.\n *\n * When `skipChompInteractions` is true, CHOMP verify and intent calls are\n * skipped; the returned hash is computed locally.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @param forceNew - Whether to create a replacement instead of reusing a\n * matching stored delegation.\n * @returns The delegation hash (CHOMP-verified unless skipped) and whether it\n * was created or reused.\n */\n async prepareDelegation(\n request: PrepareSubscriptionDelegationRequest,\n forceNew = false,\n ): Promise<PreparedSubscriptionDelegation> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const skipChomp = Boolean(request.skipChompInteractions);\n\n const {\n chainId,\n delegateAddress,\n paymentAddress,\n enforcers,\n price,\n token,\n } = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n\n if (request.checkBalance) {\n const { hasSufficientBalance } = await this.#compareMoneyAccountBalance(\n request.payerAddress,\n price,\n );\n if (!hasSufficientBalance) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.InsufficientBalance,\n );\n }\n }\n\n const periodAmount = calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: token.decimals,\n });\n const periodDuration = getPeriodDuration(request.recurringInterval);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const startDate = getDelegationStartDate({\n nowSeconds,\n trialPeriodDays: request.isTrialRequested\n ? price.trialPeriodDays\n : undefined,\n });\n const isTrialDeferred = startDate > nowSeconds;\n\n const reusable = forceNew\n ? undefined\n : await this.#findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n if (reusable) {\n if (!skipChomp) {\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId,\n delegationHash: reusable.metadata.delegationHash,\n allowance: reusable.metadata.allowance,\n tokenSymbol: reusable.metadata.tokenSymbol,\n tokenAddress: reusable.metadata.tokenAddress,\n });\n }\n return {\n delegationHash: reusable.metadata.delegationHash,\n disposition: 'reused',\n };\n }\n\n const unsigned = buildUnsignedSubscriptionDelegation({\n delegateAddress,\n delegatorAddress: request.payerAddress,\n recipientAddress: paymentAddress,\n enforcers,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n { delegation: unsigned, chainId },\n )) as Hex;\n\n const signedDelegation = { ...unsigned, signature };\n\n const delegationHash = hashDelegation({\n ...unsigned,\n salt: BigInt(unsigned.salt),\n signature,\n });\n\n if (!skipChomp) {\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n {\n signedDelegation,\n chainId,\n },\n );\n\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (!equalsIgnoreCase(verifyResult.delegationHash, delegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\n }\n }\n\n const allowance: Hex = add0x(periodAmount.toString(16));\n\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: chainId,\n allowance,\n tokenSymbol: token.symbol,\n tokenAddress: token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n\n if (!skipChomp) {\n await this.#createIntent({\n account: request.payerAddress,\n chainId,\n delegationHash,\n allowance,\n tokenSymbol: token.symbol,\n tokenAddress: token.address,\n });\n }\n\n return {\n delegationHash,\n disposition: 'created',\n };\n }\n\n async #findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n }: {\n request: PrepareSubscriptionDelegationRequest;\n chainId: Hex;\n delegateAddress: Hex;\n paymentAddress: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n nowSeconds: number;\n isTrialDeferred: boolean;\n enforcers: SubscriptionDelegationEnforcers;\n }): Promise<DelegationResponse | undefined> {\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress,\n recipientAddress: paymentAddress,\n chainId,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n\n const existingDelegations = await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n );\n\n return pickLatestMatchingSubscriptionDelegation(\n existingDelegations.filter(matches),\n enforcers,\n );\n }\n\n async #resolveConfiguration(\n product: ProductType,\n recurringInterval: RecurringInterval,\n ): Promise<ResolvedSubscriptionDelegationConfig> {\n const { remoteFeatureFlags } = this.#messenger.call(\n 'RemoteFeatureFlagController:getState',\n );\n const vaultConfig = getMoneyAccountVaultConfig(remoteFeatureFlags);\n if (!vaultConfig) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.MissingMoneyAccountVaultConfig,\n );\n }\n\n const { chainId } = vaultConfig;\n const enforcers = resolveEnforcers(chainId);\n const pricing = await this.#messenger.call(\n 'SubscriptionController:getPricing',\n );\n const price = pricing.products\n .find((entry) => entry.name === product)\n ?.prices?.find((entry) => entry.interval === recurringInterval);\n const paymentMethod = pricing.paymentMethods.find(\n (entry): entry is PricingCryptoPaymentMethod =>\n entry.type === PAYMENT_TYPES.byCrypto &&\n entry.cryptoAuthMethod === CRYPTO_AUTH_METHODS.DELEGATION &&\n entry.products?.includes(product) === true,\n );\n const chain = paymentMethod?.chains?.find(\n (entry) => entry.chainId === chainId,\n );\n const token = chain?.tokens[0];\n if (!price || !chain?.delegateAddress || !token) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.PricingConfigurationNotFound,\n );\n }\n\n return {\n chainId,\n delegateAddress: chain.delegateAddress,\n delegationManager:\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION][hexToNumber(chainId)]\n .DelegationManager,\n paymentAddress: chain.paymentAddress,\n enforcers,\n price,\n token,\n };\n }\n\n /**\n * Ensures an active CHOMP intent exists for the given delegation hash,\n * registering one when missing or revoked.\n *\n * @param params - Intent identity and metadata.\n * @param params.account - Delegator / payer address.\n * @param params.chainId - Chain ID of the delegation.\n * @param params.delegationHash - Hash of the stored delegation.\n * @param params.allowance - Period allowance stored with the delegation.\n * @param params.tokenSymbol - Payment token symbol.\n * @param params.tokenAddress - Payment token address.\n */\n async #ensureIntent(params: SubscriptionIntentParams): Promise<void> {\n const existingIntents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n params.account,\n );\n\n const hasActiveIntent = existingIntents.some(\n (intent) =>\n equalsIgnoreCase(intent.delegationHash, params.delegationHash) &&\n intent.status === 'active',\n );\n\n if (hasActiveIntent) {\n return;\n }\n\n await this.#createIntent(params);\n }\n\n async #createIntent(params: SubscriptionIntentParams): Promise<void> {\n await this.#messenger.call('ChompApiService:createIntents', [\n {\n account: params.account,\n delegationHash: params.delegationHash,\n chainId: params.chainId,\n metadata: {\n allowance: params.allowance,\n tokenSymbol: params.tokenSymbol,\n tokenAddress: params.tokenAddress,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n ]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAIvE,OAAO,EACL,0BAA0B,EAC1B,aAAa,GACd,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGrD,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,yCAAyC,GAC1C,MAAM,iBAAiB,CAAC;AAQzB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAShF,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mCAAmC,EAAE,MAAM,cAAc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Ac;gBACrC,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,QAAQ,EAAE;oBACR,SAAS,EAAE,MAAM,CAAC,SAAS;oBAC3B,WAAW,EAAE,MAAM,CAAC,WAAW;oBAC/B,YAAY,EAAE,MAAM,CAAC,YAAY;oBACjC,IAAI,EAAE,iCAAiC;iBACxC;aACF;SACF,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n DelegationResponse,\n AuthenticatedUserStorageServiceCreateDelegationAction,\n AuthenticatedUserStorageServiceListDelegationsAction,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ChompApiServiceCreateIntentsAction,\n ChompApiServiceGetIntentsByAddressAction,\n ChompApiServiceVerifyDelegationAction,\n} from '@metamask/chomp-api-service';\nimport type { DelegationControllerSignDelegationAction } from '@metamask/delegation-controller';\nimport { hashDelegation } from '@metamask/delegation-core';\nimport { DELEGATOR_CONTRACTS } from '@metamask/delegation-deployments';\nimport type { Messenger } from '@metamask/messenger';\nimport type { MoneyAccountBalanceServiceFetchBalanceWithFallbackAction } from '@metamask/money-account-balance-service';\nimport type { MoneyAccountUpgradeControllerForceUpgradeAccountAction } from '@metamask/money-account-upgrade-controller';\nimport {\n getMoneyAccountVaultConfig,\n MUSD_DECIMALS,\n} from '@metamask/money-account-utils';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport { add0x, hexToNumber } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n SubscriptionControllerErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from '../constants.js';\nimport type {\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerIsUserEligibleForTrialAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n} from '../SubscriptionController-method-action-types.js';\nimport type { SubscriptionControllerGetStateAction } from '../SubscriptionController.js';\nimport { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';\nimport type {\n ProductPrice,\n ProductType,\n PricingCryptoPaymentMethod,\n RecurringInterval,\n Subscription,\n TokenPaymentInfo,\n} from '../types.js';\nimport {\n assertPositiveInteger,\n calculatePeriodAmount,\n getDelegationStartDate,\n getPeriodDuration,\n} from './amount.js';\nimport { buildUnsignedSubscriptionDelegation } from './caveats.js';\nimport {\n equalsIgnoreCase,\n makeMatchesSubscriptionDelegation,\n pickLatestMatchingSubscriptionDelegation,\n} from './fingerprint.js';\nimport type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';\nimport {\n buildDelegationTypedData,\n decodeSubscriptionAuthority,\n} from './typed-data.js';\nimport type {\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PreparedSubscriptionPermission,\n PreparedSubscriptionDelegation,\n SignedSubscriptionDelegation,\n StartSubscriptionWithDelegationRequest,\n StartSubscriptionWithDelegationResult,\n SubscriptionDelegationEnforcers,\n UnsignedSubscriptionDelegation,\n} from './types.js';\nimport { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';\n\n/**\n * The name of the {@link SubscriptionDelegationService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'SubscriptionDelegationService';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'prepareDelegation',\n 'checkMoneyAccountBalance',\n 'startSubscriptionWithDelegation',\n] as const;\n\nconst DELEGATION_FRAMEWORK_VERSION = '1.3.0';\n\nfunction resolveEnforcers(chainId: Hex): SubscriptionDelegationEnforcers {\n const contracts =\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION]?.[hexToNumber(chainId)];\n\n if (\n !contracts?.ERC20PeriodTransferEnforcer ||\n !contracts.AllowedCalldataEnforcer\n ) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.DelegationContractsNotFound}: ${chainId}`,\n );\n }\n\n return {\n erc20TokenPeriodTransfer: contracts.ERC20PeriodTransferEnforcer,\n allowedCalldata: contracts.AllowedCalldataEnforcer,\n };\n}\n\nfunction removeDelegationSignature(\n delegation: SignedSubscriptionDelegation,\n): UnsignedSubscriptionDelegation {\n const { signature: _signature, ...unsignedDelegation } = delegation;\n return unsignedDelegation;\n}\n\n/**\n * Actions that {@link SubscriptionDelegationService} exposes to other consumers.\n */\nexport type SubscriptionDelegationServiceActions =\n SubscriptionDelegationServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link SubscriptionDelegationServiceMessenger} calls.\n */\ntype AllowedActions =\n | AuthenticatedUserStorageServiceListDelegationsAction\n | AuthenticatedUserStorageServiceCreateDelegationAction\n | ChompApiServiceVerifyDelegationAction\n | ChompApiServiceCreateIntentsAction\n | ChompApiServiceGetIntentsByAddressAction\n | DelegationControllerSignDelegationAction\n | MoneyAccountUpgradeControllerForceUpgradeAccountAction\n | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction\n | RemoteFeatureFlagControllerGetStateAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerIsUserEligibleForTrialAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction;\n\n/**\n * Events that {@link SubscriptionDelegationService} exposes to other consumers.\n */\nexport type SubscriptionDelegationServiceEvents = never;\n\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link SubscriptionDelegationService}.\n */\nexport type SubscriptionDelegationServiceMessenger = Messenger<\n typeof serviceName,\n SubscriptionDelegationServiceActions | AllowedActions,\n SubscriptionDelegationServiceEvents | AllowedEvents\n>;\n\n/**\n * Options for constructing {@link SubscriptionDelegationService}.\n */\nexport type SubscriptionDelegationServiceOptions = {\n messenger: SubscriptionDelegationServiceMessenger;\n};\n\ntype SubscriptionIntentParams = {\n account: Hex;\n chainId: Hex;\n delegationHash: Hex;\n allowance: Hex;\n tokenSymbol: string;\n tokenAddress: Hex;\n};\n\ntype ResolvedSubscriptionDelegationConfig = {\n chainId: Hex;\n delegateAddress: Hex;\n delegationManager: Hex;\n paymentAddress: Hex;\n enforcers: SubscriptionDelegationEnforcers;\n price: ProductPrice;\n token: TokenPaymentInfo;\n};\n\n/**\n * Stateless orchestrator for cash-subscription delegation setup.\n *\n * Owns the workflow: size periodic caveats → sign → CHOMP verify → persist to\n * Authenticated User Storage → register CHOMP intent. Returns a verified\n * `delegationHash` for `SubscriptionController.startSubscriptionWithCrypto`.\n *\n * Pass `skipChompInteractions: true` to skip CHOMP verify and intent\n * registration and return a locally computed delegation hash.\n *\n * Each call resolves the Money Account chain from remote feature flags, then\n * resolves its price, payment token, and delegate from `SubscriptionController`\n * pricing. The pricing `delegateAddress` is used as the delegation `delegate`.\n *\n * Does not own subscription state; `SubscriptionController` does not depend on\n * this service. Only Money Account Plus is supported.\n */\nexport class SubscriptionDelegationService {\n readonly name: typeof serviceName = serviceName;\n\n readonly #messenger: SubscriptionDelegationServiceMessenger;\n\n constructor(options: SubscriptionDelegationServiceOptions) {\n this.#messenger = options.messenger;\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Checks whether the Money Account holds enough convertible mUSD value to\n * cover pricing `unitAmount × minBillingCyclesForBalance`.\n *\n * @param request - Payer address and pricing amount fields.\n * @returns Balance comparison in mUSD base units (6 decimals).\n */\n async checkMoneyAccountBalance(\n request: MoneyAccountBalanceCheckRequest,\n ): Promise<MoneyAccountBalanceCheckResult> {\n const { price } = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n return this.#compareMoneyAccountBalance(request.payerAddress, price);\n }\n\n async #compareMoneyAccountBalance(\n payerAddress: Hex,\n price: ProductPrice,\n ): Promise<MoneyAccountBalanceCheckResult> {\n assertPositiveInteger(\n price.minBillingCyclesForBalance,\n SubscriptionDelegationServiceErrorMessage.InvalidMinimumFundingCycles,\n );\n\n const periodAmount = calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: MUSD_DECIMALS,\n });\n const requiredBalance =\n periodAmount * BigInt(price.minBillingCyclesForBalance);\n\n const { totalBalance } = await this.#messenger.call(\n 'MoneyAccountBalanceService:fetchBalanceWithFallback',\n payerAddress,\n );\n\n return {\n hasSufficientBalance: BigInt(totalBalance) >= requiredBalance,\n balance: totalBalance,\n requiredBalance: requiredBalance.toString(),\n };\n }\n\n /**\n * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade, delegation signing, persistence,\n * or CHOMP registration.\n *\n * The caller must obtain user consent and initiate funding before calling.\n * `MoneyAccountUpgradeController` ensures the Money Account vault\n * delegations and CHOMP intents exist. The Subscription API validates those\n * delegations and the Money Account balance server-side. No payment\n * delegation signing, persistence, or intent mutation occurs before the\n * account is upgraded.\n *\n * @param request - Product selection and Money Account identity.\n * @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.\n */\n async startSubscriptionWithDelegation(\n request: StartSubscriptionWithDelegationRequest,\n ): Promise<StartSubscriptionWithDelegationResult> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const config = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n if (!equalsIgnoreCase(request.chainId, config.chainId)) {\n throw new Error(SubscriptionDelegationServiceErrorMessage.ChainMismatch);\n }\n const subscriptions = await this.#messenger.call(\n 'SubscriptionController:getSubscriptions',\n );\n this.#assertUserNotSubscribed(subscriptions, request.product);\n const isEligibleForTrial = await this.#messenger.call(\n 'SubscriptionController:isUserEligibleForTrial',\n request.product,\n );\n const isTrialRequested =\n config.price.trialPeriodDays > 0 && isEligibleForTrial;\n\n await this.#messenger.call(\n 'MoneyAccountUpgradeController:forceUpgradeAccount',\n request.payerAddress,\n );\n\n const paymentPermission = await this.#preparePaymentPermission(\n request,\n config,\n isTrialRequested,\n );\n const paymentDelegation = await this.#signPaymentPermissionIfRequired(\n paymentPermission,\n config,\n );\n const paymentDelegationHash = await this.#commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n });\n return await this.#messenger.call(\n 'SubscriptionController:startSubscriptionWithCrypto',\n {\n products: [request.product],\n isTrialRequested,\n recurringInterval: request.recurringInterval,\n billingCycles: config.price.minBillingCycles,\n chainId: request.chainId,\n payerAddress: request.payerAddress,\n tokenSymbol: config.token.symbol,\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.DELEGATION,\n delegationHash: paymentDelegationHash,\n // Reject if eligibility changed during checkout, because the signed\n // delegation start date was derived from the original trial state.\n // This local guard is removed before the backend request.\n assertTrialEligibility: true,\n },\n );\n }\n\n /**\n * Rejects when the refreshed list already contains an active subscription\n * for the product. Active includes `active`, `trialing`, and `provisional`.\n *\n * @param subscriptions - Subscriptions returned by the latest refresh.\n * @param product - Product the caller is trying to start.\n */\n #assertUserNotSubscribed(\n subscriptions: Subscription[],\n product: ProductType,\n ): void {\n const alreadySubscribed = subscriptions.some(\n (subscription) =>\n ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status) &&\n subscription.products.some((entry) => entry.name === product),\n );\n if (alreadySubscribed) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n async #preparePaymentPermission(\n request: StartSubscriptionWithDelegationRequest,\n config: ResolvedSubscriptionDelegationConfig,\n isTrialRequested: boolean,\n ): Promise<PreparedSubscriptionPermission> {\n const periodAmount = calculatePeriodAmount({\n unitAmount: config.price.unitAmount,\n unitDecimals: config.price.unitDecimals,\n tokenDecimals: config.token.decimals,\n });\n const periodDuration = getPeriodDuration(request.recurringInterval);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const startDate = getDelegationStartDate({\n nowSeconds,\n trialPeriodDays: isTrialRequested\n ? config.price.trialPeriodDays\n : undefined,\n });\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress: config.delegateAddress,\n chainId: request.chainId,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred: startDate > nowSeconds,\n enforcers: config.enforcers,\n });\n const reusable = pickLatestMatchingSubscriptionDelegation(\n (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).filter(matches),\n config.enforcers,\n );\n const delegation = reusable\n ? removeDelegationSignature(reusable.signedDelegation)\n : buildUnsignedSubscriptionDelegation({\n delegateAddress: config.delegateAddress,\n delegatorAddress: request.payerAddress,\n enforcers: config.enforcers,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n const typedData = buildDelegationTypedData({\n delegation,\n chainId: request.chainId,\n delegationManager: config.delegationManager,\n });\n\n return {\n id: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n owner: 'subscription',\n disposition: reusable ? 'reused' : 'new',\n delegation,\n typedData,\n decodedAuthority: decodeSubscriptionAuthority(\n delegation,\n config.enforcers,\n ),\n ...(reusable\n ? { existingDelegationHash: reusable.metadata.delegationHash }\n : {}),\n };\n }\n\n async #signPaymentPermissionIfRequired(\n permission: PreparedSubscriptionPermission,\n config: ResolvedSubscriptionDelegationConfig,\n ): Promise<SignedSubscriptionDelegation | undefined> {\n if (permission.disposition === 'reused') {\n return undefined;\n }\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n {\n delegation: permission.delegation,\n chainId: config.chainId,\n },\n )) as Hex;\n return { ...permission.delegation, signature };\n }\n\n async #commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n }: {\n request: StartSubscriptionWithDelegationRequest;\n paymentPermission: PreparedSubscriptionPermission;\n paymentDelegation?: SignedSubscriptionDelegation;\n config: ResolvedSubscriptionDelegationConfig;\n }): Promise<Hex> {\n if (paymentPermission.disposition === 'reused') {\n const delegationHash = paymentPermission.existingDelegationHash as Hex;\n const storedDelegation = (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).find(({ metadata }) =>\n equalsIgnoreCase(metadata.delegationHash, delegationHash),\n );\n if (!storedDelegation) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n await this.#verifySignedPaymentDelegation(\n storedDelegation.signedDelegation,\n delegationHash,\n request.chainId,\n );\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance: add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n ),\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n const signedDelegation = paymentDelegation as SignedSubscriptionDelegation;\n const delegationHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n await this.#verifySignedPaymentDelegation(\n signedDelegation,\n delegationHash,\n request.chainId,\n );\n\n const allowance = add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n );\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: request.chainId,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n await this.#createIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n async #assertIntentActive(account: Hex, delegationHash: Hex): Promise<void> {\n const intents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n account,\n );\n const intent = intents.find((candidate) =>\n equalsIgnoreCase(candidate.delegationHash, delegationHash),\n );\n if (intent?.status !== 'active') {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompIntentNotActive,\n );\n }\n }\n\n async #verifySignedPaymentDelegation(\n signedDelegation: SignedSubscriptionDelegation,\n expectedDelegationHash: Hex,\n chainId: Hex,\n ): Promise<void> {\n const localHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n if (!equalsIgnoreCase(localHash, expectedDelegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n { signedDelegation, chainId },\n );\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (\n !equalsIgnoreCase(verifyResult.delegationHash, expectedDelegationHash)\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\n }\n }\n\n /**\n * Prepares a cash-subscription delegation and returns its hash.\n *\n * Reuses a stored AUS delegation that matches the semantic fingerprint when\n * one exists (ensuring a CHOMP intent is active for its hash, unless\n * `skipChompInteractions` is true). Reuse classifies period `startDate` as\n * trial-deferred (`> now`) vs immediately redeemable, matching creation.\n * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\n * If there is no match, builds, signs, optionally verifies with CHOMP,\n * persists, and optionally registers a new delegation.\n *\n * When `skipChompInteractions` is true, CHOMP verify and intent calls are\n * skipped; the returned hash is computed locally.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @param forceNew - Whether to create a replacement instead of reusing a\n * matching stored delegation.\n * @returns The delegation hash (CHOMP-verified unless skipped) and whether it\n * was created or reused.\n */\n async prepareDelegation(\n request: PrepareSubscriptionDelegationRequest,\n forceNew = false,\n ): Promise<PreparedSubscriptionDelegation> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const skipChomp = Boolean(request.skipChompInteractions);\n\n const {\n chainId,\n delegateAddress,\n paymentAddress,\n enforcers,\n price,\n token,\n } = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n\n if (request.checkBalance) {\n const { hasSufficientBalance } = await this.#compareMoneyAccountBalance(\n request.payerAddress,\n price,\n );\n if (!hasSufficientBalance) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.InsufficientBalance,\n );\n }\n }\n\n const periodAmount = calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: token.decimals,\n });\n const periodDuration = getPeriodDuration(request.recurringInterval);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const startDate = getDelegationStartDate({\n nowSeconds,\n trialPeriodDays: request.isTrialRequested\n ? price.trialPeriodDays\n : undefined,\n });\n const isTrialDeferred = startDate > nowSeconds;\n\n const reusable = forceNew\n ? undefined\n : await this.#findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n if (reusable) {\n if (!skipChomp) {\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId,\n delegationHash: reusable.metadata.delegationHash,\n allowance: reusable.metadata.allowance,\n tokenSymbol: reusable.metadata.tokenSymbol,\n tokenAddress: reusable.metadata.tokenAddress,\n });\n }\n return {\n delegationHash: reusable.metadata.delegationHash,\n disposition: 'reused',\n };\n }\n\n const unsigned = buildUnsignedSubscriptionDelegation({\n delegateAddress,\n delegatorAddress: request.payerAddress,\n recipientAddress: paymentAddress,\n enforcers,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n { delegation: unsigned, chainId },\n )) as Hex;\n\n const signedDelegation = { ...unsigned, signature };\n\n const delegationHash = hashDelegation({\n ...unsigned,\n salt: BigInt(unsigned.salt),\n signature,\n });\n\n if (!skipChomp) {\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n {\n signedDelegation,\n chainId,\n },\n );\n\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (!equalsIgnoreCase(verifyResult.delegationHash, delegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\n }\n }\n\n const allowance: Hex = add0x(periodAmount.toString(16));\n\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: chainId,\n allowance,\n tokenSymbol: token.symbol,\n tokenAddress: token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n\n if (!skipChomp) {\n await this.#createIntent({\n account: request.payerAddress,\n chainId,\n delegationHash,\n allowance,\n tokenSymbol: token.symbol,\n tokenAddress: token.address,\n });\n }\n\n return {\n delegationHash,\n disposition: 'created',\n };\n }\n\n async #findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n }: {\n request: PrepareSubscriptionDelegationRequest;\n chainId: Hex;\n delegateAddress: Hex;\n paymentAddress: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n nowSeconds: number;\n isTrialDeferred: boolean;\n enforcers: SubscriptionDelegationEnforcers;\n }): Promise<DelegationResponse | undefined> {\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress,\n recipientAddress: paymentAddress,\n chainId,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n\n const existingDelegations = await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n );\n\n return pickLatestMatchingSubscriptionDelegation(\n existingDelegations.filter(matches),\n enforcers,\n );\n }\n\n async #resolveConfiguration(\n product: ProductType,\n recurringInterval: RecurringInterval,\n ): Promise<ResolvedSubscriptionDelegationConfig> {\n const { remoteFeatureFlags } = this.#messenger.call(\n 'RemoteFeatureFlagController:getState',\n );\n const vaultConfig = getMoneyAccountVaultConfig(remoteFeatureFlags);\n if (!vaultConfig) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.MissingMoneyAccountVaultConfig,\n );\n }\n\n const { chainId } = vaultConfig;\n const enforcers = resolveEnforcers(chainId);\n const pricing = await this.#messenger.call(\n 'SubscriptionController:getPricing',\n );\n const price = pricing.products\n .find((entry) => entry.name === product)\n ?.prices?.find((entry) => entry.interval === recurringInterval);\n const paymentMethod = pricing.paymentMethods.find(\n (entry): entry is PricingCryptoPaymentMethod =>\n entry.type === PAYMENT_TYPES.byCrypto &&\n entry.cryptoAuthMethod === CRYPTO_AUTH_METHODS.DELEGATION &&\n entry.products?.includes(product) === true,\n );\n const chain = paymentMethod?.chains?.find(\n (entry) => entry.chainId === chainId,\n );\n const token = chain?.tokens[0];\n if (!price || !chain?.delegateAddress || !token) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.PricingConfigurationNotFound,\n );\n }\n\n return {\n chainId,\n delegateAddress: chain.delegateAddress,\n delegationManager:\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION][hexToNumber(chainId)]\n .DelegationManager,\n paymentAddress: chain.paymentAddress,\n enforcers,\n price,\n token,\n };\n }\n\n /**\n * Ensures an active CHOMP intent exists for the given delegation hash,\n * registering one when missing or revoked.\n *\n * @param params - Intent identity and metadata.\n * @param params.account - Delegator / payer address.\n * @param params.chainId - Chain ID of the delegation.\n * @param params.delegationHash - Hash of the stored delegation.\n * @param params.allowance - Period allowance stored with the delegation.\n * @param params.tokenSymbol - Payment token symbol.\n * @param params.tokenAddress - Payment token address.\n */\n async #ensureIntent(params: SubscriptionIntentParams): Promise<void> {\n const existingIntents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n params.account,\n );\n\n const hasActiveIntent = existingIntents.some(\n (intent) =>\n equalsIgnoreCase(intent.delegationHash, params.delegationHash) &&\n intent.status === 'active',\n );\n\n if (hasActiveIntent) {\n return;\n }\n\n await this.#createIntent(params);\n }\n\n async #createIntent(params: SubscriptionIntentParams): Promise<void> {\n await this.#messenger.call('ChompApiService:createIntents', [\n {\n account: params.account,\n delegationHash: params.delegationHash,\n chainId: params.chainId,\n metadata: {\n allowance: params.allowance,\n tokenSymbol: params.tokenSymbol,\n tokenAddress: params.tokenAddress,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n ]);\n }\n}\n"]}
|