@metamask/subscription-controller 10.0.1 → 12.0.0
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 +57 -1
- package/dist/SubscriptionController-method-action-types.d.ts +17 -1
- package/dist/SubscriptionController-method-action-types.d.ts.map +1 -1
- package/dist/SubscriptionController-method-action-types.js.map +1 -1
- package/dist/SubscriptionController.d.ts +15 -1
- package/dist/SubscriptionController.d.ts.map +1 -1
- package/dist/SubscriptionController.js +41 -5
- package/dist/SubscriptionController.js.map +1 -1
- package/dist/SubscriptionService-method-action-types.d.ts +2 -1
- package/dist/SubscriptionService-method-action-types.d.ts.map +1 -1
- package/dist/SubscriptionService-method-action-types.js.map +1 -1
- package/dist/SubscriptionService-structs.d.ts +33 -47
- package/dist/SubscriptionService-structs.d.ts.map +1 -1
- package/dist/SubscriptionService-structs.js +2 -6
- package/dist/SubscriptionService-structs.js.map +1 -1
- package/dist/SubscriptionService.d.ts +2 -1
- package/dist/SubscriptionService.d.ts.map +1 -1
- package/dist/SubscriptionService.js +4 -3
- package/dist/SubscriptionService.js.map +1 -1
- package/dist/constants.d.ts +8 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +7 -0
- package/dist/constants.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts +29 -5
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts +33 -11
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService.js +305 -22
- package/dist/subscription-delegation/SubscriptionDelegationService.js.map +1 -1
- package/dist/subscription-delegation/caveats.d.ts +31 -2
- package/dist/subscription-delegation/caveats.d.ts.map +1 -1
- package/dist/subscription-delegation/caveats.js +49 -9
- package/dist/subscription-delegation/caveats.js.map +1 -1
- package/dist/subscription-delegation/fingerprint.d.ts +1 -0
- package/dist/subscription-delegation/fingerprint.d.ts.map +1 -1
- package/dist/subscription-delegation/fingerprint.js +10 -6
- package/dist/subscription-delegation/fingerprint.js.map +1 -1
- package/dist/subscription-delegation/typed-data.d.ts +23 -0
- package/dist/subscription-delegation/typed-data.d.ts.map +1 -0
- package/dist/subscription-delegation/typed-data.js +75 -0
- package/dist/subscription-delegation/typed-data.js.map +1 -0
- package/dist/subscription-delegation/types.d.ts +105 -12
- package/dist/subscription-delegation/types.d.ts.map +1 -1
- package/dist/subscription-delegation/types.js +3 -4
- package/dist/subscription-delegation/types.js.map +1 -1
- package/dist/types.d.ts +15 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/package.json +19 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService.js","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAE9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAGnE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAI/C,OAAO,EACL,GAAG,EACH,UAAU,EACV,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,EAChC,wBAAwB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEhE,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,qBAAqB,EACrB,qCAAqC,EACrC,+BAA+B,EAC/B,oCAAoC,EACpC,kCAAkC,EAClC,kCAA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,CACF,CAAC;YAEF,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { BaseDataService } from '@metamask/base-data-service';\nimport type { CreateServicePolicyOptions } from '@metamask/controller-utils';\nimport { handleWhen, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { create } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport {\n Env,\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n SubscriptionServiceErrorMessage,\n} from './constants.js';\nimport {\n createSentryError,\n getSubscriptionErrorFromResponse,\n SubscriptionServiceError,\n} from './errors.js';\nimport { createModuleLogger, projectLogger } from './logger.js';\nimport type { SubscriptionServiceMethodActions } from './SubscriptionService-method-action-types.js';\nimport {\n BillingPortalResponseStruct,\n GetSubscriptionsResponseStruct,\n PricingResponseStruct,\n StartCryptoSubscriptionResponseStruct,\n StartSubscriptionResponseStruct,\n SubscriptionApiGeneralResponseStruct,\n SubscriptionBenefitsResponseStruct,\n SubscriptionEligibilityArrayStruct,\n SubscriptionStruct,\n UpdatePaymentMethodCardResponseStruct,\n} from './SubscriptionService-structs.js';\nimport { CRYPTO_AUTH_METHODS } from './types.js';\nimport type {\n AssignCohortRequest,\n BillingPortalResponse,\n CancelSubscriptionRequest,\n GetSubscriptionsEligibilitiesRequest,\n GetSubscriptionsResponse,\n LinkRewardsRequest,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n SubmitSponsorshipIntentsRequest,\n SubmitUserEventRequest,\n Subscription,\n SubscriptionApiGeneralResponse,\n SubscriptionBenefitsResponse,\n SubscriptionEligibility,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodCryptoRequest,\n} from './types.js';\n\nexport const serviceName = 'SubscriptionService';\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string): string =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getSubscriptions',\n 'getBenefits',\n 'cancelSubscription',\n 'unCancelSubscription',\n 'startSubscriptionWithCard',\n 'startSubscriptionWithCrypto',\n 'updatePaymentMethodCard',\n 'updatePaymentMethodCrypto',\n 'getSubscriptionsEligibilities',\n 'submitUserEvent',\n 'assignUserToCohort',\n 'submitSponsorshipIntents',\n 'linkRewards',\n 'getPricing',\n 'getBillingPortalUrl',\n] as const;\n\nexport type SubscriptionServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\nexport type SubscriptionServiceActions =\n | SubscriptionServiceMethodActions\n | SubscriptionServiceInvalidateQueriesAction;\n\ntype AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerGetSessionProfileAction;\n\ntype AllowedEvents = never;\n\nexport type SubscriptionServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\nexport type SubscriptionServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\nexport type SubscriptionServiceEvents =\n | SubscriptionServiceCacheUpdatedEvent\n | SubscriptionServiceGranularCacheUpdatedEvent;\n\nexport type SubscriptionServiceMessenger = Messenger<\n typeof serviceName,\n SubscriptionServiceActions | AllowedActions,\n SubscriptionServiceEvents | AllowedEvents\n>;\n\nexport type SubscriptionServiceOptions = {\n messenger: SubscriptionServiceMessenger;\n /**\n * The `fetch` function to use for requests. Defaults to the global `fetch`.\n */\n fetchFunction?: typeof fetch;\n env?: Env;\n captureException?: (error: Error) => void;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n};\n\nconst log = createModuleLogger(projectLogger, 'SubscriptionService');\n\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof HttpError) {\n if (error.httpStatus === 429) {\n return true;\n }\n return error.httpStatus < 400 || error.httpStatus >= 500;\n }\n return true;\n}\n\nconst DEFAULT_POLICY_OPTIONS: CreateServicePolicyOptions = {\n retryFilterPolicy: handleWhen(isRetryableError),\n};\n\n/**\n * Data service for the Subscription API.\n *\n * All requests are authenticated via JWT Bearer tokens obtained from the\n * `AuthenticationController:getBearerToken` messenger action. Cached queries\n * are scoped by `profileId` from\n * `AuthenticationController:getSessionProfile`.\n */\nexport class SubscriptionService extends BaseDataService<\n typeof serviceName,\n SubscriptionServiceMessenger\n> {\n readonly #env: Env;\n\n readonly #fetch: typeof fetch;\n\n readonly #captureException?: (error: Error) => void;\n\n constructor({\n messenger,\n fetchFunction = globalThis.fetch,\n env = Env.PRD,\n captureException,\n queryClientConfig = {},\n policyOptions = {},\n }: SubscriptionServiceOptions) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions: { ...DEFAULT_POLICY_OPTIONS, ...policyOptions },\n });\n\n this.#env = env;\n this.#fetch = fetchFunction;\n this.#captureException = captureException;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getSubscriptions',\n requestParams: null,\n path: 'subscriptions',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptions,\n });\n\n return create(jsonResponse, GetSubscriptionsResponseStruct);\n }\n\n /**\n * Fetches the user's subscription benefits.\n *\n * @returns The benefits response.\n */\n async getBenefits(): Promise<SubscriptionBenefitsResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getBenefits',\n requestParams: null,\n path: 'benefits',\n method: 'POST',\n body: {},\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetBenefits,\n });\n\n return create(jsonResponse, SubscriptionBenefitsResponseStruct);\n }\n\n /**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\n async cancelSubscription(\n params: CancelSubscriptionRequest,\n ): Promise<Subscription> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'cancelSubscription',\n requestParams: {\n subscriptionId: params.subscriptionId,\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\n cancellationReason: params.cancellationReason,\n },\n path,\n method: 'POST',\n body: {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\n cancellationReason: params.cancellationReason,\n cancellationFeedback: params.cancellationFeedback,\n },\n errorMessage: SubscriptionServiceErrorMessage.FailedToCancelSubscription,\n });\n\n return create(jsonResponse, SubscriptionStruct);\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 */\n async unCancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${params.subscriptionId}/uncancel`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'unCancelSubscription',\n requestParams: params,\n path,\n method: 'POST',\n body: {},\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUncancelSubscription,\n });\n\n return create(jsonResponse, SubscriptionStruct);\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 */\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'startSubscriptionWithCard',\n requestParams: request,\n path: 'subscriptions/card',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,\n });\n\n return create(jsonResponse, StartSubscriptionResponseStruct);\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 */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n this.#assertValidCryptoAuthCombo(request);\n\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'startSubscriptionWithCrypto',\n requestParams: request,\n path: 'subscriptions/crypto',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,\n });\n\n return create(jsonResponse, StartCryptoSubscriptionResponseStruct);\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 */\n async updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<UpdatePaymentMethodCardResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'updatePaymentMethodCard',\n requestParams: request,\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,\n });\n\n return create(jsonResponse, UpdatePaymentMethodCardResponseStruct);\n }\n\n /**\n * Updates a subscription's crypto payment method.\n *\n * @param request - The update payment method request.\n */\n async updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'updatePaymentMethodCrypto',\n requestParams: request,\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCrypto,\n });\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 */\n async getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n let queryParams: Record<string, string> | undefined;\n if (request?.balanceCategory !== undefined) {\n queryParams = { balanceCategory: request.balanceCategory };\n }\n\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getSubscriptionsEligibilities',\n requestParams: request ?? null,\n path: 'subscriptions/eligibility',\n queryParams,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,\n });\n\n const results = create(jsonResponse, SubscriptionEligibilityArrayStruct);\n\n return results.map((result) => ({\n ...result,\n canSubscribe: result.canSubscribe ?? false,\n canViewEntryModal: result.canViewEntryModal ?? false,\n cohorts: result.cohorts ?? [],\n assignedCohort: result.assignedCohort ?? null,\n hasAssignedCohortExpired: result.hasAssignedCohortExpired ?? false,\n }));\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 */\n async submitUserEvent(request: SubmitUserEventRequest): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'submitUserEvent',\n requestParams: request,\n path: 'user-events',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,\n });\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 const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'assignUserToCohort',\n requestParams: request,\n path: 'cohorts/assign',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,\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 { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }\n */\n async submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsRequest,\n ): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'submitSponsorshipIntents',\n requestParams: request,\n path: 'transaction-sponsorship/intents',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,\n });\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 */\n async linkRewards(\n request: LinkRewardsRequest,\n ): Promise<SubscriptionApiGeneralResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'linkRewards',\n requestParams: request,\n path: 'rewards/link',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToLinkRewards,\n });\n\n return create(jsonResponse, SubscriptionApiGeneralResponseStruct);\n }\n\n /**\n * Fetches subscription pricing information.\n *\n * @returns The pricing response.\n */\n async getPricing(): Promise<PricingResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getPricing',\n requestParams: null,\n path: 'pricing',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetPricing,\n });\n\n return create(jsonResponse, PricingResponseStruct);\n }\n\n /**\n * Fetches the billing portal URL.\n *\n * @returns The billing portal response.\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getBillingPortalUrl',\n requestParams: null,\n path: 'billing-portal',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,\n });\n\n return create(jsonResponse, BillingPortalResponseStruct);\n }\n\n async #fetchJson({\n profileKey,\n bearerToken,\n methodName,\n requestParams,\n path,\n method = 'GET',\n body,\n queryParams,\n errorMessage,\n }: {\n profileKey: string;\n bearerToken: string;\n methodName: string;\n requestParams: unknown;\n path: string;\n method?: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';\n body?: Record<string, unknown>;\n queryParams?: Record<string, string>;\n errorMessage: string;\n }): Promise<unknown> {\n const url = this.#getSubscriptionApiUrl(path);\n\n if (queryParams) {\n Object.entries(queryParams).forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n }\n\n try {\n return await this.fetchQuery({\n queryKey: [\n `${this.name}:${methodName}`,\n profileKey,\n requestParams as Json,\n ],\n staleTime: 0,\n gcTime: 0,\n queryFn: async () => {\n const response = await this.#fetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...this.#headersForToken(bearerToken),\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const apiError = await getSubscriptionErrorFromResponse(response);\n throw new HttpError(response.status, apiError.message);\n }\n\n return response.json();\n },\n });\n } catch (error) {\n log(errorMessage, error);\n\n const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;\n const errorToCapture =\n error instanceof Error ? error : new Error(errorMessage);\n this.#captureException?.(\n createSentryError(errorMessageWithUrl, errorToCapture),\n );\n\n if (error instanceof SubscriptionServiceError) {\n throw error;\n }\n\n throw new SubscriptionServiceError(\n `Failed to make request. ${errorMessageWithUrl}`,\n {\n cause: errorToCapture,\n },\n );\n }\n }\n\n /**\n * Ensures the request uses exactly one crypto auth method: ERC-20 approval\n * (`rawTransaction`, default) or delegation (`delegationHash`).\n *\n * @param request - The start crypto subscription request.\n * @throws If both, neither, or a mismatched combo of auth fields is provided.\n */\n #assertValidCryptoAuthCombo(request: StartCryptoSubscriptionRequest): void {\n const method =\n request.cryptoAuthMethod ?? CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n const hasRawTransaction = Boolean(request.rawTransaction);\n const hasDelegationHash = Boolean(request.delegationHash);\n const isValidErc20Approval =\n method === CRYPTO_AUTH_METHODS.ERC20_APPROVAL &&\n hasRawTransaction &&\n !hasDelegationHash;\n const isValidDelegation =\n method === CRYPTO_AUTH_METHODS.DELEGATION &&\n hasDelegationHash &&\n !hasRawTransaction;\n\n if (!isValidErc20Approval && !isValidDelegation) {\n throw new SubscriptionServiceError(\n SubscriptionServiceErrorMessage.InvalidCryptoAuthCombo,\n );\n }\n }\n\n async #getAuthenticatedContext(): Promise<{\n profileKey: string;\n bearerToken: string;\n }> {\n try {\n const [bearerToken, sessionProfile] = await Promise.all([\n this.messenger.call('AuthenticationController:getBearerToken'),\n this.messenger.call('AuthenticationController:getSessionProfile'),\n ]);\n\n return { profileKey: sessionProfile.profileId, bearerToken };\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting authorization header';\n\n this.#captureException?.(\n createSentryError(\n `Failed to get authorization header. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw new SubscriptionServiceError(\n `Failed to get authorization header. ${errorMessage}`,\n {\n cause: error instanceof Error ? error : new Error(errorMessage),\n },\n );\n }\n }\n\n #headersForToken(bearerToken: string): Record<string, string> {\n return { Authorization: `Bearer ${bearerToken}` };\n }\n\n #getSubscriptionApiUrl(path: string): URL {\n try {\n return new URL(SUBSCRIPTION_URL(this.#env, path));\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting subscription API URL';\n this.#captureException?.(\n createSentryError(\n `Failed to get subscription API URL. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw error;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionService.js","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAE9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAGnE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAI/C,OAAO,EACL,GAAG,EACH,UAAU,EACV,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,EAChC,wBAAwB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEhE,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,qBAAqB,EACrB,+BAA+B,EAC/B,oCAA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KAAK,CAAC,YAAY,CAAC,CACzD,CACF,CAAC;YAEF,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { BaseDataService } from '@metamask/base-data-service';\nimport type { CreateServicePolicyOptions } from '@metamask/controller-utils';\nimport { handleWhen, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { create } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport {\n Env,\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n SubscriptionServiceErrorMessage,\n} from './constants.js';\nimport {\n createSentryError,\n getSubscriptionErrorFromResponse,\n SubscriptionServiceError,\n} from './errors.js';\nimport { createModuleLogger, projectLogger } from './logger.js';\nimport type { SubscriptionServiceMethodActions } from './SubscriptionService-method-action-types.js';\nimport {\n BillingPortalResponseStruct,\n GetSubscriptionsResponseStruct,\n PricingResponseStruct,\n StartSubscriptionResponseStruct,\n SubscriptionApiGeneralResponseStruct,\n SubscriptionBenefitsResponseStruct,\n SubscriptionEligibilityArrayStruct,\n SubscriptionStruct,\n UpdatePaymentMethodCardResponseStruct,\n} from './SubscriptionService-structs.js';\nimport { CRYPTO_AUTH_METHODS } from './types.js';\nimport type {\n AssignCohortRequest,\n BillingPortalResponse,\n CancelSubscriptionRequest,\n GetSubscriptionsEligibilitiesRequest,\n GetSubscriptionsResponse,\n LinkRewardsRequest,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n SubmitSponsorshipIntentsRequest,\n SubmitUserEventRequest,\n Subscription,\n SubscriptionApiGeneralResponse,\n SubscriptionBenefitsResponse,\n SubscriptionEligibility,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodCryptoRequest,\n} from './types.js';\n\nexport const serviceName = 'SubscriptionService';\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string): string =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getSubscriptions',\n 'getBenefits',\n 'cancelSubscription',\n 'unCancelSubscription',\n 'startSubscriptionWithCard',\n 'startSubscriptionWithCrypto',\n 'updatePaymentMethodCard',\n 'updatePaymentMethodCrypto',\n 'getSubscriptionsEligibilities',\n 'submitUserEvent',\n 'assignUserToCohort',\n 'submitSponsorshipIntents',\n 'linkRewards',\n 'getPricing',\n 'getBillingPortalUrl',\n] as const;\n\nexport type SubscriptionServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\nexport type SubscriptionServiceActions =\n | SubscriptionServiceMethodActions\n | SubscriptionServiceInvalidateQueriesAction;\n\ntype AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerGetSessionProfileAction;\n\ntype AllowedEvents = never;\n\nexport type SubscriptionServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\nexport type SubscriptionServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\nexport type SubscriptionServiceEvents =\n | SubscriptionServiceCacheUpdatedEvent\n | SubscriptionServiceGranularCacheUpdatedEvent;\n\nexport type SubscriptionServiceMessenger = Messenger<\n typeof serviceName,\n SubscriptionServiceActions | AllowedActions,\n SubscriptionServiceEvents | AllowedEvents\n>;\n\nexport type SubscriptionServiceOptions = {\n messenger: SubscriptionServiceMessenger;\n /**\n * The `fetch` function to use for requests. Defaults to the global `fetch`.\n */\n fetchFunction?: typeof fetch;\n env?: Env;\n captureException?: (error: Error) => void;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n};\n\nconst log = createModuleLogger(projectLogger, 'SubscriptionService');\n\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof HttpError) {\n if (error.httpStatus === 429) {\n return true;\n }\n return error.httpStatus < 400 || error.httpStatus >= 500;\n }\n return true;\n}\n\nconst DEFAULT_POLICY_OPTIONS: CreateServicePolicyOptions = {\n retryFilterPolicy: handleWhen(isRetryableError),\n};\n\n/**\n * Data service for the Subscription API.\n *\n * All requests are authenticated via JWT Bearer tokens obtained from the\n * `AuthenticationController:getBearerToken` messenger action. Cached queries\n * are scoped by `profileId` from\n * `AuthenticationController:getSessionProfile`.\n */\nexport class SubscriptionService extends BaseDataService<\n typeof serviceName,\n SubscriptionServiceMessenger\n> {\n readonly #env: Env;\n\n readonly #fetch: typeof fetch;\n\n readonly #captureException?: (error: Error) => void;\n\n constructor({\n messenger,\n fetchFunction = globalThis.fetch,\n env = Env.PRD,\n captureException,\n queryClientConfig = {},\n policyOptions = {},\n }: SubscriptionServiceOptions) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions: { ...DEFAULT_POLICY_OPTIONS, ...policyOptions },\n });\n\n this.#env = env;\n this.#fetch = fetchFunction;\n this.#captureException = captureException;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getSubscriptions',\n requestParams: null,\n path: 'subscriptions',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptions,\n });\n\n return create(jsonResponse, GetSubscriptionsResponseStruct);\n }\n\n /**\n * Fetches the user's subscription benefits.\n *\n * @returns The benefits response.\n */\n async getBenefits(): Promise<SubscriptionBenefitsResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getBenefits',\n requestParams: null,\n path: 'benefits',\n method: 'POST',\n body: {},\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetBenefits,\n });\n\n return create(jsonResponse, SubscriptionBenefitsResponseStruct);\n }\n\n /**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\n async cancelSubscription(\n params: CancelSubscriptionRequest,\n ): Promise<Subscription> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'cancelSubscription',\n requestParams: {\n subscriptionId: params.subscriptionId,\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\n cancellationReason: params.cancellationReason,\n },\n path,\n method: 'POST',\n body: {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\n cancellationReason: params.cancellationReason,\n cancellationFeedback: params.cancellationFeedback,\n },\n errorMessage: SubscriptionServiceErrorMessage.FailedToCancelSubscription,\n });\n\n return create(jsonResponse, SubscriptionStruct);\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 */\n async unCancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${params.subscriptionId}/uncancel`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'unCancelSubscription',\n requestParams: params,\n path,\n method: 'POST',\n body: {},\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUncancelSubscription,\n });\n\n return create(jsonResponse, SubscriptionStruct);\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 */\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'startSubscriptionWithCard',\n requestParams: request,\n path: 'subscriptions/card',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,\n });\n\n return create(jsonResponse, StartSubscriptionResponseStruct);\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. Unlike card checkout, the Subscription\n * API creates the subscription immediately and returns it in full.\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 */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n this.#assertValidCryptoAuthCombo(request);\n\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'startSubscriptionWithCrypto',\n requestParams: request,\n path: 'subscriptions/crypto',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,\n });\n\n return create(jsonResponse, SubscriptionStruct);\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 */\n async updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<UpdatePaymentMethodCardResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'updatePaymentMethodCard',\n requestParams: request,\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,\n });\n\n return create(jsonResponse, UpdatePaymentMethodCardResponseStruct);\n }\n\n /**\n * Updates a subscription's crypto payment method.\n *\n * @param request - The update payment method request.\n */\n async updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'updatePaymentMethodCrypto',\n requestParams: request,\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCrypto,\n });\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 */\n async getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n let queryParams: Record<string, string> | undefined;\n if (request?.balanceCategory !== undefined) {\n queryParams = { balanceCategory: request.balanceCategory };\n }\n\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getSubscriptionsEligibilities',\n requestParams: request ?? null,\n path: 'subscriptions/eligibility',\n queryParams,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,\n });\n\n const results = create(jsonResponse, SubscriptionEligibilityArrayStruct);\n\n return results.map((result) => ({\n ...result,\n canSubscribe: result.canSubscribe ?? false,\n canViewEntryModal: result.canViewEntryModal ?? false,\n cohorts: result.cohorts ?? [],\n assignedCohort: result.assignedCohort ?? null,\n hasAssignedCohortExpired: result.hasAssignedCohortExpired ?? false,\n }));\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 */\n async submitUserEvent(request: SubmitUserEventRequest): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'submitUserEvent',\n requestParams: request,\n path: 'user-events',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,\n });\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 const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'assignUserToCohort',\n requestParams: request,\n path: 'cohorts/assign',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,\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 { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }\n */\n async submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsRequest,\n ): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'submitSponsorshipIntents',\n requestParams: request,\n path: 'transaction-sponsorship/intents',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,\n });\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 */\n async linkRewards(\n request: LinkRewardsRequest,\n ): Promise<SubscriptionApiGeneralResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'linkRewards',\n requestParams: request,\n path: 'rewards/link',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToLinkRewards,\n });\n\n return create(jsonResponse, SubscriptionApiGeneralResponseStruct);\n }\n\n /**\n * Fetches subscription pricing information.\n *\n * @returns The pricing response.\n */\n async getPricing(): Promise<PricingResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getPricing',\n requestParams: null,\n path: 'pricing',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetPricing,\n });\n\n return create(jsonResponse, PricingResponseStruct);\n }\n\n /**\n * Fetches the billing portal URL.\n *\n * @returns The billing portal response.\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getBillingPortalUrl',\n requestParams: null,\n path: 'billing-portal',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,\n });\n\n return create(jsonResponse, BillingPortalResponseStruct);\n }\n\n async #fetchJson({\n profileKey,\n bearerToken,\n methodName,\n requestParams,\n path,\n method = 'GET',\n body,\n queryParams,\n errorMessage,\n }: {\n profileKey: string;\n bearerToken: string;\n methodName: string;\n requestParams: unknown;\n path: string;\n method?: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';\n body?: Record<string, unknown>;\n queryParams?: Record<string, string>;\n errorMessage: string;\n }): Promise<unknown> {\n const url = this.#getSubscriptionApiUrl(path);\n\n if (queryParams) {\n Object.entries(queryParams).forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n }\n\n try {\n return await this.fetchQuery({\n queryKey: [\n `${this.name}:${methodName}`,\n profileKey,\n requestParams as Json,\n ],\n staleTime: 0,\n gcTime: 0,\n queryFn: async () => {\n const response = await this.#fetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...this.#headersForToken(bearerToken),\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const apiError = await getSubscriptionErrorFromResponse(response);\n throw new HttpError(response.status, apiError.message);\n }\n\n return response.json();\n },\n });\n } catch (error) {\n log(errorMessage, error);\n\n const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;\n const errorToCapture =\n error instanceof Error ? error : new Error(errorMessage);\n this.#captureException?.(\n createSentryError(errorMessageWithUrl, errorToCapture),\n );\n\n if (error instanceof SubscriptionServiceError) {\n throw error;\n }\n\n throw new SubscriptionServiceError(\n `Failed to make request. ${errorMessageWithUrl}`,\n {\n cause: errorToCapture,\n },\n );\n }\n }\n\n /**\n * Ensures the request uses exactly one crypto auth method: ERC-20 approval\n * (`rawTransaction`, default) or delegation (`delegationHash`).\n *\n * @param request - The start crypto subscription request.\n * @throws If both, neither, or a mismatched combo of auth fields is provided.\n */\n #assertValidCryptoAuthCombo(request: StartCryptoSubscriptionRequest): void {\n const method =\n request.cryptoAuthMethod ?? CRYPTO_AUTH_METHODS.ERC20_APPROVAL;\n const hasRawTransaction = Boolean(request.rawTransaction);\n const hasDelegationHash = Boolean(request.delegationHash);\n const isValidErc20Approval =\n method === CRYPTO_AUTH_METHODS.ERC20_APPROVAL &&\n hasRawTransaction &&\n !hasDelegationHash;\n const isValidDelegation =\n method === CRYPTO_AUTH_METHODS.DELEGATION &&\n hasDelegationHash &&\n !hasRawTransaction;\n\n if (!isValidErc20Approval && !isValidDelegation) {\n throw new SubscriptionServiceError(\n SubscriptionServiceErrorMessage.InvalidCryptoAuthCombo,\n );\n }\n }\n\n async #getAuthenticatedContext(): Promise<{\n profileKey: string;\n bearerToken: string;\n }> {\n try {\n const [bearerToken, sessionProfile] = await Promise.all([\n this.messenger.call('AuthenticationController:getBearerToken'),\n this.messenger.call('AuthenticationController:getSessionProfile'),\n ]);\n\n return { profileKey: sessionProfile.profileId, bearerToken };\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting authorization header';\n\n this.#captureException?.(\n createSentryError(\n `Failed to get authorization header. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw new SubscriptionServiceError(\n `Failed to get authorization header. ${errorMessage}`,\n {\n cause: error instanceof Error ? error : new Error(errorMessage),\n },\n );\n }\n }\n\n #headersForToken(bearerToken: string): Record<string, string> {\n return { Authorization: `Bearer ${bearerToken}` };\n }\n\n #getSubscriptionApiUrl(path: string): URL {\n try {\n return new URL(SUBSCRIPTION_URL(this.#env, path));\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting subscription API URL';\n this.#captureException?.(\n createSentryError(\n `Failed to get subscription API URL. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw error;\n }\n }\n}\n"]}
|
package/dist/constants.d.ts
CHANGED
|
@@ -66,10 +66,17 @@ export declare enum SubscriptionDelegationServiceErrorMessage {
|
|
|
66
66
|
MissingMoneyAccountVaultConfig = "Money Account vault configuration is missing or invalid",
|
|
67
67
|
DelegationContractsNotFound = "Subscription delegation contracts were not found for the configured chain",
|
|
68
68
|
PricingConfigurationNotFound = "Subscription delegation pricing configuration was not found",
|
|
69
|
+
InvalidRecipientAddress = "Subscription delegation recipient must be a valid 20-byte address",
|
|
69
70
|
InsufficientBalance = "Money Account balance is insufficient for the subscription funding requirement",
|
|
70
71
|
ChompRejectedDelegation = "CHOMP rejected the subscription delegation",
|
|
71
72
|
ChompMissingDelegationHash = "CHOMP verify response did not include a delegation hash",
|
|
72
|
-
ChompDelegationHashMismatch = "CHOMP verify response delegation hash does not match the locally computed hash"
|
|
73
|
+
ChompDelegationHashMismatch = "CHOMP verify response delegation hash does not match the locally computed hash",
|
|
74
|
+
ChainMismatch = "Subscription delegation chain does not match the Money Account chain",
|
|
75
|
+
ApprovalResultMissing = "Subscription delegation approval result is missing",
|
|
76
|
+
InvalidFundingTransactionHash = "Subscription funding transaction hash is invalid",
|
|
77
|
+
ReusableDelegationInvalid = "Reusable subscription delegation is missing or invalid",
|
|
78
|
+
TrialEligibilityChanged = "Subscription trial eligibility changed after authorization",
|
|
79
|
+
ChompIntentNotActive = "CHOMP subscription intent is not active"
|
|
73
80
|
}
|
|
74
81
|
export declare const DEFAULT_POLLING_INTERVAL: number;
|
|
75
82
|
export declare const ACTIVE_SUBSCRIPTION_STATUSES: string[];
|
package/dist/constants.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD;;GAEG;AACH,eAAO,MAAM,oBAAoB;aAE/B,aAAa,EAAE,eAAe;aAE9B,kBAAkB,EAAE,oBAAoB;aAExC,wBAAwB,EAAE,0BAA0B;aAEpD,sBAAsB,EAAE,wBAAwB;aAEhD,oBAAoB,EAAE,sBAAsB;aAE5C,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,oBAAY,GAAG;IACb,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,GAAG,QAAQ;CACZ;AAED,KAAK,YAAY,GAAG;IAClB,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAcF;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,YAAY,CAKjD;AAED,oBAAY,kCAAkC;IAC5C,qBAAqB,wDAAmD;IACxE,iBAAiB,oDAA+C;IAChE,yBAAyB,yEAAoE;IAC7F,6CAA6C,8FAAyF;IACtI,sBAAsB,0DAAqD;IAC3E,oBAAoB,qDAAgD;IACpE,qCAAqC,2EAAsE;IAC3G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+D;IACtF,oBAAoB,4CAA4C;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,EAIpC,MAAM,EAAE,CAAC"}
|
package/dist/constants.js
CHANGED
|
@@ -90,10 +90,17 @@ export var SubscriptionDelegationServiceErrorMessage;
|
|
|
90
90
|
SubscriptionDelegationServiceErrorMessage["MissingMoneyAccountVaultConfig"] = "Money Account vault configuration is missing or invalid";
|
|
91
91
|
SubscriptionDelegationServiceErrorMessage["DelegationContractsNotFound"] = "Subscription delegation contracts were not found for the configured chain";
|
|
92
92
|
SubscriptionDelegationServiceErrorMessage["PricingConfigurationNotFound"] = "Subscription delegation pricing configuration was not found";
|
|
93
|
+
SubscriptionDelegationServiceErrorMessage["InvalidRecipientAddress"] = "Subscription delegation recipient must be a valid 20-byte address";
|
|
93
94
|
SubscriptionDelegationServiceErrorMessage["InsufficientBalance"] = "Money Account balance is insufficient for the subscription funding requirement";
|
|
94
95
|
SubscriptionDelegationServiceErrorMessage["ChompRejectedDelegation"] = "CHOMP rejected the subscription delegation";
|
|
95
96
|
SubscriptionDelegationServiceErrorMessage["ChompMissingDelegationHash"] = "CHOMP verify response did not include a delegation hash";
|
|
96
97
|
SubscriptionDelegationServiceErrorMessage["ChompDelegationHashMismatch"] = "CHOMP verify response delegation hash does not match the locally computed hash";
|
|
98
|
+
SubscriptionDelegationServiceErrorMessage["ChainMismatch"] = "Subscription delegation chain does not match the Money Account chain";
|
|
99
|
+
SubscriptionDelegationServiceErrorMessage["ApprovalResultMissing"] = "Subscription delegation approval result is missing";
|
|
100
|
+
SubscriptionDelegationServiceErrorMessage["InvalidFundingTransactionHash"] = "Subscription funding transaction hash is invalid";
|
|
101
|
+
SubscriptionDelegationServiceErrorMessage["ReusableDelegationInvalid"] = "Reusable subscription delegation is missing or invalid";
|
|
102
|
+
SubscriptionDelegationServiceErrorMessage["TrialEligibilityChanged"] = "Subscription trial eligibility changed after authorization";
|
|
103
|
+
SubscriptionDelegationServiceErrorMessage["ChompIntentNotActive"] = "CHOMP subscription intent is not active";
|
|
97
104
|
})(SubscriptionDelegationServiceErrorMessage || (SubscriptionDelegationServiceErrorMessage = {}));
|
|
98
105
|
export const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes
|
|
99
106
|
export const ACTIVE_SUBSCRIPTION_STATUSES = [
|
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEnD,MAAM,CAAC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,6BAA6B;IAC7B,aAAa,EAAE,eAAe;IAC9B,8BAA8B;IAC9B,kBAAkB,EAAE,oBAAoB;IACxC,uCAAuC;IACvC,wBAAwB,EAAE,0BAA0B;IACpD,wBAAwB;IACxB,sBAAsB,EAAE,wBAAwB;IAChD,uBAAuB;IACvB,oBAAoB,EAAE,sBAAsB;IAC5C,QAAQ;IACR,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,MAAM,CAAN,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,KAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,yCAAyC;KAC9D;CACF,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,GAAQ;IACjC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CA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IACvD,iGAA8D,CAAA;IAC9D,4GAAyE,CAAA;IACzE,iFAA8C,CAAA;IAC9C,+EAA4C,CAAA;IAC5C,mGAAgE,CAAA;AAClE,CAAC,EAjBW,+BAA+B,KAA/B,+BAA+B,QAiB1C;AAED,MAAM,CAAN,IAAY,yCAsBX;AAtBD,WAAY,yCAAyC;IACnD,4HAA+E,CAAA;IAC/E,gIAAmF,CAAA;IACnF,gJAAmG,CAAA;IACnG,sJAAyG,CAAA;IACzG,qJAAwG,CAAA;IACxG,yHAA4E,CAAA;IAC5E,+HAAkF,CAAA;IAClF,uIAA0F,CAAA;IAC1F,sJAAyG,CAAA;IACzG,yIAA4F,CAAA;IAC5F,0IAA6F,CAAA;IAC7F,mJAAsG,CAAA;IACtG,mHAAsE,CAAA;IACtE,mIAAsF,CAAA;IACtF,2JAA8G,CAAA;IAC9G,mIAAsF,CAAA;IACtF,yHAA4E,CAAA;IAC5E,+HAAkF,CAAA;IAClF,iIAAoF,CAAA;IACpF,mIAAsF,CAAA;IACtF,6GAAgE,CAAA;AAClE,CAAC,EAtBW,yCAAyC,KAAzC,yCAAyC,QAsBpD;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC,YAAY;AAEpE,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC1C,qBAAqB,CAAC,MAAM;IAC5B,qBAAqB,CAAC,QAAQ;IAC9B,qBAAqB,CAAC,WAAW;CACtB,CAAC","sourcesContent":["import { SUBSCRIPTION_STATUSES } from './types.js';\n\nexport const controllerName = 'SubscriptionController';\n\n/**\n * API cancellation reason values and their client-facing text.\n */\nexport const CANCELLATION_REASONS = {\n // Costs more than it's worth\n TOO_EXPENSIVE: 'too_expensive',\n // I wasn't using the benefits\n NOT_USING_BENEFITS: 'not_using_benefits',\n // The benefits weren't what I expected\n BENEFITS_NOT_AS_EXPECTED: 'benefits_not_as_expected',\n // Something didn't work\n SOMETHING_DID_NOT_WORK: 'something_did_not_work',\n // Unhappy with support\n UNHAPPY_WITH_SUPPORT: 'unhappy_with_support',\n // Other\n OTHER: 'other',\n} as const;\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n CryptoApprovalRequiresShieldApprove = `${controllerName} - Crypto approval is only supported for Shield ERC-20 approve transactions`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport enum SubscriptionServiceErrorMessage {\n FailedToGetSubscriptions = 'Failed to get subscriptions',\n FailedToGetBenefits = 'Failed to get benefits',\n FailedToCancelSubscription = 'Failed to cancel subscription',\n FailedToUncancelSubscription = 'Failed to uncancel subscription',\n FailedToStartSubscriptionWithCard = 'Failed to start subscription with card',\n FailedToStartSubscriptionWithCrypto = 'Failed to start subscription with crypto',\n InvalidCryptoAuthCombo = 'Crypto subscription requires exactly one of rawTransaction (erc20_approval) or delegationHash (delegation)',\n FailedToUpdatePaymentMethodCard = 'Failed to update payment method card',\n FailedToUpdatePaymentMethodCrypto = 'Failed to update payment method crypto',\n FailedToGetSubscriptionsEligibilities = 'Failed to get subscriptions eligibilities',\n FailedToSubmitUserEvent = 'Failed to submit user event',\n FailedToAssignUserToCohort = 'Failed to assign user to cohort',\n FailedToSubmitSponsorshipIntents = 'Failed to submit sponsorship intents',\n FailedToLinkRewards = 'Failed to link rewards',\n FailedToGetPricing = 'Failed to get pricing',\n FailedToGetBillingPortalUrl = 'Failed to get billing portal url',\n}\n\nexport enum SubscriptionDelegationServiceErrorMessage {\n InvalidAmount = 'Subscription delegation amount must be a non-negative integer',\n InvalidDecimals = 'Subscription delegation decimals must be a non-negative integer',\n InvalidTrialPeriodDays = 'Subscription delegation trial period days must be a non-negative integer',\n InvalidMinimumFundingCycles = 'Subscription delegation minimum funding cycles must be a positive integer',\n LossyAmountScale = 'Subscription delegation amount cannot be scaled to token decimals without remainder',\n UnsupportedRecurringInterval = 'Unsupported subscription recurring interval',\n UnsupportedProduct = 'Subscription delegation is only supported for Money Account',\n MissingMoneyAccountVaultConfig = 'Money Account vault configuration is missing or invalid',\n DelegationContractsNotFound = 'Subscription delegation contracts were not found for the configured chain',\n PricingConfigurationNotFound = 'Subscription delegation pricing configuration was not found',\n InvalidRecipientAddress = 'Subscription delegation recipient must be a valid 20-byte address',\n InsufficientBalance = 'Money Account balance is insufficient for the subscription funding requirement',\n ChompRejectedDelegation = 'CHOMP rejected the subscription delegation',\n ChompMissingDelegationHash = 'CHOMP verify response did not include a delegation hash',\n ChompDelegationHashMismatch = 'CHOMP verify response delegation hash does not match the locally computed hash',\n ChainMismatch = 'Subscription delegation chain does not match the Money Account chain',\n ApprovalResultMissing = 'Subscription delegation approval result is missing',\n InvalidFundingTransactionHash = 'Subscription funding transaction hash is invalid',\n ReusableDelegationInvalid = 'Reusable subscription delegation is missing or invalid',\n TrialEligibilityChanged = 'Subscription trial eligibility changed after authorization',\n ChompIntentNotActive = 'CHOMP subscription intent is not active',\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type { SubscriptionControllerActions, SubscriptionControllerState, SubscriptionControllerEvents, SubscriptionControllerGetStateAction, SubscriptionControllerMessenger, SubscriptionControllerOptions, SubscriptionControllerStateChangeEvent, } from './SubscriptionController.js';
|
|
2
|
-
export type { SubscriptionControllerGetPricingAction, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerGetBenefitsAction, SubscriptionControllerGetSubscriptionByProductAction, SubscriptionControllerGetSubscriptionsEligibilitiesAction, SubscriptionControllerCancelSubscriptionAction, SubscriptionControllerUnCancelSubscriptionAction, SubscriptionControllerStartSubscriptionWithCardAction, SubscriptionControllerStartSubscriptionWithCryptoAction, SubscriptionControllerSubmitSubscriptionCryptoApprovalAction, SubscriptionControllerGetCryptoApproveTransactionParamsAction, SubscriptionControllerUpdatePaymentMethodAction, SubscriptionControllerGetBillingPortalUrlAction, SubscriptionControllerCacheLastSelectedPaymentMethodAction, SubscriptionControllerClearLastSelectedPaymentMethodAction, SubscriptionControllerSubmitSponsorshipIntentsAction, SubscriptionControllerSubmitUserEventAction, SubscriptionControllerAssignUserToCohortAction, SubscriptionControllerLinkRewardsAction, SubscriptionControllerGetTokenApproveAmountAction, SubscriptionControllerGetTokenMinimumBalanceAmountAction, SubscriptionControllerClearStateAction, SubscriptionControllerTriggerAccessTokenRefreshAction, SubscriptionControllerStopAllPollingAction, } from './SubscriptionController-method-action-types.js';
|
|
2
|
+
export type { SubscriptionControllerGetPricingAction, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerGetBenefitsAction, SubscriptionControllerGetSubscriptionByProductAction, SubscriptionControllerIsUserEligibleForTrialAction, SubscriptionControllerGetSubscriptionsEligibilitiesAction, SubscriptionControllerCancelSubscriptionAction, SubscriptionControllerUnCancelSubscriptionAction, SubscriptionControllerStartSubscriptionWithCardAction, SubscriptionControllerStartSubscriptionWithCryptoAction, SubscriptionControllerSubmitSubscriptionCryptoApprovalAction, SubscriptionControllerGetCryptoApproveTransactionParamsAction, SubscriptionControllerUpdatePaymentMethodAction, SubscriptionControllerGetBillingPortalUrlAction, SubscriptionControllerCacheLastSelectedPaymentMethodAction, SubscriptionControllerClearLastSelectedPaymentMethodAction, SubscriptionControllerSubmitSponsorshipIntentsAction, SubscriptionControllerSubmitUserEventAction, SubscriptionControllerAssignUserToCohortAction, SubscriptionControllerLinkRewardsAction, SubscriptionControllerGetTokenApproveAmountAction, SubscriptionControllerGetTokenMinimumBalanceAmountAction, SubscriptionControllerClearStateAction, SubscriptionControllerTriggerAccessTokenRefreshAction, SubscriptionControllerStopAllPollingAction, } from './SubscriptionController-method-action-types.js';
|
|
3
3
|
export { SubscriptionController, getDefaultSubscriptionControllerState, } from './SubscriptionController.js';
|
|
4
4
|
export type { SubscriptionApiError, Subscription, PerpsBenefitUsage, PredictBenefitUsage, SubscriptionBenefitsResponse, SubscriptionBenefitsState, SwapsBenefitUsage, AuthUtils, CancelSubscriptionRequest, CancelType, CancellationReasonCode, ISubscriptionService, StartCryptoSubscriptionRequest, StartDelegationCryptoSubscriptionRequest, StartErc20CryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, SubmitSubscriptionCryptoApprovalRequest, SubscriptionCardPaymentMethod, SubscriptionCryptoPaymentMethod, SubscriptionPaymentMethod, SubscriptionInvoice, InvoicePaymentStatus, SubmitUserEventRequest, SubmitSponsorshipIntentsRequest, SubscriptionEligibility, SubscriptionUserEventType, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, SpotTokenPaymentInfo, VaultTokenPaymentInfo, VaultName, ChainPaymentInfo, Currency, CryptoAuthMethod, PricingPaymentMethod, PricingCardPaymentMethod, PricingCryptoPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, BillingPortalResponse, CryptoPaymentMethodError, CryptoPaymentError, UpdateErc20PaymentMethodCryptoRequest, UpdateDelegationPaymentMethodCryptoRequest, UpdatePaymentMethodCryptoRequest, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCardResponse, CachedLastSelectedPaymentMethod, CacheLastSelectedPaymentMethodRequest, SubmitSponsorshipIntentsMethodParams, Cohort, CohortName, BalanceCategory, AssignCohortRequest, GetSubscriptionsEligibilitiesRequest, ModalType, MoneyAccountEntitlements, MoneyAccountPlusClaim, ProductEntitlementFeatureMap, ProductEntitlements, ShieldEntitlements, } from './types.js';
|
|
5
5
|
export { CANCEL_TYPES, CRYPTO_PAYMENT_METHOD_ERRORS, CRYPTO_PAYMENT_ERRORS, INVOICE_PAYMENT_STATUSES, SUBSCRIPTION_STATUSES, PRODUCT_TYPES, RECURRING_INTERVALS, PAYMENT_TYPES, CRYPTO_AUTH_METHODS, VAULT_NAMES, isVaultShareToken, SubscriptionUserEvent, COHORT_NAMES, BALANCE_CATEGORIES, MODAL_TYPE, MoneyAccountFeature, ShieldFeature, } from './types.js';
|
|
@@ -14,6 +14,7 @@ export type { SubscriptionDelegationServiceActions, SubscriptionDelegationServic
|
|
|
14
14
|
export { SubscriptionDelegationService, serviceName as subscriptionDelegationServiceName, } from './subscription-delegation/SubscriptionDelegationService.js';
|
|
15
15
|
export type { SubscriptionDelegationServicePrepareDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';
|
|
16
16
|
export type { SubscriptionDelegationServiceCheckMoneyAccountBalanceAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';
|
|
17
|
-
export type {
|
|
18
|
-
export {
|
|
17
|
+
export type { SubscriptionDelegationServiceStartSubscriptionWithDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';
|
|
18
|
+
export type { ChompIntentType, CommitAuthorizationBundleRequest, CommitAuthorizationBundleResult, DecodedPermission, MoneyAccountAuthorizationReason, MoneyAccountBalanceCheckRequest, MoneyAccountBalanceCheckResult, PrepareSubscriptionDelegationRequest, PrepareAuthorizationBundleResult, PreparedSubscriptionDelegation, PreparedSubscriptionDelegationBundle, PreparedSubscriptionPermission, SignedSubscriptionDelegation, StartSubscriptionWithDelegationRequest, StartSubscriptionWithDelegationResult, SubscriptionDelegationApprovalResult, SubscriptionDelegationTypedData, SubscriptionFundingRequest, SubscriptionPermissionId, UnsignedSubscriptionDelegation, } from './subscription-delegation/types.js';
|
|
19
|
+
export { CASH_SUBSCRIPTION_DELEGATION_TYPE, SUBSCRIPTION_DELEGATION_APPROVAL_TYPE, SUBSCRIPTION_DELEGATION_POLICY_VERSION, } from './subscription-delegation/types.js';
|
|
19
20
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,MAAM,6BAA6B,CAAC;AACrC,YAAY,EACV,sCAAsC,EACtC,4CAA4C,EAC5C,uCAAuC,EACvC,oDAAoD,EACpD,yDAAyD,EACzD,8CAA8C,EAC9C,gDAAgD,EAChD,qDAAqD,EACrD,uDAAuD,EACvD,4DAA4D,EAC5D,6DAA6D,EAC7D,+CAA+C,EAC/C,+CAA+C,EAC/C,0DAA0D,EAC1D,0DAA0D,EAC1D,oDAAoD,EACpD,2CAA2C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8B,GAC/B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,iCAAiC,EACjC,qCAAqC,EACrC,sCAAsC,GACvC,MAAM,oCAAoC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -6,5 +6,5 @@ export { SubscriptionServiceError } from './errors.js';
|
|
|
6
6
|
export { Env, SubscriptionControllerErrorMessage, SubscriptionServiceErrorMessage, SubscriptionDelegationServiceErrorMessage, } from './constants.js';
|
|
7
7
|
export { SubscriptionService, serviceName as subscriptionServiceName, SUBSCRIPTION_URL, } from './SubscriptionService.js';
|
|
8
8
|
export { SubscriptionDelegationService, serviceName as subscriptionDelegationServiceName, } from './subscription-delegation/SubscriptionDelegationService.js';
|
|
9
|
-
export { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './subscription-delegation/types.js';
|
|
9
|
+
export { CASH_SUBSCRIPTION_DELEGATION_TYPE, SUBSCRIPTION_DELEGATION_APPROVAL_TYPE, SUBSCRIPTION_DELEGATION_POLICY_VERSION, } from './subscription-delegation/types.js';
|
|
10
10
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoCA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,MAAM,6BAA6B,CAAC;AA0ErC,OAAO,EACL,YAAY,EACZ,4BAA4B,EAC5B,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,qBAAqB,EACrB,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,mBAAmB,EACnB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EACL,GAAG,EACH,kCAAkC,EAClC,+BAA+B,EAC/B,yCAAyC,GAC1C,MAAM,gBAAgB,CAAC;AAUxB,OAAO,EACL,mBAAmB,EACnB,WAAW,IAAI,uBAAuB,EACtC,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAyBlC,OAAO,EACL,6BAA6B,EAC7B,WAAW,IAAI,iCAAiC,GACjD,MAAM,4DAA4D,CAAC;AA0BpE,OAAO,EACL,iCAAiC,EACjC,qCAAqC,EACrC,sCAAsC,GACvC,MAAM,oCAAoC,CAAC","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController.js';\nexport type {\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerGetBenefitsAction,\n SubscriptionControllerGetSubscriptionByProductAction,\n SubscriptionControllerIsUserEligibleForTrialAction,\n SubscriptionControllerGetSubscriptionsEligibilitiesAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerUnCancelSubscriptionAction,\n SubscriptionControllerStartSubscriptionWithCardAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerSubmitSubscriptionCryptoApprovalAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerUpdatePaymentMethodAction,\n SubscriptionControllerGetBillingPortalUrlAction,\n SubscriptionControllerCacheLastSelectedPaymentMethodAction,\n SubscriptionControllerClearLastSelectedPaymentMethodAction,\n SubscriptionControllerSubmitSponsorshipIntentsAction,\n SubscriptionControllerSubmitUserEventAction,\n SubscriptionControllerAssignUserToCohortAction,\n SubscriptionControllerLinkRewardsAction,\n SubscriptionControllerGetTokenApproveAmountAction,\n SubscriptionControllerGetTokenMinimumBalanceAmountAction,\n SubscriptionControllerClearStateAction,\n SubscriptionControllerTriggerAccessTokenRefreshAction,\n SubscriptionControllerStopAllPollingAction,\n} from './SubscriptionController-method-action-types.js';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController.js';\nexport type {\n SubscriptionApiError,\n Subscription,\n PerpsBenefitUsage,\n PredictBenefitUsage,\n SubscriptionBenefitsResponse,\n SubscriptionBenefitsState,\n SwapsBenefitUsage,\n AuthUtils,\n CancelSubscriptionRequest,\n CancelType,\n CancellationReasonCode,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartDelegationCryptoSubscriptionRequest,\n StartErc20CryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n SubmitSubscriptionCryptoApprovalRequest,\n SubscriptionCardPaymentMethod,\n SubscriptionCryptoPaymentMethod,\n SubscriptionPaymentMethod,\n SubscriptionInvoice,\n InvoicePaymentStatus,\n SubmitUserEventRequest,\n SubmitSponsorshipIntentsRequest,\n SubscriptionEligibility,\n SubscriptionUserEventType,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n SpotTokenPaymentInfo,\n VaultTokenPaymentInfo,\n VaultName,\n ChainPaymentInfo,\n Currency,\n CryptoAuthMethod,\n PricingPaymentMethod,\n PricingCardPaymentMethod,\n PricingCryptoPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n BillingPortalResponse,\n CryptoPaymentMethodError,\n CryptoPaymentError,\n UpdateErc20PaymentMethodCryptoRequest,\n UpdateDelegationPaymentMethodCryptoRequest,\n UpdatePaymentMethodCryptoRequest,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCardResponse,\n CachedLastSelectedPaymentMethod,\n CacheLastSelectedPaymentMethodRequest,\n SubmitSponsorshipIntentsMethodParams,\n Cohort,\n CohortName,\n BalanceCategory,\n AssignCohortRequest,\n GetSubscriptionsEligibilitiesRequest,\n ModalType,\n MoneyAccountEntitlements,\n MoneyAccountPlusClaim,\n ProductEntitlementFeatureMap,\n ProductEntitlements,\n ShieldEntitlements,\n} from './types.js';\nexport {\n CANCEL_TYPES,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n CRYPTO_PAYMENT_ERRORS,\n INVOICE_PAYMENT_STATUSES,\n SUBSCRIPTION_STATUSES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n PAYMENT_TYPES,\n CRYPTO_AUTH_METHODS,\n VAULT_NAMES,\n isVaultShareToken,\n SubscriptionUserEvent,\n COHORT_NAMES,\n BALANCE_CATEGORIES,\n MODAL_TYPE,\n MoneyAccountFeature,\n ShieldFeature,\n} from './types.js';\nexport { CANCELLATION_REASONS } from './constants.js';\nexport {\n selectHasEntitlement,\n selectIsActiveSubscriber,\n selectIsUsageAvailable,\n selectIsPaymentFailed,\n selectPaymentFailureReason,\n selectIsRenewalNeeded,\n selectIsDelegationExhausted,\n} from './selectors.js';\nexport { SubscriptionServiceError } from './errors.js';\nexport {\n Env,\n SubscriptionControllerErrorMessage,\n SubscriptionServiceErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from './constants.js';\nexport type {\n SubscriptionServiceOptions,\n SubscriptionServiceMessenger,\n SubscriptionServiceActions,\n SubscriptionServiceEvents,\n SubscriptionServiceCacheUpdatedEvent,\n SubscriptionServiceGranularCacheUpdatedEvent,\n SubscriptionServiceInvalidateQueriesAction,\n} from './SubscriptionService.js';\nexport {\n SubscriptionService,\n serviceName as subscriptionServiceName,\n SUBSCRIPTION_URL,\n} from './SubscriptionService.js';\nexport type {\n SubscriptionServiceGetSubscriptionsAction,\n SubscriptionServiceGetBenefitsAction,\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} from './SubscriptionService-method-action-types.js';\n\nexport type {\n SubscriptionDelegationServiceActions,\n SubscriptionDelegationServiceEvents,\n SubscriptionDelegationServiceMessenger,\n SubscriptionDelegationServiceOptions,\n} from './subscription-delegation/SubscriptionDelegationService.js';\nexport {\n SubscriptionDelegationService,\n serviceName as subscriptionDelegationServiceName,\n} from './subscription-delegation/SubscriptionDelegationService.js';\nexport type { SubscriptionDelegationServicePrepareDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';\nexport type { SubscriptionDelegationServiceCheckMoneyAccountBalanceAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';\nexport type { SubscriptionDelegationServiceStartSubscriptionWithDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';\nexport type {\n ChompIntentType,\n CommitAuthorizationBundleRequest,\n CommitAuthorizationBundleResult,\n DecodedPermission,\n MoneyAccountAuthorizationReason,\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PrepareAuthorizationBundleResult,\n PreparedSubscriptionDelegation,\n PreparedSubscriptionDelegationBundle,\n PreparedSubscriptionPermission,\n SignedSubscriptionDelegation,\n StartSubscriptionWithDelegationRequest,\n StartSubscriptionWithDelegationResult,\n SubscriptionDelegationApprovalResult,\n SubscriptionDelegationTypedData,\n SubscriptionFundingRequest,\n SubscriptionPermissionId,\n UnsignedSubscriptionDelegation,\n} from './subscription-delegation/types.js';\nexport {\n CASH_SUBSCRIPTION_DELEGATION_TYPE,\n SUBSCRIPTION_DELEGATION_APPROVAL_TYPE,\n SUBSCRIPTION_DELEGATION_POLICY_VERSION,\n} from './subscription-delegation/types.js';\n"]}
|
|
@@ -14,6 +14,32 @@ export type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {
|
|
|
14
14
|
type: `SubscriptionDelegationService:checkMoneyAccountBalance`;
|
|
15
15
|
handler: SubscriptionDelegationService['checkMoneyAccountBalance'];
|
|
16
16
|
};
|
|
17
|
+
/**
|
|
18
|
+
* Runs the complete Money Account subscription checkout authorization flow.
|
|
19
|
+
*
|
|
20
|
+
* Subscriptions are refreshed first. An active subscription for the product
|
|
21
|
+
* is rejected before Money Account upgrade, approval, delegation signing,
|
|
22
|
+
* persistence, or CHOMP registration.
|
|
23
|
+
*
|
|
24
|
+
* Before the approval, `MoneyAccountUpgradeController` is asked to ensure
|
|
25
|
+
* the Money Account vault delegations and CHOMP intents exist; the
|
|
26
|
+
* Subscription API validates them server-side. The custom approval is the
|
|
27
|
+
* sole consent and funding boundary for the payment permission. No payment
|
|
28
|
+
* delegation signing, persistence, or intent mutation occurs before it
|
|
29
|
+
* returns a funding transaction hash.
|
|
30
|
+
*
|
|
31
|
+
* When `request.skipApproval` is `true`, the approval request and its
|
|
32
|
+
* result validation are skipped and the flow proceeds directly to signing.
|
|
33
|
+
* The caller is then responsible for consent and funding.
|
|
34
|
+
*
|
|
35
|
+
* @param request - Product selection, Money Account identity, and optional
|
|
36
|
+
* `skipApproval` flag.
|
|
37
|
+
* @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.
|
|
38
|
+
*/
|
|
39
|
+
export type SubscriptionDelegationServiceStartSubscriptionWithDelegationAction = {
|
|
40
|
+
type: `SubscriptionDelegationService:startSubscriptionWithDelegation`;
|
|
41
|
+
handler: SubscriptionDelegationService['startSubscriptionWithDelegation'];
|
|
42
|
+
};
|
|
17
43
|
/**
|
|
18
44
|
* Prepares a cash-subscription delegation and returns its hash.
|
|
19
45
|
*
|
|
@@ -27,10 +53,8 @@ export type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {
|
|
|
27
53
|
* If there is no match, builds, signs, optionally verifies with CHOMP,
|
|
28
54
|
* persists, and optionally registers a new delegation.
|
|
29
55
|
*
|
|
30
|
-
* When `skipChompInteractions` is true
|
|
31
|
-
*
|
|
32
|
-
* default CHOMP-enabled path requires a follow-up chomp-api-service release
|
|
33
|
-
* that accepts `'cash-subscription'` intent metadata.
|
|
56
|
+
* When `skipChompInteractions` is true, CHOMP verify and intent calls are
|
|
57
|
+
* skipped; the returned hash is computed locally.
|
|
34
58
|
*
|
|
35
59
|
* @param request - Authoritative pricing and payer details for the delegation.
|
|
36
60
|
* @param forceNew - Whether to create a replacement instead of reusing a
|
|
@@ -45,5 +69,5 @@ export type SubscriptionDelegationServicePrepareDelegationAction = {
|
|
|
45
69
|
/**
|
|
46
70
|
* Union of all SubscriptionDelegationService action types.
|
|
47
71
|
*/
|
|
48
|
-
export type SubscriptionDelegationServiceMethodActions = SubscriptionDelegationServiceCheckMoneyAccountBalanceAction | SubscriptionDelegationServicePrepareDelegationAction;
|
|
72
|
+
export type SubscriptionDelegationServiceMethodActions = SubscriptionDelegationServiceCheckMoneyAccountBalanceAction | SubscriptionDelegationServiceStartSubscriptionWithDelegationAction | SubscriptionDelegationServicePrepareDelegationAction;
|
|
49
73
|
//# sourceMappingURL=SubscriptionDelegationService-method-action-types.d.ts.map
|
package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService-method-action-types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AAExF;;;;;;GAMG;AACH,MAAM,MAAM,2DAA2D,GAAG;IACxE,IAAI,EAAE,wDAAwD,CAAC;IAC/D,OAAO,EAAE,6BAA6B,CAAC,0BAA0B,CAAC,CAAC;CACpE,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService-method-action-types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AAExF;;;;;;GAMG;AACH,MAAM,MAAM,2DAA2D,GAAG;IACxE,IAAI,EAAE,wDAAwD,CAAC;IAC/D,OAAO,EAAE,6BAA6B,CAAC,0BAA0B,CAAC,CAAC;CACpE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,MAAM,kEAAkE,GAC5E;IACE,IAAI,EAAE,+DAA+D,CAAC;IACtE,OAAO,EAAE,6BAA6B,CAAC,iCAAiC,CAAC,CAAC;CAC3E,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,MAAM,oDAAoD,GAAG;IACjE,IAAI,EAAE,iDAAiD,CAAC;IACxD,OAAO,EAAE,6BAA6B,CAAC,mBAAmB,CAAC,CAAC;CAC7D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0CAA0C,GAClD,2DAA2D,GAC3D,kEAAkE,GAClE,oDAAoD,CAAC"}
|
package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService-method-action-types.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionDelegationService } from './SubscriptionDelegationService.js';\n\n/**\n * Checks whether the Money Account holds enough convertible mUSD value to\n * cover pricing `unitAmount × minBillingCyclesForBalance`.\n *\n * @param request - Payer address and pricing amount fields.\n * @returns Balance comparison in mUSD base units (6 decimals).\n */\nexport type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {\n type: `SubscriptionDelegationService:checkMoneyAccountBalance`;\n handler: SubscriptionDelegationService['checkMoneyAccountBalance'];\n};\n\n/**\n * Prepares a cash-subscription delegation and returns its hash.\n *\n * Reuses a stored AUS delegation that matches the semantic fingerprint when\n * one exists (ensuring a CHOMP intent is active for its hash, unless\n * `skipChompInteractions` is true). Reuse classifies period `startDate` as\n * trial-deferred (`> now`) vs immediately redeemable, matching creation.\n * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\n * If there is no match, builds, signs, optionally verifies with CHOMP,\n * persists, and optionally registers a new delegation.\n *\n * When `skipChompInteractions` is true
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService-method-action-types.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionDelegationService } from './SubscriptionDelegationService.js';\n\n/**\n * Checks whether the Money Account holds enough convertible mUSD value to\n * cover pricing `unitAmount × minBillingCyclesForBalance`.\n *\n * @param request - Payer address and pricing amount fields.\n * @returns Balance comparison in mUSD base units (6 decimals).\n */\nexport type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {\n type: `SubscriptionDelegationService:checkMoneyAccountBalance`;\n handler: SubscriptionDelegationService['checkMoneyAccountBalance'];\n};\n\n/**\n * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade, approval, delegation signing,\n * persistence, or CHOMP registration.\n *\n * Before the approval, `MoneyAccountUpgradeController` is asked to ensure\n * the Money Account vault delegations and CHOMP intents exist; the\n * Subscription API validates them server-side. The custom approval is the\n * sole consent and funding boundary for the payment permission. No payment\n * delegation signing, persistence, or intent mutation occurs before it\n * returns a funding transaction hash.\n *\n * When `request.skipApproval` is `true`, the approval request and its\n * result validation are skipped and the flow proceeds directly to signing.\n * The caller is then responsible for consent and funding.\n *\n * @param request - Product selection, Money Account identity, and optional\n * `skipApproval` flag.\n * @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.\n */\nexport type SubscriptionDelegationServiceStartSubscriptionWithDelegationAction =\n {\n type: `SubscriptionDelegationService:startSubscriptionWithDelegation`;\n handler: SubscriptionDelegationService['startSubscriptionWithDelegation'];\n };\n\n/**\n * Prepares a cash-subscription delegation and returns its hash.\n *\n * Reuses a stored AUS delegation that matches the semantic fingerprint when\n * one exists (ensuring a CHOMP intent is active for its hash, unless\n * `skipChompInteractions` is true). Reuse classifies period `startDate` as\n * trial-deferred (`> now`) vs immediately redeemable, matching creation.\n * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\n * If there is no match, builds, signs, optionally verifies with CHOMP,\n * persists, and optionally registers a new delegation.\n *\n * When `skipChompInteractions` is true, CHOMP verify and intent calls are\n * skipped; the returned hash is computed locally.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @param forceNew - Whether to create a replacement instead of reusing a\n * matching stored delegation.\n * @returns The delegation hash (CHOMP-verified unless skipped) and whether it\n * was created or reused.\n */\nexport type SubscriptionDelegationServicePrepareDelegationAction = {\n type: `SubscriptionDelegationService:prepareDelegation`;\n handler: SubscriptionDelegationService['prepareDelegation'];\n};\n\n/**\n * Union of all SubscriptionDelegationService action types.\n */\nexport type SubscriptionDelegationServiceMethodActions =\n | SubscriptionDelegationServiceCheckMoneyAccountBalanceAction\n | SubscriptionDelegationServiceStartSubscriptionWithDelegationAction\n | SubscriptionDelegationServicePrepareDelegationAction;\n"]}
|
|
@@ -1,12 +1,15 @@
|
|
|
1
|
+
import type { ApprovalControllerAddRequestAction } from '@metamask/approval-controller';
|
|
1
2
|
import type { AuthenticatedUserStorageServiceCreateDelegationAction, AuthenticatedUserStorageServiceListDelegationsAction } from '@metamask/authenticated-user-storage';
|
|
2
3
|
import type { ChompApiServiceCreateIntentsAction, ChompApiServiceGetIntentsByAddressAction, ChompApiServiceVerifyDelegationAction } from '@metamask/chomp-api-service';
|
|
3
4
|
import type { DelegationControllerSignDelegationAction } from '@metamask/delegation-controller';
|
|
4
5
|
import type { Messenger } from '@metamask/messenger';
|
|
5
6
|
import type { MoneyAccountBalanceServiceFetchBalanceWithFallbackAction } from '@metamask/money-account-balance-service';
|
|
7
|
+
import type { MoneyAccountUpgradeControllerForceUpgradeAccountAction } from '@metamask/money-account-upgrade-controller';
|
|
6
8
|
import type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';
|
|
7
|
-
import type { SubscriptionControllerGetPricingAction } from '../SubscriptionController-method-action-types.js';
|
|
9
|
+
import type { SubscriptionControllerGetPricingAction, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerStartSubscriptionWithCryptoAction } from '../SubscriptionController-method-action-types.js';
|
|
10
|
+
import type { SubscriptionControllerGetStateAction } from '../SubscriptionController.js';
|
|
8
11
|
import type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';
|
|
9
|
-
import type { MoneyAccountBalanceCheckRequest, MoneyAccountBalanceCheckResult, PrepareSubscriptionDelegationRequest, PreparedSubscriptionDelegation } from './types.js';
|
|
12
|
+
import type { MoneyAccountBalanceCheckRequest, MoneyAccountBalanceCheckResult, PrepareSubscriptionDelegationRequest, PreparedSubscriptionDelegation, StartSubscriptionWithDelegationRequest, StartSubscriptionWithDelegationResult } from './types.js';
|
|
10
13
|
/**
|
|
11
14
|
* The name of the {@link SubscriptionDelegationService}, used to namespace the
|
|
12
15
|
* service's actions and events.
|
|
@@ -19,7 +22,7 @@ export type SubscriptionDelegationServiceActions = SubscriptionDelegationService
|
|
|
19
22
|
/**
|
|
20
23
|
* Actions from other messengers that {@link SubscriptionDelegationServiceMessenger} calls.
|
|
21
24
|
*/
|
|
22
|
-
type AllowedActions = AuthenticatedUserStorageServiceListDelegationsAction | AuthenticatedUserStorageServiceCreateDelegationAction | ChompApiServiceVerifyDelegationAction | ChompApiServiceCreateIntentsAction | ChompApiServiceGetIntentsByAddressAction | DelegationControllerSignDelegationAction | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction | RemoteFeatureFlagControllerGetStateAction | SubscriptionControllerGetPricingAction;
|
|
25
|
+
type AllowedActions = AuthenticatedUserStorageServiceListDelegationsAction | AuthenticatedUserStorageServiceCreateDelegationAction | ChompApiServiceVerifyDelegationAction | ChompApiServiceCreateIntentsAction | ChompApiServiceGetIntentsByAddressAction | DelegationControllerSignDelegationAction | ApprovalControllerAddRequestAction | MoneyAccountUpgradeControllerForceUpgradeAccountAction | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction | RemoteFeatureFlagControllerGetStateAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerStartSubscriptionWithCryptoAction;
|
|
23
26
|
/**
|
|
24
27
|
* Events that {@link SubscriptionDelegationService} exposes to other consumers.
|
|
25
28
|
*/
|
|
@@ -43,10 +46,8 @@ export type SubscriptionDelegationServiceOptions = {
|
|
|
43
46
|
* Authenticated User Storage → register CHOMP intent. Returns a verified
|
|
44
47
|
* `delegationHash` for `SubscriptionController.startSubscriptionWithCrypto`.
|
|
45
48
|
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* metadata. The CHOMP-enabled path (`skipChompInteractions` unset/false)
|
|
49
|
-
* remains dormant and is not production-ready without that package support.
|
|
49
|
+
* Pass `skipChompInteractions: true` to skip CHOMP verify and intent
|
|
50
|
+
* registration and return a locally computed delegation hash.
|
|
50
51
|
*
|
|
51
52
|
* Each call resolves the Money Account chain from remote feature flags, then
|
|
52
53
|
* resolves its price, payment token, and delegate from `SubscriptionController`
|
|
@@ -67,6 +68,29 @@ export declare class SubscriptionDelegationService {
|
|
|
67
68
|
* @returns Balance comparison in mUSD base units (6 decimals).
|
|
68
69
|
*/
|
|
69
70
|
checkMoneyAccountBalance(request: MoneyAccountBalanceCheckRequest): Promise<MoneyAccountBalanceCheckResult>;
|
|
71
|
+
/**
|
|
72
|
+
* Runs the complete Money Account subscription checkout authorization flow.
|
|
73
|
+
*
|
|
74
|
+
* Subscriptions are refreshed first. An active subscription for the product
|
|
75
|
+
* is rejected before Money Account upgrade, approval, delegation signing,
|
|
76
|
+
* persistence, or CHOMP registration.
|
|
77
|
+
*
|
|
78
|
+
* Before the approval, `MoneyAccountUpgradeController` is asked to ensure
|
|
79
|
+
* the Money Account vault delegations and CHOMP intents exist; the
|
|
80
|
+
* Subscription API validates them server-side. The custom approval is the
|
|
81
|
+
* sole consent and funding boundary for the payment permission. No payment
|
|
82
|
+
* delegation signing, persistence, or intent mutation occurs before it
|
|
83
|
+
* returns a funding transaction hash.
|
|
84
|
+
*
|
|
85
|
+
* When `request.skipApproval` is `true`, the approval request and its
|
|
86
|
+
* result validation are skipped and the flow proceeds directly to signing.
|
|
87
|
+
* The caller is then responsible for consent and funding.
|
|
88
|
+
*
|
|
89
|
+
* @param request - Product selection, Money Account identity, and optional
|
|
90
|
+
* `skipApproval` flag.
|
|
91
|
+
* @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.
|
|
92
|
+
*/
|
|
93
|
+
startSubscriptionWithDelegation(request: StartSubscriptionWithDelegationRequest): Promise<StartSubscriptionWithDelegationResult>;
|
|
70
94
|
/**
|
|
71
95
|
* Prepares a cash-subscription delegation and returns its hash.
|
|
72
96
|
*
|
|
@@ -80,10 +104,8 @@ export declare class SubscriptionDelegationService {
|
|
|
80
104
|
* If there is no match, builds, signs, optionally verifies with CHOMP,
|
|
81
105
|
* persists, and optionally registers a new delegation.
|
|
82
106
|
*
|
|
83
|
-
* When `skipChompInteractions` is true
|
|
84
|
-
*
|
|
85
|
-
* default CHOMP-enabled path requires a follow-up chomp-api-service release
|
|
86
|
-
* that accepts `'cash-subscription'` intent metadata.
|
|
107
|
+
* When `skipChompInteractions` is true, CHOMP verify and intent calls are
|
|
108
|
+
* skipped; the returned hash is computed locally.
|
|
87
109
|
*
|
|
88
110
|
* @param request - Authoritative pricing and payer details for the delegation.
|
|
89
111
|
* @param forceNew - Whether to create a replacement instead of reusing a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,qDAAqD,EACrD,oDAAoD,EACrD,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EACV,kCAAkC,EAClC,wCAAwC,EACxC,qCAAqC,EACtC,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kCAAkC,EACnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAEV,qDAAqD,EACrD,oDAAoD,EACrD,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EACV,kCAAkC,EAClC,wCAAwC,EACxC,qCAAqC,EACtC,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,wCAAwC,EAAE,MAAM,iCAAiC,CAAC;AAGhG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,wDAAwD,EAAE,MAAM,yCAAyC,CAAC;AACxH,OAAO,KAAK,EAAE,sDAAsD,EAAE,MAAM,4CAA4C,CAAC;AAMzH,OAAO,KAAK,EAAE,yCAAyC,EAAE,MAAM,0CAA0C,CAAC;AAS1G,O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