@metamask-previews/subscription-controller 7.0.0-preview-9efd0b754 → 7.0.0-preview-4e64b66e8
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 +33 -1
- package/dist/SubscriptionController-method-action-types.cjs.map +1 -1
- package/dist/SubscriptionController-method-action-types.d.cts +55 -18
- package/dist/SubscriptionController-method-action-types.d.cts.map +1 -1
- package/dist/SubscriptionController-method-action-types.d.mts +55 -18
- package/dist/SubscriptionController-method-action-types.d.mts.map +1 -1
- package/dist/SubscriptionController-method-action-types.mjs.map +1 -1
- package/dist/SubscriptionController.cjs +165 -45
- package/dist/SubscriptionController.cjs.map +1 -1
- package/dist/SubscriptionController.d.cts +53 -17
- package/dist/SubscriptionController.d.cts.map +1 -1
- package/dist/SubscriptionController.d.mts +53 -17
- package/dist/SubscriptionController.d.mts.map +1 -1
- package/dist/SubscriptionController.mjs +166 -46
- package/dist/SubscriptionController.mjs.map +1 -1
- package/dist/SubscriptionService-method-action-types.cjs.map +1 -1
- package/dist/SubscriptionService-method-action-types.d.cts +5 -1
- package/dist/SubscriptionService-method-action-types.d.cts.map +1 -1
- package/dist/SubscriptionService-method-action-types.d.mts +5 -1
- package/dist/SubscriptionService-method-action-types.d.mts.map +1 -1
- package/dist/SubscriptionService-method-action-types.mjs.map +1 -1
- package/dist/SubscriptionService-structs.cjs +35 -12
- package/dist/SubscriptionService-structs.cjs.map +1 -1
- package/dist/SubscriptionService-structs.d.cts +185 -237
- package/dist/SubscriptionService-structs.d.cts.map +1 -1
- package/dist/SubscriptionService-structs.d.mts +185 -237
- package/dist/SubscriptionService-structs.d.mts.map +1 -1
- package/dist/SubscriptionService-structs.mjs +37 -14
- package/dist/SubscriptionService-structs.mjs.map +1 -1
- package/dist/SubscriptionService.cjs +24 -2
- package/dist/SubscriptionService.cjs.map +1 -1
- package/dist/SubscriptionService.d.cts +5 -1
- package/dist/SubscriptionService.d.cts.map +1 -1
- package/dist/SubscriptionService.d.mts +5 -1
- package/dist/SubscriptionService.d.mts.map +1 -1
- package/dist/SubscriptionService.mjs +24 -2
- package/dist/SubscriptionService.mjs.map +1 -1
- package/dist/constants.cjs +2 -0
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +2 -0
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.mts +2 -0
- package/dist/constants.d.mts.map +1 -1
- package/dist/constants.mjs +2 -0
- package/dist/constants.mjs.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs +27 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +171 -10
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +171 -10
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +26 -0
- package/dist/types.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionController.mjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;AAMA,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAG/E,OAAO,EAAE,eAAe,EAAE,yCAAyC;AAEnE,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EACL,4BAA4B,EAC5B,cAAc,EACd,wBAAwB,EACxB,kCAAkC,EACnC,wBAAuB;AAkBxB,OAAO,EACL,aAAa,EACb,aAAa,EACb,qBAAqB,EACtB,oBAAmB;AA+GpB;;;;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,E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ACnC,uBAAA,IAAI,wFAAuB,MAA3B,IAAI,EAAwB,MAAM,CAAC,CACpC,CAAC;AACJ,CAAC,yGAEsB,YAA0B;IAC/C,MAAM,sBAAsB,GAAG;QAC7B,GAAG,YAAY;QACf,6BAA6B;QAC7B,QAAQ,EAAE,CAAC,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACjD,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAC7B;KACF,CAAC;IAEF,OAAO,IAAI,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import type {\n StateMetadata,\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n controllerName,\n DEFAULT_POLLING_INTERVAL,\n SubscriptionControllerErrorMessage,\n} from './constants.js';\nimport type { SubscriptionControllerMethodActions } from './SubscriptionController-method-action-types.js';\nimport type {\n SubscriptionServiceAssignUserToCohortAction,\n SubscriptionServiceCancelSubscriptionAction,\n SubscriptionServiceGetBillingPortalUrlAction,\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 PAYMENT_TYPES,\n PRODUCT_TYPES,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\nimport type {\n AssignCohortRequest,\n BillingPortalResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n GetSubscriptionsEligibilitiesRequest,\n ProductPrice,\n SubscriptionEligibility,\n StartCryptoSubscriptionRequest,\n SubmitUserEventRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodOpts,\n CachedLastSelectedPaymentMethod,\n SubmitSponsorshipIntentsMethodParams,\n RecurringInterval,\n SubscriptionStatus,\n LinkRewardsRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionResponse,\n CancelSubscriptionRequest,\n} from './types.js';\nimport type {\n PricingResponse,\n ProductType,\n StartSubscriptionRequest,\n Subscription,\n} from './types.js';\n\nexport type SubscriptionControllerState = {\n customerId?: string;\n trialedProducts: ProductType[];\n subscriptions: Subscription[];\n pricing?: PricingResponse;\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?: Record<\n ProductType,\n 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 | 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\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 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 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 'getSubscriptionByProduct',\n 'getSubscriptionsEligibilities',\n 'cancelSubscription',\n 'unCancelSubscription',\n 'startShieldSubscriptionWithCard',\n 'startSubscriptionWithCrypto',\n 'stopAllPolling',\n 'submitShieldSubscriptionCryptoApproval',\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 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\n const {\n customerId: newCustomerId,\n subscriptions: newSubscriptions,\n trialedProducts: newTrialedProducts,\n lastSubscription: newLastSubscription,\n rewardAccountId: newRewardAccountId,\n } = await this.messenger.call('SubscriptionService:getSubscriptions');\n\n // check if the new subscriptions are different from the current subscriptions\n const areSubscriptionsEqual = this.#areSubscriptionsEqual(\n currentSubscriptions,\n newSubscriptions,\n );\n // check if the new trialed products are different from the current trialed products\n const areTrialedProductsEqual = this.#areTrialedProductsEqual(\n currentTrialedProducts,\n newTrialedProducts,\n );\n // check if the new last subscription is different from the current last subscription\n const isLastSubscriptionEqual = this.#isSubscriptionEqual(\n currentLastSubscription,\n newLastSubscription,\n );\n\n const areCustomerIdsEqual = currentCustomerId === newCustomerId;\n const areRewardAccountIdsEqual =\n currentRewardAccountId === newRewardAccountId;\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 if (\n !areSubscriptionsEqual ||\n !isLastSubscriptionEqual ||\n !areTrialedProductsEqual ||\n !areCustomerIdsEqual ||\n !areRewardAccountIdsEqual\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 });\n // trigger access token refresh to ensure the user has the latest access token if subscription state change\n this.triggerAccessTokenRefresh();\n }\n\n return newSubscriptions;\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 * 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 this.triggerAccessTokenRefresh();\n }\n\n async unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<void> {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const uncancelledSubscription = await this.messenger.call(\n 'SubscriptionService:unCancelSubscription',\n {\n subscriptionId: request.subscriptionId,\n },\n );\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...uncancelledSubscription }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCard',\n request,\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 async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n this.#assertIsUserNotSubscribed({ products: request.products });\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCrypto',\n request,\n );\n\n return response;\n }\n\n /**\n * Handles shield subscription crypto approval transactions.\n *\n * @param txMeta - The transaction metadata.\n * @param isSponsored - Whether the transaction is sponsored.\n * @param rewardAccountId - The account ID of the reward subscription to link to the shield subscription.\n * @returns void\n */\n async submitShieldSubscriptionCryptoApproval(\n txMeta: TransactionMeta,\n isSponsored?: boolean,\n rewardAccountId?: CaipAccountId,\n ): Promise<void> {\n if (txMeta.type !== TransactionType.shieldSubscriptionApprove) {\n return;\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, trialedProducts, 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 lastSelectedPaymentMethodShield =\n lastSelectedPaymentMethod[PRODUCT_TYPES.SHIELD];\n this.#assertIsPaymentMethodCrypto(lastSelectedPaymentMethodShield);\n\n const productPrice = this.#getProductPriceByProductAndPlan(\n PRODUCT_TYPES.SHIELD,\n lastSelectedPaymentMethodShield.plan,\n );\n const isTrialed = trialedProducts?.includes(PRODUCT_TYPES.SHIELD);\n // get the latest subscriptions state to check if the user has an active shield subscription\n await this.getSubscriptions();\n const currentSubscription = this.state.subscriptions.find((subscription) =>\n subscription.products.some(\n (product) => product.name === PRODUCT_TYPES.SHIELD,\n ),\n );\n\n this.#assertValidSubscriptionStateForCryptoApproval({\n productType: PRODUCT_TYPES.SHIELD,\n });\n // if shield 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: lastSelectedPaymentMethodShield.paymentTokenSymbol,\n rawTransaction: rawTx as Hex,\n recurringInterval: productPrice.interval,\n billingCycles: productPrice.minBillingCycles,\n });\n } else {\n const params = {\n products: [PRODUCT_TYPES.SHIELD],\n isTrialRequested: !isTrialed,\n recurringInterval: productPrice.interval,\n billingCycles: productPrice.minBillingCycles,\n chainId,\n payerAddress: txMeta.txParams.from as Hex,\n tokenSymbol: lastSelectedPaymentMethodShield.paymentTokenSymbol,\n rawTransaction: rawTx as Hex,\n isSponsored,\n useTestClock: lastSelectedPaymentMethodShield.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();\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 = pricing.paymentMethods.find(\n (paymentMethod) => paymentMethod.type === PAYMENT_TYPES.byCrypto,\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 product - The product to cache the payment method for.\n * @param paymentMethod - The payment method to cache.\n * @param paymentMethod.type - The type of the payment method.\n * @param paymentMethod.paymentTokenAddress - The payment token address.\n * @param paymentMethod.plan - The plan of the payment method.\n * @param paymentMethod.product - The product of the payment method.\n */\n cacheLastSelectedPaymentMethod(\n product: ProductType,\n paymentMethod: CachedLastSelectedPaymentMethod,\n ): void {\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 =\n rest as typeof state.lastSelectedPaymentMethod;\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 otherwise\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 isEligibleForTrialedSponsorship =\n this.#getIsEligibleForTrialedSponsorship(\n request.chainId,\n request.products,\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 /**\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 typeof 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 typeof 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.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 #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 * @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 Required<CachedLastSelectedPaymentMethod> {\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 /**\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 * @returns True if the user is eligible for trialed sponsorship, false otherwise\n */\n #getIsEligibleForTrialedSponsorship(\n chainId: Hex,\n products: ProductType[],\n ): boolean {\n const isSponsorshipSupported = this.#getChainSupportsSponsorship(chainId);\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 #getChainSupportsSponsorship(chainId: Hex): boolean {\n const cryptoPaymentInfo = this.state.pricing?.paymentMethods.find(\n (paymentMethod) => paymentMethod.type === PAYMENT_TYPES.byCrypto,\n );\n\n const isSponsorshipSupported = cryptoPaymentInfo?.chains?.find(\n (chain) => chain.chainId === chainId,\n )?.isSponsorshipSupported;\n return Boolean(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 * 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.mjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;AAMA,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAE/E,OAAO,EAAE,eAAe,EAAE,yCAAyC;AAEnE,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EACL,4BAA4B,EAC5B,cAAc,EACd,wBAAwB,EACxB,kCAAkC,EACnC,wBAAuB;AAkBxB,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,qBAAqB,EACtB,oBAAmB;AAkHpB;;;;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;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E5E,uCAAuC;IACvC,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;QAC3C,MAAM,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,uBAAA,IAAI,sFAAqB,MAAzB,IAAI,EAAsB,MAAM,EAAE,MAAM,CAAC,CAAC;IACnD,CAAC,CAAC,CAAC;AACL,CAAC,qGAEoB,MAAqB,EAAE,MAAqB;IAC/D,yDAAyD;IACzD,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,uBAAA,IAAI,wFAAuB,MAA3B,IAAI,EAAwB,MAAM,CAAC;QACnC,uBAAA,IAAI,wFAAuB,MAA3B,IAAI,EAAwB,MAAM,CAAC,CACpC,CAAC;AACJ,CAAC,yGAEsB,YAA0B;IAC/C,MAAM,sBAAsB,GAAG;QAC7B,GAAG,YAAY;QACf,6BAA6B;QAC7B,QAAQ,EAAE,CAAC,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACjD,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAC7B;KACF,CAAC;IAEF,OAAO,IAAI,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import type {\n StateMetadata,\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { CaipAccountId, Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n controllerName,\n DEFAULT_POLLING_INTERVAL,\n SubscriptionControllerErrorMessage,\n} from './constants.js';\nimport type { SubscriptionControllerMethodActions } from './SubscriptionController-method-action-types.js';\nimport type {\n SubscriptionServiceAssignUserToCohortAction,\n SubscriptionServiceCancelSubscriptionAction,\n SubscriptionServiceGetBillingPortalUrlAction,\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 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} from './types.js';\nimport type {\n PricingResponse,\n ProductType,\n StartSubscriptionRequest,\n Subscription,\n} from './types.js';\n\nexport type SubscriptionControllerState = {\n customerId?: string;\n trialedProducts: ProductType[];\n subscriptions: Subscription[];\n pricing?: PricingResponse;\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 | 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\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 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 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 'getSubscriptionByProduct',\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 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\n const {\n customerId: newCustomerId,\n subscriptions: newSubscriptions,\n trialedProducts: newTrialedProducts,\n lastSubscription: newLastSubscription,\n rewardAccountId: newRewardAccountId,\n } = await this.messenger.call('SubscriptionService:getSubscriptions');\n\n // check if the new subscriptions are different from the current subscriptions\n const areSubscriptionsEqual = this.#areSubscriptionsEqual(\n currentSubscriptions,\n newSubscriptions,\n );\n // check if the new trialed products are different from the current trialed products\n const areTrialedProductsEqual = this.#areTrialedProductsEqual(\n currentTrialedProducts,\n newTrialedProducts,\n );\n // check if the new last subscription is different from the current last subscription\n const isLastSubscriptionEqual = this.#isSubscriptionEqual(\n currentLastSubscription,\n newLastSubscription,\n );\n\n const areCustomerIdsEqual = currentCustomerId === newCustomerId;\n const areRewardAccountIdsEqual =\n currentRewardAccountId === newRewardAccountId;\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 if (\n !areSubscriptionsEqual ||\n !isLastSubscriptionEqual ||\n !areTrialedProductsEqual ||\n !areCustomerIdsEqual ||\n !areRewardAccountIdsEqual\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 });\n // trigger access token refresh to ensure the user has the latest access token if subscription state change\n this.triggerAccessTokenRefresh();\n }\n\n return newSubscriptions;\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 * 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 this.triggerAccessTokenRefresh();\n }\n\n async unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<void> {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const uncancelledSubscription = await this.messenger.call(\n 'SubscriptionService:unCancelSubscription',\n {\n subscriptionId: request.subscriptionId,\n },\n );\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...uncancelledSubscription }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n /**\n * Starts a card-paid subscription checkout session for the requested products\n * (e.g. Shield or Money Account Plus).\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n // get the latest subscriptions state before computing trial eligibility\n await this.getSubscriptions();\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCard',\n {\n ...request,\n isTrialRequested: this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\n ),\n },\n );\n // note: no need to trigger access token refresh after startSubscriptionWithCard request because this only return stripe checkout session url, subscription not created yet\n\n return response;\n }\n\n /**\n * Starts a crypto-paid subscription for the requested products\n * (e.g. Shield or Money Account Plus). Unlike card checkout, this\n * creates the subscription immediately, so local state is refreshed\n * afterwards.\n *\n * `isTrialRequested` on the request is ignored and overwritten from pricing\n * (`trialPeriodDays > 0`) and `trialedProducts`.\n *\n * @param request - The start crypto subscription request.\n * @returns The start crypto subscription response.\n * @throws If `products` is empty.\n */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new Error(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n // get the latest subscriptions state before computing trial eligibility\n await this.getSubscriptions();\n this.#assertIsUserNotSubscribed({ products: request.products });\n const response = await this.messenger.call(\n 'SubscriptionService:startSubscriptionWithCrypto',\n {\n ...request,\n isTrialRequested: this.#getIsTrialRequested(\n request.products,\n request.recurringInterval,\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();\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();\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 =\n rest as typeof state.lastSelectedPaymentMethod;\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 /**\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.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 #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 /**\n * Determines if the user is eligible for trialed sponsorship for the given chain and products.\n * The user is eligible if the chain supports sponsorship and the user has not trialed the provided products before.\n *\n * @param chainId - The chain ID\n * @param products - The products to check eligibility for\n * @param cryptoAuthMethod - The crypto authorization method of the selected payment method\n * @returns True if the user is eligible for trialed sponsorship, false otherwise\n */\n #getIsEligibleForTrialedSponsorship(\n chainId: Hex,\n products: ProductType[],\n cryptoAuthMethod: CryptoAuthMethod,\n ): boolean {\n const isSponsorshipSupported = this.#getChainSupportsSponsorship(\n chainId,\n products[0],\n cryptoAuthMethod,\n );\n\n // verify if the user has trialed the provided products before\n const hasTrialedBefore = this.state.trialedProducts.some((product) =>\n products.includes(product),\n );\n\n return isSponsorshipSupported && !hasTrialedBefore;\n }\n\n /**\n * Whether a trial should be requested for the given products and plan.\n * True only when every product has `trialPeriodDays > 0` and has not\n * already been trialed.\n *\n * @param products - The products to check.\n * @param plan - The recurring interval to look up pricing for.\n * @returns Whether a trial should be requested.\n */\n #getIsTrialRequested(\n products: ProductType[],\n plan: RecurringInterval,\n ): boolean {\n return products.every((productType) => {\n if (this.state.trialedProducts.includes(productType)) {\n return false;\n }\n const productPrice = this.#getProductPriceByProductAndPlan(\n productType,\n plan,\n );\n return productPrice.trialPeriodDays > 0;\n });\n }\n\n #findCryptoPaymentMethod(\n productType: ProductType,\n cryptoAuthMethod: CryptoAuthMethod,\n ): PricingCryptoPaymentMethod | undefined {\n const matches: {\n method: PricingCryptoPaymentMethod;\n explicit: boolean;\n }[] = [];\n\n for (const paymentMethod of this.state.pricing?.paymentMethods ?? []) {\n if (paymentMethod.type !== PAYMENT_TYPES.byCrypto) {\n continue;\n }\n\n const resolved = this.#resolveCryptoPaymentMethodDefaults(paymentMethod);\n if (!resolved) {\n continue;\n }\n\n if (\n resolved.cryptoAuthMethod === cryptoAuthMethod &&\n resolved.products.includes(productType)\n ) {\n matches.push({\n method: paymentMethod,\n explicit: resolved.explicit,\n });\n }\n }\n\n if (matches.length === 0) {\n return undefined;\n }\n\n const explicitMatches = matches.filter((match) => match.explicit);\n const candidates = explicitMatches.length > 0 ? explicitMatches : matches;\n\n if (candidates.length > 1) {\n throw new Error('Multiple matching crypto payment methods found');\n }\n\n return candidates[0].method;\n }\n\n /**\n * Resolves omitted `products` / `cryptoAuthMethod` on a crypto pricing row.\n * Legacy Shield + `erc20_approval` defaults apply only when both fields are\n * absent. If `products` is present, the list must be non-empty and\n * `cryptoAuthMethod` must be explicit; otherwise the row is ignored.\n *\n * @param paymentMethod - The crypto pricing row.\n * @returns Resolved products and auth method, or `undefined` if the row is\n * incomplete.\n */\n #resolveCryptoPaymentMethodDefaults(\n paymentMethod: PricingCryptoPaymentMethod,\n ):\n | {\n products: ProductType[];\n cryptoAuthMethod: CryptoAuthMethod;\n explicit: boolean;\n }\n | undefined {\n const productsPresent = paymentMethod.products !== undefined;\n const authPresent = paymentMethod.cryptoAuthMethod !== undefined;\n\n if (!productsPresent && !authPresent) {\n return {\n products: [PRODUCT_TYPES.SHIELD],\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.ERC20_APPROVAL,\n explicit: false,\n };\n }\n\n if (!paymentMethod.products?.length || !paymentMethod.cryptoAuthMethod) {\n return undefined;\n }\n\n return {\n products: paymentMethod.products,\n cryptoAuthMethod: paymentMethod.cryptoAuthMethod,\n explicit: true,\n };\n }\n\n /**\n * Whether the given chain supports sponsorship for the product and auth method.\n *\n * @param chainId - The chain ID\n * @param productType - The product type\n * @param cryptoAuthMethod - The crypto authorization method to look up\n * @returns True if the chain row has sponsorship enabled, false if it is explicitly not sponsored\n * @throws If the crypto payment method or chain row is missing from pricing\n */\n #getChainSupportsSponsorship(\n chainId: Hex,\n productType: ProductType,\n cryptoAuthMethod: CryptoAuthMethod,\n ): boolean {\n const cryptoPaymentInfo = this.#findCryptoPaymentMethod(\n productType,\n cryptoAuthMethod,\n );\n if (!cryptoPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n\n const chainPaymentInfo = cryptoPaymentInfo.chains?.find(\n (chain) => chain.chainId === chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n return Boolean(chainPaymentInfo.isSponsorshipSupported);\n }\n\n /**\n * Determines whether two trialed products arrays are equal by comparing all products in the arrays.\n *\n * @param oldTrialedProducts - The first trialed products array to compare.\n * @param newTrialedProducts - The second trialed products array to compare.\n * @returns True if the trialed products arrays are equal, false otherwise.\n */\n #areTrialedProductsEqual(\n oldTrialedProducts: ProductType[],\n newTrialedProducts: ProductType[],\n ): boolean {\n return (\n oldTrialedProducts.length === newTrialedProducts?.length &&\n oldTrialedProducts.every((product) =>\n newTrialedProducts?.includes(product),\n )\n );\n }\n\n /**\n * 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-method-action-types.cjs","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionService } from './SubscriptionService.js';\n\n/**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\nexport type SubscriptionServiceGetSubscriptionsAction = {\n type: `SubscriptionService:getSubscriptions`;\n handler: SubscriptionService['getSubscriptions'];\n};\n\n/**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceCancelSubscriptionAction = {\n type: `SubscriptionService:cancelSubscription`;\n handler: SubscriptionService['cancelSubscription'];\n};\n\n/**\n * Reverses a pending subscription cancellation.\n *\n * @param params - The uncancel subscription request.\n * @param params.subscriptionId - The subscription ID to uncancel.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceUnCancelSubscriptionAction = {\n type: `SubscriptionService:unCancelSubscription`;\n handler: SubscriptionService['unCancelSubscription'];\n};\n\n/**\n * Starts a subscription
|
|
1
|
+
{"version":3,"file":"SubscriptionService-method-action-types.cjs","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionService } from './SubscriptionService.js';\n\n/**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\nexport type SubscriptionServiceGetSubscriptionsAction = {\n type: `SubscriptionService:getSubscriptions`;\n handler: SubscriptionService['getSubscriptions'];\n};\n\n/**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceCancelSubscriptionAction = {\n type: `SubscriptionService:cancelSubscription`;\n handler: SubscriptionService['cancelSubscription'];\n};\n\n/**\n * Reverses a pending subscription cancellation.\n *\n * @param params - The uncancel subscription request.\n * @param params.subscriptionId - The subscription ID to uncancel.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceUnCancelSubscriptionAction = {\n type: `SubscriptionService:unCancelSubscription`;\n handler: SubscriptionService['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 * @param request - The start subscription request.\n * @returns The checkout session response.\n */\nexport type SubscriptionServiceStartSubscriptionWithCardAction = {\n type: `SubscriptionService:startSubscriptionWithCard`;\n handler: SubscriptionService['startSubscriptionWithCard'];\n};\n\n/**\n * Starts a subscription with a crypto payment method.\n *\n * @param request - The start crypto subscription request.\n * @returns The created subscription response.\n * @throws If `products` is empty.\n * @throws If the request does not use exactly one of `rawTransaction`\n * (ERC-20 approval) or `delegationHash` (delegation).\n */\nexport type SubscriptionServiceStartSubscriptionWithCryptoAction = {\n type: `SubscriptionService:startSubscriptionWithCrypto`;\n handler: SubscriptionService['startSubscriptionWithCrypto'];\n};\n\n/**\n * Updates a subscription's card payment method.\n *\n * @param request - The update payment method request.\n * @returns The redirect URL response.\n */\nexport type SubscriptionServiceUpdatePaymentMethodCardAction = {\n type: `SubscriptionService:updatePaymentMethodCard`;\n handler: SubscriptionService['updatePaymentMethodCard'];\n};\n\n/**\n * Updates a subscription's crypto payment method.\n *\n * @param request - The update payment method request.\n */\nexport type SubscriptionServiceUpdatePaymentMethodCryptoAction = {\n type: `SubscriptionService:updatePaymentMethodCrypto`;\n handler: SubscriptionService['updatePaymentMethodCrypto'];\n};\n\n/**\n * Get the eligibility for a shield subscription.\n *\n * @param request - Optional request object containing user balance category to check cohort eligibility\n * @returns The eligibility for a shield subscription\n */\nexport type SubscriptionServiceGetSubscriptionsEligibilitiesAction = {\n type: `SubscriptionService:getSubscriptionsEligibilities`;\n handler: SubscriptionService['getSubscriptionsEligibilities'];\n};\n\n/**\n * Submit a user event. (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 SubscriptionServiceSubmitUserEventAction = {\n type: `SubscriptionService:submitUserEvent`;\n handler: SubscriptionService['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 SubscriptionServiceAssignUserToCohortAction = {\n type: `SubscriptionService:assignUserToCohort`;\n handler: SubscriptionService['assignUserToCohort'];\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 { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }\n */\nexport type SubscriptionServiceSubmitSponsorshipIntentsAction = {\n type: `SubscriptionService:submitSponsorshipIntents`;\n handler: SubscriptionService['submitSponsorshipIntents'];\n};\n\n/**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward account ID.\n * @example { rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns The response from the API.\n */\nexport type SubscriptionServiceLinkRewardsAction = {\n type: `SubscriptionService:linkRewards`;\n handler: SubscriptionService['linkRewards'];\n};\n\n/**\n * Fetches subscription pricing information.\n *\n * @returns The pricing response.\n */\nexport type SubscriptionServiceGetPricingAction = {\n type: `SubscriptionService:getPricing`;\n handler: SubscriptionService['getPricing'];\n};\n\n/**\n * Fetches the billing portal URL.\n *\n * @returns The billing portal response.\n */\nexport type SubscriptionServiceGetBillingPortalUrlAction = {\n type: `SubscriptionService:getBillingPortalUrl`;\n handler: SubscriptionService['getBillingPortalUrl'];\n};\n\n/**\n * Union of all SubscriptionService action types.\n */\nexport type SubscriptionServiceMethodActions =\n | SubscriptionServiceGetSubscriptionsAction\n | SubscriptionServiceCancelSubscriptionAction\n | SubscriptionServiceUnCancelSubscriptionAction\n | SubscriptionServiceStartSubscriptionWithCardAction\n | SubscriptionServiceStartSubscriptionWithCryptoAction\n | SubscriptionServiceUpdatePaymentMethodCardAction\n | SubscriptionServiceUpdatePaymentMethodCryptoAction\n | SubscriptionServiceGetSubscriptionsEligibilitiesAction\n | SubscriptionServiceSubmitUserEventAction\n | SubscriptionServiceAssignUserToCohortAction\n | SubscriptionServiceSubmitSponsorshipIntentsAction\n | SubscriptionServiceLinkRewardsAction\n | SubscriptionServiceGetPricingAction\n | SubscriptionServiceGetBillingPortalUrlAction;\n"]}
|
|
@@ -34,7 +34,8 @@ export type SubscriptionServiceUnCancelSubscriptionAction = {
|
|
|
34
34
|
handler: SubscriptionService['unCancelSubscription'];
|
|
35
35
|
};
|
|
36
36
|
/**
|
|
37
|
-
* Starts a subscription
|
|
37
|
+
* Starts a card-paid subscription checkout session for the requested products
|
|
38
|
+
* (e.g. Shield or Money Account Plus).
|
|
38
39
|
*
|
|
39
40
|
* @param request - The start subscription request.
|
|
40
41
|
* @returns The checkout session response.
|
|
@@ -48,6 +49,9 @@ export type SubscriptionServiceStartSubscriptionWithCardAction = {
|
|
|
48
49
|
*
|
|
49
50
|
* @param request - The start crypto subscription request.
|
|
50
51
|
* @returns The created subscription response.
|
|
52
|
+
* @throws If `products` is empty.
|
|
53
|
+
* @throws If the request does not use exactly one of `rawTransaction`
|
|
54
|
+
* (ERC-20 approval) or `delegationHash` (delegation).
|
|
51
55
|
*/
|
|
52
56
|
export type SubscriptionServiceStartSubscriptionWithCryptoAction = {
|
|
53
57
|
type: `SubscriptionService:startSubscriptionWithCrypto`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-method-action-types.d.cts","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAAiC;AAEpE;;;;GAIG;AACH,MAAM,MAAM,yCAAyC,GAAG;IACtD,IAAI,EAAE,sCAAsC,CAAC;IAC7C,OAAO,EAAE,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;CAClD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,mBAAmB,CAAC,oBAAoB,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,mBAAmB,CAAC,sBAAsB,CAAC,CAAC;CACtD,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"SubscriptionService-method-action-types.d.cts","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAAiC;AAEpE;;;;GAIG;AACH,MAAM,MAAM,yCAAyC,GAAG;IACtD,IAAI,EAAE,sCAAsC,CAAC;IAC7C,OAAO,EAAE,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;CAClD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,mBAAmB,CAAC,oBAAoB,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,mBAAmB,CAAC,sBAAsB,CAAC,CAAC;CACtD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;IACtD,OAAO,EAAE,mBAAmB,CAAC,2BAA2B,CAAC,CAAC;CAC3D,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,oDAAoD,GAAG;IACjE,IAAI,EAAE,iDAAiD,CAAC;IACxD,OAAO,EAAE,mBAAmB,CAAC,6BAA6B,CAAC,CAAC;CAC7D,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gDAAgD,GAAG;IAC7D,IAAI,EAAE,6CAA6C,CAAC;IACpD,OAAO,EAAE,mBAAmB,CAAC,yBAAyB,CAAC,CAAC;CACzD,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;IACtD,OAAO,EAAE,mBAAmB,CAAC,2BAA2B,CAAC,CAAC;CA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AAiD,GACjD,oCAAoC,GACpC,mCAAmC,GACnC,4CAA4C,CAAC"}
|
|
@@ -34,7 +34,8 @@ export type SubscriptionServiceUnCancelSubscriptionAction = {
|
|
|
34
34
|
handler: SubscriptionService['unCancelSubscription'];
|
|
35
35
|
};
|
|
36
36
|
/**
|
|
37
|
-
* Starts a subscription
|
|
37
|
+
* Starts a card-paid subscription checkout session for the requested products
|
|
38
|
+
* (e.g. Shield or Money Account Plus).
|
|
38
39
|
*
|
|
39
40
|
* @param request - The start subscription request.
|
|
40
41
|
* @returns The checkout session response.
|
|
@@ -48,6 +49,9 @@ export type SubscriptionServiceStartSubscriptionWithCardAction = {
|
|
|
48
49
|
*
|
|
49
50
|
* @param request - The start crypto subscription request.
|
|
50
51
|
* @returns The created subscription response.
|
|
52
|
+
* @throws If `products` is empty.
|
|
53
|
+
* @throws If the request does not use exactly one of `rawTransaction`
|
|
54
|
+
* (ERC-20 approval) or `delegationHash` (delegation).
|
|
51
55
|
*/
|
|
52
56
|
export type SubscriptionServiceStartSubscriptionWithCryptoAction = {
|
|
53
57
|
type: `SubscriptionService:startSubscriptionWithCrypto`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-method-action-types.d.mts","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAAiC;AAEpE;;;;GAIG;AACH,MAAM,MAAM,yCAAyC,GAAG;IACtD,IAAI,EAAE,sCAAsC,CAAC;IAC7C,OAAO,EAAE,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;CAClD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,mBAAmB,CAAC,oBAAoB,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,mBAAmB,CAAC,sBAAsB,CAAC,CAAC;CACtD,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"SubscriptionService-method-action-types.d.mts","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAAiC;AAEpE;;;;GAIG;AACH,MAAM,MAAM,yCAAyC,GAAG;IACtD,IAAI,EAAE,sCAAsC,CAAC;IAC7C,OAAO,EAAE,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;CAClD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,mBAAmB,CAAC,oBAAoB,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,mBAAmB,CAAC,sBAAsB,CAAC,CAAC;CACtD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;IACtD,OAAO,EAAE,mBAAmB,CAAC,2BAA2B,CAAC,CAAC;CAC3D,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,oDAAoD,GAAG;IACjE,IAAI,EAAE,iDAAiD,CAAC;IACxD,OAAO,EAAE,mBAAmB,CAAC,6BAA6B,CAAC,CAAC;CAC7D,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gDAAgD,GAAG;IAC7D,IAAI,EAAE,6CAA6C,CAAC;IACpD,OAAO,EAAE,mBAAmB,CAAC,yBAAyB,CAAC,CAAC;CACzD,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;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D,GAClD,sDAAsD,GACtD,wCAAwC,GACxC,2CAA2C,GAC3C,iDAAiD,GACjD,oCAAoC,GACpC,mCAAmC,GACnC,4CAA4C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-method-action-types.mjs","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionService } from './SubscriptionService.js';\n\n/**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\nexport type SubscriptionServiceGetSubscriptionsAction = {\n type: `SubscriptionService:getSubscriptions`;\n handler: SubscriptionService['getSubscriptions'];\n};\n\n/**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceCancelSubscriptionAction = {\n type: `SubscriptionService:cancelSubscription`;\n handler: SubscriptionService['cancelSubscription'];\n};\n\n/**\n * Reverses a pending subscription cancellation.\n *\n * @param params - The uncancel subscription request.\n * @param params.subscriptionId - The subscription ID to uncancel.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceUnCancelSubscriptionAction = {\n type: `SubscriptionService:unCancelSubscription`;\n handler: SubscriptionService['unCancelSubscription'];\n};\n\n/**\n * Starts a subscription
|
|
1
|
+
{"version":3,"file":"SubscriptionService-method-action-types.mjs","sourceRoot":"","sources":["../src/SubscriptionService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionService } from './SubscriptionService.js';\n\n/**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\nexport type SubscriptionServiceGetSubscriptionsAction = {\n type: `SubscriptionService:getSubscriptions`;\n handler: SubscriptionService['getSubscriptions'];\n};\n\n/**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceCancelSubscriptionAction = {\n type: `SubscriptionService:cancelSubscription`;\n handler: SubscriptionService['cancelSubscription'];\n};\n\n/**\n * Reverses a pending subscription cancellation.\n *\n * @param params - The uncancel subscription request.\n * @param params.subscriptionId - The subscription ID to uncancel.\n * @returns The updated subscription.\n */\nexport type SubscriptionServiceUnCancelSubscriptionAction = {\n type: `SubscriptionService:unCancelSubscription`;\n handler: SubscriptionService['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 * @param request - The start subscription request.\n * @returns The checkout session response.\n */\nexport type SubscriptionServiceStartSubscriptionWithCardAction = {\n type: `SubscriptionService:startSubscriptionWithCard`;\n handler: SubscriptionService['startSubscriptionWithCard'];\n};\n\n/**\n * Starts a subscription with a crypto payment method.\n *\n * @param request - The start crypto subscription request.\n * @returns The created subscription response.\n * @throws If `products` is empty.\n * @throws If the request does not use exactly one of `rawTransaction`\n * (ERC-20 approval) or `delegationHash` (delegation).\n */\nexport type SubscriptionServiceStartSubscriptionWithCryptoAction = {\n type: `SubscriptionService:startSubscriptionWithCrypto`;\n handler: SubscriptionService['startSubscriptionWithCrypto'];\n};\n\n/**\n * Updates a subscription's card payment method.\n *\n * @param request - The update payment method request.\n * @returns The redirect URL response.\n */\nexport type SubscriptionServiceUpdatePaymentMethodCardAction = {\n type: `SubscriptionService:updatePaymentMethodCard`;\n handler: SubscriptionService['updatePaymentMethodCard'];\n};\n\n/**\n * Updates a subscription's crypto payment method.\n *\n * @param request - The update payment method request.\n */\nexport type SubscriptionServiceUpdatePaymentMethodCryptoAction = {\n type: `SubscriptionService:updatePaymentMethodCrypto`;\n handler: SubscriptionService['updatePaymentMethodCrypto'];\n};\n\n/**\n * Get the eligibility for a shield subscription.\n *\n * @param request - Optional request object containing user balance category to check cohort eligibility\n * @returns The eligibility for a shield subscription\n */\nexport type SubscriptionServiceGetSubscriptionsEligibilitiesAction = {\n type: `SubscriptionService:getSubscriptionsEligibilities`;\n handler: SubscriptionService['getSubscriptionsEligibilities'];\n};\n\n/**\n * Submit a user event. (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 SubscriptionServiceSubmitUserEventAction = {\n type: `SubscriptionService:submitUserEvent`;\n handler: SubscriptionService['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 SubscriptionServiceAssignUserToCohortAction = {\n type: `SubscriptionService:assignUserToCohort`;\n handler: SubscriptionService['assignUserToCohort'];\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 { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }\n */\nexport type SubscriptionServiceSubmitSponsorshipIntentsAction = {\n type: `SubscriptionService:submitSponsorshipIntents`;\n handler: SubscriptionService['submitSponsorshipIntents'];\n};\n\n/**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward account ID.\n * @example { rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns The response from the API.\n */\nexport type SubscriptionServiceLinkRewardsAction = {\n type: `SubscriptionService:linkRewards`;\n handler: SubscriptionService['linkRewards'];\n};\n\n/**\n * Fetches subscription pricing information.\n *\n * @returns The pricing response.\n */\nexport type SubscriptionServiceGetPricingAction = {\n type: `SubscriptionService:getPricing`;\n handler: SubscriptionService['getPricing'];\n};\n\n/**\n * Fetches the billing portal URL.\n *\n * @returns The billing portal response.\n */\nexport type SubscriptionServiceGetBillingPortalUrlAction = {\n type: `SubscriptionService:getBillingPortalUrl`;\n handler: SubscriptionService['getBillingPortalUrl'];\n};\n\n/**\n * Union of all SubscriptionService action types.\n */\nexport type SubscriptionServiceMethodActions =\n | SubscriptionServiceGetSubscriptionsAction\n | SubscriptionServiceCancelSubscriptionAction\n | SubscriptionServiceUnCancelSubscriptionAction\n | SubscriptionServiceStartSubscriptionWithCardAction\n | SubscriptionServiceStartSubscriptionWithCryptoAction\n | SubscriptionServiceUpdatePaymentMethodCardAction\n | SubscriptionServiceUpdatePaymentMethodCryptoAction\n | SubscriptionServiceGetSubscriptionsEligibilitiesAction\n | SubscriptionServiceSubmitUserEventAction\n | SubscriptionServiceAssignUserToCohortAction\n | SubscriptionServiceSubmitSponsorshipIntentsAction\n | SubscriptionServiceLinkRewardsAction\n | SubscriptionServiceGetPricingAction\n | SubscriptionServiceGetBillingPortalUrlAction;\n"]}
|
|
@@ -5,7 +5,7 @@ const superstruct_1 = require("@metamask/superstruct");
|
|
|
5
5
|
const utils_1 = require("@metamask/utils");
|
|
6
6
|
const types_js_1 = require("./types.cjs");
|
|
7
7
|
const ProductTypeStruct = (0, superstruct_1.enums)(Object.values(types_js_1.PRODUCT_TYPES));
|
|
8
|
-
const
|
|
8
|
+
const CryptoAuthMethodStruct = (0, superstruct_1.enums)(Object.values(types_js_1.CRYPTO_AUTH_METHODS));
|
|
9
9
|
const RecurringIntervalStruct = (0, superstruct_1.enums)(Object.values(types_js_1.RECURRING_INTERVALS));
|
|
10
10
|
const SubscriptionStatusStruct = (0, superstruct_1.enums)(Object.values(types_js_1.SUBSCRIPTION_STATUSES));
|
|
11
11
|
const CancelTypeStruct = (0, superstruct_1.enums)(Object.values(types_js_1.CANCEL_TYPES));
|
|
@@ -93,24 +93,47 @@ const ProductPricingStruct = (0, superstruct_1.type)({
|
|
|
93
93
|
name: ProductTypeStruct,
|
|
94
94
|
prices: (0, superstruct_1.array)(ProductPriceStruct),
|
|
95
95
|
});
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
96
|
+
const TokenPaymentInfoConversionRateStruct = (0, superstruct_1.type)({
|
|
97
|
+
usd: (0, superstruct_1.string)(),
|
|
98
|
+
});
|
|
99
|
+
const TokenPaymentInfoStruct = (0, superstruct_1.lazy)(() => (0, superstruct_1.union)([
|
|
100
|
+
(0, superstruct_1.object)({
|
|
101
|
+
symbol: (0, superstruct_1.string)(),
|
|
102
|
+
address: utils_1.StrictHexStruct,
|
|
103
|
+
decimals: (0, superstruct_1.number)(),
|
|
104
|
+
conversionRate: (0, superstruct_1.optional)(TokenPaymentInfoConversionRateStruct),
|
|
105
|
+
isVaultShare: (0, superstruct_1.literal)(true),
|
|
106
|
+
accountantAddress: utils_1.StrictHexStruct,
|
|
107
|
+
sources: (0, superstruct_1.optional)((0, superstruct_1.array)(TokenPaymentInfoStruct)),
|
|
102
108
|
}),
|
|
103
|
-
|
|
109
|
+
(0, superstruct_1.object)({
|
|
110
|
+
symbol: (0, superstruct_1.string)(),
|
|
111
|
+
address: utils_1.StrictHexStruct,
|
|
112
|
+
decimals: (0, superstruct_1.number)(),
|
|
113
|
+
conversionRate: (0, superstruct_1.optional)(TokenPaymentInfoConversionRateStruct),
|
|
114
|
+
isVaultShare: (0, superstruct_1.optional)((0, superstruct_1.literal)(false)),
|
|
115
|
+
sources: (0, superstruct_1.optional)((0, superstruct_1.array)(TokenPaymentInfoStruct)),
|
|
116
|
+
}),
|
|
117
|
+
]));
|
|
104
118
|
const ChainPaymentInfoStruct = (0, superstruct_1.type)({
|
|
105
119
|
chainId: utils_1.StrictHexStruct,
|
|
106
120
|
paymentAddress: utils_1.StrictHexStruct,
|
|
121
|
+
delegateAddress: (0, superstruct_1.optional)(utils_1.StrictHexStruct),
|
|
107
122
|
tokens: (0, superstruct_1.array)(TokenPaymentInfoStruct),
|
|
108
123
|
isSponsorshipSupported: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
|
|
109
124
|
});
|
|
110
|
-
const PricingPaymentMethodStruct = (0, superstruct_1.
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
125
|
+
const PricingPaymentMethodStruct = (0, superstruct_1.union)([
|
|
126
|
+
(0, superstruct_1.object)({
|
|
127
|
+
type: (0, superstruct_1.enums)([types_js_1.PAYMENT_TYPES.byCard]),
|
|
128
|
+
products: (0, superstruct_1.optional)((0, superstruct_1.array)(ProductTypeStruct)),
|
|
129
|
+
}),
|
|
130
|
+
(0, superstruct_1.object)({
|
|
131
|
+
type: (0, superstruct_1.enums)([types_js_1.PAYMENT_TYPES.byCrypto]),
|
|
132
|
+
cryptoAuthMethod: (0, superstruct_1.optional)(CryptoAuthMethodStruct),
|
|
133
|
+
products: (0, superstruct_1.optional)((0, superstruct_1.array)(ProductTypeStruct)),
|
|
134
|
+
chains: (0, superstruct_1.optional)((0, superstruct_1.array)(ChainPaymentInfoStruct)),
|
|
135
|
+
}),
|
|
136
|
+
]);
|
|
114
137
|
exports.PricingResponseStruct = (0, superstruct_1.type)({
|
|
115
138
|
products: (0, superstruct_1.array)(ProductPricingStruct),
|
|
116
139
|
paymentMethods: (0, superstruct_1.array)(PricingPaymentMethodStruct),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-structs.cjs","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":";;;AAAA,uDAU+B;AAC/B,2CAAuE;AAEvE,0CAOoB;AAEpB,MAAM,iBAAiB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,wBAAa,CAAC,CAAC,CAAC;AAC9D,MAAM,iBAAiB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,wBAAa,CAAC,CAAC,CAAC;AAC9D,MAAM,uBAAuB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,8BAAmB,CAAC,CAAC,CAAC;AAC1E,MAAM,wBAAwB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,gCAAqB,CAAC,CAAC,CAAC;AAC7E,MAAM,gBAAgB,GAAG,IAAA,mBAAK,EAAC,MAA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C;IAC5C,UAAU,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;IAC9B,wBAAwB,EAAE,IAAA,sBAAQ,EAAC,IAAA,qBAAO,GAAE,CAAC;CAC9C,CAAC,CAAC;AAEU,QAAA,kCAAkC,GAAG,IAAA,mBAAK,EACrD,qCAA6B,CAC9B,CAAC","sourcesContent":["import {\n array,\n boolean,\n enums,\n nullable,\n number,\n optional,\n string,\n type,\n union,\n} from '@metamask/superstruct';\nimport { StrictHexStruct, CaipAccountIdStruct } from '@metamask/utils';\n\nimport {\n CANCEL_TYPES,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\n\nconst ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));\nconst PaymentTypeStruct = enums(Object.values(PAYMENT_TYPES));\nconst RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));\nconst SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));\nconst CancelTypeStruct = enums(Object.values(CANCEL_TYPES));\nconst CryptoPaymentMethodErrorStruct = enums(\n Object.values(CRYPTO_PAYMENT_METHOD_ERRORS),\n);\n\nconst ProductStruct = type({\n name: ProductTypeStruct,\n currency: enums(['usd']),\n unitAmount: number(),\n unitDecimals: number(),\n});\n\nconst SubscriptionCardPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCard]),\n card: type({\n brand: string(),\n displayBrand: string(),\n last4: string(),\n }),\n});\n\nconst SubscriptionCryptoPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCrypto]),\n crypto: type({\n payerAddress: StrictHexStruct,\n chainId: StrictHexStruct,\n tokenSymbol: string(),\n error: optional(CryptoPaymentMethodErrorStruct),\n }),\n});\n\nconst SubscriptionPaymentMethodStruct = union([\n SubscriptionCardPaymentMethodStruct,\n SubscriptionCryptoPaymentMethodStruct,\n]);\n\nexport const SubscriptionStruct = type({\n id: string(),\n products: array(ProductStruct),\n currentPeriodStart: string(),\n currentPeriodEnd: string(),\n cancelAtPeriodEnd: optional(boolean()),\n status: SubscriptionStatusStruct,\n interval: RecurringIntervalStruct,\n paymentMethod: SubscriptionPaymentMethodStruct,\n trialPeriodDays: optional(number()),\n trialStart: optional(string()),\n trialEnd: optional(string()),\n endDate: optional(string()),\n canceledAt: optional(string()),\n cancelType: CancelTypeStruct,\n inactiveAt: optional(string()),\n isEligibleForSupport: boolean(),\n billingCycles: optional(number()),\n});\n\nexport const GetSubscriptionsResponseStruct = type({\n customerId: optional(string()),\n subscriptions: array(SubscriptionStruct),\n trialedProducts: array(ProductTypeStruct),\n lastSubscription: optional(SubscriptionStruct),\n rewardAccountId: optional(CaipAccountIdStruct),\n});\n\nexport const StartSubscriptionResponseStruct = type({\n checkoutSessionUrl: string(),\n});\n\nexport const StartCryptoSubscriptionResponseStruct = type({\n subscriptionId: string(),\n status: SubscriptionStatusStruct,\n});\n\nexport const UpdatePaymentMethodCardResponseStruct = type({\n redirectUrl: string(),\n});\n\nexport const BillingPortalResponseStruct = type({\n url: string(),\n});\n\nexport const SubscriptionApiGeneralResponseStruct = type({\n success: boolean(),\n message: optional(string()),\n});\n\nconst ProductPriceStruct = type({\n interval: RecurringIntervalStruct,\n unitAmount: number(),\n unitDecimals: number(),\n currency: enums(['usd']),\n trialPeriodDays: number(),\n minBillingCycles: number(),\n minBillingCyclesForBalance: number(),\n});\n\nconst ProductPricingStruct = type({\n name: ProductTypeStruct,\n prices: array(ProductPriceStruct),\n});\n\nconst TokenPaymentInfoStruct = type({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: type({\n usd: string(),\n }),\n});\n\nconst ChainPaymentInfoStruct = type({\n chainId: StrictHexStruct,\n paymentAddress: StrictHexStruct,\n tokens: array(TokenPaymentInfoStruct),\n isSponsorshipSupported: optional(boolean()),\n});\n\nconst PricingPaymentMethodStruct = type({\n type: PaymentTypeStruct,\n chains: optional(array(ChainPaymentInfoStruct)),\n});\n\nexport const PricingResponseStruct = type({\n products: array(ProductPricingStruct),\n paymentMethods: array(PricingPaymentMethodStruct),\n});\n\nconst CohortStruct = type({\n cohort: string(),\n eligibilityRate: number(),\n priority: number(),\n eligible: boolean(),\n});\n\nexport const SubscriptionEligibilityStruct = type({\n product: ProductTypeStruct,\n canSubscribe: optional(boolean()),\n canViewEntryModal: optional(boolean()),\n modalType: optional(enums(['A', 'B'])),\n cohorts: optional(array(CohortStruct)),\n assignedCohort: optional(nullable(string())),\n assignedAt: optional(string()),\n hasAssignedCohortExpired: optional(boolean()),\n});\n\nexport const SubscriptionEligibilityArrayStruct = array(\n SubscriptionEligibilityStruct,\n);\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionService-structs.cjs","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":";;;AAAA,uDAa+B;AAE/B,2CAAuE;AAEvE,0CAQoB;AAGpB,MAAM,iBAAiB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,wBAAa,CAAC,CAAC,CAAC;AAC9D,MAAM,sBAAsB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,8BAAmB,CAAC,CAAC,CAAC;AACzE,MAAM,uBAAuB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,8BAAmB,CAAC,CAAC,CAAC;AAC1E,MAAM,wBAAwB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,gCAAqB,CAAC,CAAC,CAAC;AAC7E,MAAM,gBAAgB,GAAG,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,uBAAY,CAAC,CAAC,CAAC;AAC5D,MAAM,8BAA8B,GAAG,IAAA,mBAAK,EAC1C,MAAM,CAAC,MAAM,CAAC,uCAA4B,CAAC,CAC5C,CAAC;AAEF,MAAM,aAAa,GAAG,IAAA,kBAAI,EAAC;IACzB,I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superstruct';\nimport type { Struct } from '@metamask/superstruct';\nimport { StrictHexStruct, CaipAccountIdStruct } from '@metamask/utils';\n\nimport {\n CANCEL_TYPES,\n CRYPTO_AUTH_METHODS,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\nimport type { TokenPaymentInfo } from './types.js';\n\nconst ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));\nconst CryptoAuthMethodStruct = enums(Object.values(CRYPTO_AUTH_METHODS));\nconst RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));\nconst SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));\nconst CancelTypeStruct = enums(Object.values(CANCEL_TYPES));\nconst CryptoPaymentMethodErrorStruct = enums(\n Object.values(CRYPTO_PAYMENT_METHOD_ERRORS),\n);\n\nconst ProductStruct = type({\n name: ProductTypeStruct,\n currency: enums(['usd']),\n unitAmount: number(),\n unitDecimals: number(),\n});\n\nconst SubscriptionCardPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCard]),\n card: type({\n brand: string(),\n displayBrand: string(),\n last4: string(),\n }),\n});\n\nconst SubscriptionCryptoPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCrypto]),\n crypto: type({\n payerAddress: StrictHexStruct,\n chainId: StrictHexStruct,\n tokenSymbol: string(),\n error: optional(CryptoPaymentMethodErrorStruct),\n }),\n});\n\nconst SubscriptionPaymentMethodStruct = union([\n SubscriptionCardPaymentMethodStruct,\n SubscriptionCryptoPaymentMethodStruct,\n]);\n\nexport const SubscriptionStruct = type({\n id: string(),\n products: array(ProductStruct),\n currentPeriodStart: string(),\n currentPeriodEnd: string(),\n cancelAtPeriodEnd: optional(boolean()),\n status: SubscriptionStatusStruct,\n interval: RecurringIntervalStruct,\n paymentMethod: SubscriptionPaymentMethodStruct,\n trialPeriodDays: optional(number()),\n trialStart: optional(string()),\n trialEnd: optional(string()),\n endDate: optional(string()),\n canceledAt: optional(string()),\n cancelType: CancelTypeStruct,\n inactiveAt: optional(string()),\n isEligibleForSupport: boolean(),\n billingCycles: optional(number()),\n});\n\nexport const GetSubscriptionsResponseStruct = type({\n customerId: optional(string()),\n subscriptions: array(SubscriptionStruct),\n trialedProducts: array(ProductTypeStruct),\n lastSubscription: optional(SubscriptionStruct),\n rewardAccountId: optional(CaipAccountIdStruct),\n});\n\nexport const StartSubscriptionResponseStruct = type({\n checkoutSessionUrl: string(),\n});\n\nexport const StartCryptoSubscriptionResponseStruct = type({\n subscriptionId: string(),\n status: SubscriptionStatusStruct,\n});\n\nexport const UpdatePaymentMethodCardResponseStruct = type({\n redirectUrl: string(),\n});\n\nexport const BillingPortalResponseStruct = type({\n url: string(),\n});\n\nexport const SubscriptionApiGeneralResponseStruct = type({\n success: boolean(),\n message: optional(string()),\n});\n\nconst ProductPriceStruct = type({\n interval: RecurringIntervalStruct,\n unitAmount: number(),\n unitDecimals: number(),\n currency: enums(['usd']),\n trialPeriodDays: number(),\n minBillingCycles: number(),\n minBillingCyclesForBalance: number(),\n});\n\nconst ProductPricingStruct = type({\n name: ProductTypeStruct,\n prices: array(ProductPriceStruct),\n});\n\nconst TokenPaymentInfoConversionRateStruct = type({\n usd: string(),\n});\n\nconst TokenPaymentInfoStruct: Struct<TokenPaymentInfo> = lazy(() =>\n union([\n object({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: optional(TokenPaymentInfoConversionRateStruct),\n isVaultShare: literal(true),\n accountantAddress: StrictHexStruct,\n sources: optional(array(TokenPaymentInfoStruct)),\n }),\n object({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: optional(TokenPaymentInfoConversionRateStruct),\n isVaultShare: optional(literal(false)),\n sources: optional(array(TokenPaymentInfoStruct)),\n }),\n ]),\n) as Struct<TokenPaymentInfo>;\n\nconst ChainPaymentInfoStruct = type({\n chainId: StrictHexStruct,\n paymentAddress: StrictHexStruct,\n delegateAddress: optional(StrictHexStruct),\n tokens: array(TokenPaymentInfoStruct),\n isSponsorshipSupported: optional(boolean()),\n});\n\nconst PricingPaymentMethodStruct = union([\n object({\n type: enums([PAYMENT_TYPES.byCard]),\n products: optional(array(ProductTypeStruct)),\n }),\n object({\n type: enums([PAYMENT_TYPES.byCrypto]),\n cryptoAuthMethod: optional(CryptoAuthMethodStruct),\n products: optional(array(ProductTypeStruct)),\n chains: optional(array(ChainPaymentInfoStruct)),\n }),\n]);\n\nexport const PricingResponseStruct = type({\n products: array(ProductPricingStruct),\n paymentMethods: array(PricingPaymentMethodStruct),\n});\n\nconst CohortStruct = type({\n cohort: string(),\n eligibilityRate: number(),\n priority: number(),\n eligible: boolean(),\n});\n\nexport const SubscriptionEligibilityStruct = type({\n product: ProductTypeStruct,\n canSubscribe: optional(boolean()),\n canViewEntryModal: optional(boolean()),\n modalType: optional(enums(['A', 'B'])),\n cohorts: optional(array(CohortStruct)),\n assignedCohort: optional(nullable(string())),\n assignedAt: optional(string()),\n hasAssignedCohortExpired: optional(boolean()),\n});\n\nexport const SubscriptionEligibilityArrayStruct = array(\n SubscriptionEligibilityStruct,\n);\n"]}
|