@metamask-previews/subscription-controller 7.0.0-preview-9efd0b754 → 7.0.0-preview-4e64b66e8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -1
- package/dist/SubscriptionController-method-action-types.cjs.map +1 -1
- package/dist/SubscriptionController-method-action-types.d.cts +55 -18
- package/dist/SubscriptionController-method-action-types.d.cts.map +1 -1
- package/dist/SubscriptionController-method-action-types.d.mts +55 -18
- package/dist/SubscriptionController-method-action-types.d.mts.map +1 -1
- package/dist/SubscriptionController-method-action-types.mjs.map +1 -1
- package/dist/SubscriptionController.cjs +165 -45
- package/dist/SubscriptionController.cjs.map +1 -1
- package/dist/SubscriptionController.d.cts +53 -17
- package/dist/SubscriptionController.d.cts.map +1 -1
- package/dist/SubscriptionController.d.mts +53 -17
- package/dist/SubscriptionController.d.mts.map +1 -1
- package/dist/SubscriptionController.mjs +166 -46
- package/dist/SubscriptionController.mjs.map +1 -1
- package/dist/SubscriptionService-method-action-types.cjs.map +1 -1
- package/dist/SubscriptionService-method-action-types.d.cts +5 -1
- package/dist/SubscriptionService-method-action-types.d.cts.map +1 -1
- package/dist/SubscriptionService-method-action-types.d.mts +5 -1
- package/dist/SubscriptionService-method-action-types.d.mts.map +1 -1
- package/dist/SubscriptionService-method-action-types.mjs.map +1 -1
- package/dist/SubscriptionService-structs.cjs +35 -12
- package/dist/SubscriptionService-structs.cjs.map +1 -1
- package/dist/SubscriptionService-structs.d.cts +185 -237
- package/dist/SubscriptionService-structs.d.cts.map +1 -1
- package/dist/SubscriptionService-structs.d.mts +185 -237
- package/dist/SubscriptionService-structs.d.mts.map +1 -1
- package/dist/SubscriptionService-structs.mjs +37 -14
- package/dist/SubscriptionService-structs.mjs.map +1 -1
- package/dist/SubscriptionService.cjs +24 -2
- package/dist/SubscriptionService.cjs.map +1 -1
- package/dist/SubscriptionService.d.cts +5 -1
- package/dist/SubscriptionService.d.cts.map +1 -1
- package/dist/SubscriptionService.d.mts +5 -1
- package/dist/SubscriptionService.d.mts.map +1 -1
- package/dist/SubscriptionService.mjs +24 -2
- package/dist/SubscriptionService.mjs.map +1 -1
- package/dist/constants.cjs +2 -0
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +2 -0
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.mts +2 -0
- package/dist/constants.d.mts.map +1 -1
- package/dist/constants.mjs +2 -0
- package/dist/constants.mjs.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs +27 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +171 -10
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +171 -10
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +26 -0
- package/dist/types.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-structs.d.mts","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"SubscriptionService-structs.d.mts","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAYpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAmB;AA0CnD,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkB7B,CAAC;AAEH,eAAO,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAMzC,CAAC;AAEH,eAAO,MAAM,+BAA+B;;;;EAE1C,CAAC;AAEH,eAAO,MAAM,qCAAqC;;;;;;;;;;;;;;;;EAGhD,CAAC;AAEH,eAAO,MAAM,qCAAqC;;;;EAEhD,CAAC;AAEH,eAAO,MAAM,2BAA2B;;;;EAEtC,CAAC;AAEH,eAAO,MAAM,oCAAoC;;;;;;EAG/C,CAAC;AAgEH,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAGhC,CAAC;AASH,eAAO,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EASxC,CAAC;AAEH,eAAO,MAAM,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE9C,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { array, boolean, enums, nullable, number, optional, string, type, union } from "@metamask/superstruct";
|
|
1
|
+
import { array, boolean, enums, lazy, literal, nullable, number, object, optional, string, type, union } from "@metamask/superstruct";
|
|
2
2
|
import { StrictHexStruct, CaipAccountIdStruct } from "@metamask/utils";
|
|
3
|
-
import { CANCEL_TYPES, CRYPTO_PAYMENT_METHOD_ERRORS, PAYMENT_TYPES, PRODUCT_TYPES, RECURRING_INTERVALS, SUBSCRIPTION_STATUSES } from "./types.mjs";
|
|
3
|
+
import { CANCEL_TYPES, CRYPTO_AUTH_METHODS, CRYPTO_PAYMENT_METHOD_ERRORS, PAYMENT_TYPES, PRODUCT_TYPES, RECURRING_INTERVALS, SUBSCRIPTION_STATUSES } from "./types.mjs";
|
|
4
4
|
const ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));
|
|
5
|
-
const
|
|
5
|
+
const CryptoAuthMethodStruct = enums(Object.values(CRYPTO_AUTH_METHODS));
|
|
6
6
|
const RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));
|
|
7
7
|
const SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));
|
|
8
8
|
const CancelTypeStruct = enums(Object.values(CANCEL_TYPES));
|
|
@@ -90,24 +90,47 @@ const ProductPricingStruct = type({
|
|
|
90
90
|
name: ProductTypeStruct,
|
|
91
91
|
prices: array(ProductPriceStruct),
|
|
92
92
|
});
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
93
|
+
const TokenPaymentInfoConversionRateStruct = type({
|
|
94
|
+
usd: string(),
|
|
95
|
+
});
|
|
96
|
+
const TokenPaymentInfoStruct = lazy(() => union([
|
|
97
|
+
object({
|
|
98
|
+
symbol: string(),
|
|
99
|
+
address: StrictHexStruct,
|
|
100
|
+
decimals: number(),
|
|
101
|
+
conversionRate: optional(TokenPaymentInfoConversionRateStruct),
|
|
102
|
+
isVaultShare: literal(true),
|
|
103
|
+
accountantAddress: StrictHexStruct,
|
|
104
|
+
sources: optional(array(TokenPaymentInfoStruct)),
|
|
99
105
|
}),
|
|
100
|
-
|
|
106
|
+
object({
|
|
107
|
+
symbol: string(),
|
|
108
|
+
address: StrictHexStruct,
|
|
109
|
+
decimals: number(),
|
|
110
|
+
conversionRate: optional(TokenPaymentInfoConversionRateStruct),
|
|
111
|
+
isVaultShare: optional(literal(false)),
|
|
112
|
+
sources: optional(array(TokenPaymentInfoStruct)),
|
|
113
|
+
}),
|
|
114
|
+
]));
|
|
101
115
|
const ChainPaymentInfoStruct = type({
|
|
102
116
|
chainId: StrictHexStruct,
|
|
103
117
|
paymentAddress: StrictHexStruct,
|
|
118
|
+
delegateAddress: optional(StrictHexStruct),
|
|
104
119
|
tokens: array(TokenPaymentInfoStruct),
|
|
105
120
|
isSponsorshipSupported: optional(boolean()),
|
|
106
121
|
});
|
|
107
|
-
const PricingPaymentMethodStruct =
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
122
|
+
const PricingPaymentMethodStruct = union([
|
|
123
|
+
object({
|
|
124
|
+
type: enums([PAYMENT_TYPES.byCard]),
|
|
125
|
+
products: optional(array(ProductTypeStruct)),
|
|
126
|
+
}),
|
|
127
|
+
object({
|
|
128
|
+
type: enums([PAYMENT_TYPES.byCrypto]),
|
|
129
|
+
cryptoAuthMethod: optional(CryptoAuthMethodStruct),
|
|
130
|
+
products: optional(array(ProductTypeStruct)),
|
|
131
|
+
chains: optional(array(ChainPaymentInfoStruct)),
|
|
132
|
+
}),
|
|
133
|
+
]);
|
|
111
134
|
export const PricingResponseStruct = type({
|
|
112
135
|
products: array(ProductPricingStruct),
|
|
113
136
|
paymentMethods: array(PricingPaymentMethodStruct),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService-structs.mjs","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,OAAO,EACP,KAAK,EACL,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,MAAM,EACN,IAAI,EACJ,KAAK,EACN,8BAA8B;AAC/B,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB;AAEvE,OAAO,EACL,YAAY,EACZ,4BAA4B,EAC5B,aAAa,EACb,aAAa,EACb,mBAAmB,EACnB,qB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","sourcesContent":["import {\n array,\n boolean,\n enums,\n nullable,\n number,\n optional,\n string,\n type,\n union,\n} from '@metamask/superstruct';\nimport { StrictHexStruct, CaipAccountIdStruct } from '@metamask/utils';\n\nimport {\n CANCEL_TYPES,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\n\nconst ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));\nconst PaymentTypeStruct = enums(Object.values(PAYMENT_TYPES));\nconst RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));\nconst SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));\nconst CancelTypeStruct = enums(Object.values(CANCEL_TYPES));\nconst CryptoPaymentMethodErrorStruct = enums(\n Object.values(CRYPTO_PAYMENT_METHOD_ERRORS),\n);\n\nconst ProductStruct = type({\n name: ProductTypeStruct,\n currency: enums(['usd']),\n unitAmount: number(),\n unitDecimals: number(),\n});\n\nconst SubscriptionCardPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCard]),\n card: type({\n brand: string(),\n displayBrand: string(),\n last4: string(),\n }),\n});\n\nconst SubscriptionCryptoPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCrypto]),\n crypto: type({\n payerAddress: StrictHexStruct,\n chainId: StrictHexStruct,\n tokenSymbol: string(),\n error: optional(CryptoPaymentMethodErrorStruct),\n }),\n});\n\nconst SubscriptionPaymentMethodStruct = union([\n SubscriptionCardPaymentMethodStruct,\n SubscriptionCryptoPaymentMethodStruct,\n]);\n\nexport const SubscriptionStruct = type({\n id: string(),\n products: array(ProductStruct),\n currentPeriodStart: string(),\n currentPeriodEnd: string(),\n cancelAtPeriodEnd: optional(boolean()),\n status: SubscriptionStatusStruct,\n interval: RecurringIntervalStruct,\n paymentMethod: SubscriptionPaymentMethodStruct,\n trialPeriodDays: optional(number()),\n trialStart: optional(string()),\n trialEnd: optional(string()),\n endDate: optional(string()),\n canceledAt: optional(string()),\n cancelType: CancelTypeStruct,\n inactiveAt: optional(string()),\n isEligibleForSupport: boolean(),\n billingCycles: optional(number()),\n});\n\nexport const GetSubscriptionsResponseStruct = type({\n customerId: optional(string()),\n subscriptions: array(SubscriptionStruct),\n trialedProducts: array(ProductTypeStruct),\n lastSubscription: optional(SubscriptionStruct),\n rewardAccountId: optional(CaipAccountIdStruct),\n});\n\nexport const StartSubscriptionResponseStruct = type({\n checkoutSessionUrl: string(),\n});\n\nexport const StartCryptoSubscriptionResponseStruct = type({\n subscriptionId: string(),\n status: SubscriptionStatusStruct,\n});\n\nexport const UpdatePaymentMethodCardResponseStruct = type({\n redirectUrl: string(),\n});\n\nexport const BillingPortalResponseStruct = type({\n url: string(),\n});\n\nexport const SubscriptionApiGeneralResponseStruct = type({\n success: boolean(),\n message: optional(string()),\n});\n\nconst ProductPriceStruct = type({\n interval: RecurringIntervalStruct,\n unitAmount: number(),\n unitDecimals: number(),\n currency: enums(['usd']),\n trialPeriodDays: number(),\n minBillingCycles: number(),\n minBillingCyclesForBalance: number(),\n});\n\nconst ProductPricingStruct = type({\n name: ProductTypeStruct,\n prices: array(ProductPriceStruct),\n});\n\nconst TokenPaymentInfoStruct = type({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: type({\n usd: string(),\n }),\n});\n\nconst ChainPaymentInfoStruct = type({\n chainId: StrictHexStruct,\n paymentAddress: StrictHexStruct,\n tokens: array(TokenPaymentInfoStruct),\n isSponsorshipSupported: optional(boolean()),\n});\n\nconst PricingPaymentMethodStruct = type({\n type: PaymentTypeStruct,\n chains: optional(array(ChainPaymentInfoStruct)),\n});\n\nexport const PricingResponseStruct = type({\n products: array(ProductPricingStruct),\n paymentMethods: array(PricingPaymentMethodStruct),\n});\n\nconst CohortStruct = type({\n cohort: string(),\n eligibilityRate: number(),\n priority: number(),\n eligible: boolean(),\n});\n\nexport const SubscriptionEligibilityStruct = type({\n product: ProductTypeStruct,\n canSubscribe: optional(boolean()),\n canViewEntryModal: optional(boolean()),\n modalType: optional(enums(['A', 'B'])),\n cohorts: optional(array(CohortStruct)),\n assignedCohort: optional(nullable(string())),\n assignedAt: optional(string()),\n hasAssignedCohortExpired: optional(boolean()),\n});\n\nexport const SubscriptionEligibilityArrayStruct = array(\n SubscriptionEligibilityStruct,\n);\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionService-structs.mjs","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,OAAO,EACP,KAAK,EACL,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACN,IAAI,EACJ,KAAK,EACN,8BAA8B;AAE/B,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,wBAAwB;AAEvE,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,4BAA4B,EAC5B,aAAa,EACb,aAAa,EACb,mBAAmB,EACnB,qBAAqB,EACtB,oBAAmB;AAGpB,MAAM,iBAAiB,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;AAC9D,MAAM,sBAAsB,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC;AACzE,MAAM,uBAAuB,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC;AAC1E,MAAM,wBAAwB,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC;AAC7E,MAAM,gBAAgB,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC;AAC5D,MAAM,8BAA8B,GAAG,KAAK,CAC1C,MAAM,CAAC,MAAM,CAAC,4BAA4B,CAAC,CAC5C,CAAC;AAEF,MAAM,aAAa,GAAG,IAAI,C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AAG,CAAC,CAAC,CAAC;IACtC,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACtC,cAAc,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5C,UAAU,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IAC9B,wBAAwB,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CAC9C,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,kCAAkC,GAAG,KAAK,CACrD,6BAA6B,CAC9B,CAAC","sourcesContent":["import {\n array,\n boolean,\n enums,\n lazy,\n literal,\n nullable,\n number,\n object,\n optional,\n string,\n type,\n union,\n} from '@metamask/superstruct';\nimport type { Struct } from '@metamask/superstruct';\nimport { StrictHexStruct, CaipAccountIdStruct } from '@metamask/utils';\n\nimport {\n CANCEL_TYPES,\n CRYPTO_AUTH_METHODS,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\nimport type { TokenPaymentInfo } from './types.js';\n\nconst ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));\nconst CryptoAuthMethodStruct = enums(Object.values(CRYPTO_AUTH_METHODS));\nconst RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));\nconst SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));\nconst CancelTypeStruct = enums(Object.values(CANCEL_TYPES));\nconst CryptoPaymentMethodErrorStruct = enums(\n Object.values(CRYPTO_PAYMENT_METHOD_ERRORS),\n);\n\nconst ProductStruct = type({\n name: ProductTypeStruct,\n currency: enums(['usd']),\n unitAmount: number(),\n unitDecimals: number(),\n});\n\nconst SubscriptionCardPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCard]),\n card: type({\n brand: string(),\n displayBrand: string(),\n last4: string(),\n }),\n});\n\nconst SubscriptionCryptoPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCrypto]),\n crypto: type({\n payerAddress: StrictHexStruct,\n chainId: StrictHexStruct,\n tokenSymbol: string(),\n error: optional(CryptoPaymentMethodErrorStruct),\n }),\n});\n\nconst SubscriptionPaymentMethodStruct = union([\n SubscriptionCardPaymentMethodStruct,\n SubscriptionCryptoPaymentMethodStruct,\n]);\n\nexport const SubscriptionStruct = type({\n id: string(),\n products: array(ProductStruct),\n currentPeriodStart: string(),\n currentPeriodEnd: string(),\n cancelAtPeriodEnd: optional(boolean()),\n status: SubscriptionStatusStruct,\n interval: RecurringIntervalStruct,\n paymentMethod: SubscriptionPaymentMethodStruct,\n trialPeriodDays: optional(number()),\n trialStart: optional(string()),\n trialEnd: optional(string()),\n endDate: optional(string()),\n canceledAt: optional(string()),\n cancelType: CancelTypeStruct,\n inactiveAt: optional(string()),\n isEligibleForSupport: boolean(),\n billingCycles: optional(number()),\n});\n\nexport const GetSubscriptionsResponseStruct = type({\n customerId: optional(string()),\n subscriptions: array(SubscriptionStruct),\n trialedProducts: array(ProductTypeStruct),\n lastSubscription: optional(SubscriptionStruct),\n rewardAccountId: optional(CaipAccountIdStruct),\n});\n\nexport const StartSubscriptionResponseStruct = type({\n checkoutSessionUrl: string(),\n});\n\nexport const StartCryptoSubscriptionResponseStruct = type({\n subscriptionId: string(),\n status: SubscriptionStatusStruct,\n});\n\nexport const UpdatePaymentMethodCardResponseStruct = type({\n redirectUrl: string(),\n});\n\nexport const BillingPortalResponseStruct = type({\n url: string(),\n});\n\nexport const SubscriptionApiGeneralResponseStruct = type({\n success: boolean(),\n message: optional(string()),\n});\n\nconst ProductPriceStruct = type({\n interval: RecurringIntervalStruct,\n unitAmount: number(),\n unitDecimals: number(),\n currency: enums(['usd']),\n trialPeriodDays: number(),\n minBillingCycles: number(),\n minBillingCyclesForBalance: number(),\n});\n\nconst ProductPricingStruct = type({\n name: ProductTypeStruct,\n prices: array(ProductPriceStruct),\n});\n\nconst TokenPaymentInfoConversionRateStruct = type({\n usd: string(),\n});\n\nconst TokenPaymentInfoStruct: Struct<TokenPaymentInfo> = lazy(() =>\n union([\n object({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: optional(TokenPaymentInfoConversionRateStruct),\n isVaultShare: literal(true),\n accountantAddress: StrictHexStruct,\n sources: optional(array(TokenPaymentInfoStruct)),\n }),\n object({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: optional(TokenPaymentInfoConversionRateStruct),\n isVaultShare: optional(literal(false)),\n sources: optional(array(TokenPaymentInfoStruct)),\n }),\n ]),\n) as Struct<TokenPaymentInfo>;\n\nconst ChainPaymentInfoStruct = type({\n chainId: StrictHexStruct,\n paymentAddress: StrictHexStruct,\n delegateAddress: optional(StrictHexStruct),\n tokens: array(TokenPaymentInfoStruct),\n isSponsorshipSupported: optional(boolean()),\n});\n\nconst PricingPaymentMethodStruct = union([\n object({\n type: enums([PAYMENT_TYPES.byCard]),\n products: optional(array(ProductTypeStruct)),\n }),\n object({\n type: enums([PAYMENT_TYPES.byCrypto]),\n cryptoAuthMethod: optional(CryptoAuthMethodStruct),\n products: optional(array(ProductTypeStruct)),\n chains: optional(array(ChainPaymentInfoStruct)),\n }),\n]);\n\nexport const PricingResponseStruct = type({\n products: array(ProductPricingStruct),\n paymentMethods: array(PricingPaymentMethodStruct),\n});\n\nconst CohortStruct = type({\n cohort: string(),\n eligibilityRate: number(),\n priority: number(),\n eligible: boolean(),\n});\n\nexport const SubscriptionEligibilityStruct = type({\n product: ProductTypeStruct,\n canSubscribe: optional(boolean()),\n canViewEntryModal: optional(boolean()),\n modalType: optional(enums(['A', 'B'])),\n cohorts: optional(array(CohortStruct)),\n assignedCohort: optional(nullable(string())),\n assignedAt: optional(string()),\n hasAssignedCohortExpired: optional(boolean()),\n});\n\nexport const SubscriptionEligibilityArrayStruct = array(\n SubscriptionEligibilityStruct,\n);\n"]}
|
|
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
11
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
12
|
};
|
|
13
|
-
var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_fetchJson, _SubscriptionService_getAuthenticatedContext, _SubscriptionService_headersForToken, _SubscriptionService_getSubscriptionApiUrl;
|
|
13
|
+
var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_fetchJson, _SubscriptionService_assertValidCryptoAuthCombo, _SubscriptionService_getAuthenticatedContext, _SubscriptionService_headersForToken, _SubscriptionService_getSubscriptionApiUrl;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.SubscriptionService = exports.SUBSCRIPTION_URL = exports.serviceName = void 0;
|
|
16
16
|
const base_data_service_1 = require("@metamask/base-data-service");
|
|
@@ -20,6 +20,7 @@ const constants_js_1 = require("./constants.cjs");
|
|
|
20
20
|
const errors_js_1 = require("./errors.cjs");
|
|
21
21
|
const logger_js_1 = require("./logger.cjs");
|
|
22
22
|
const SubscriptionService_structs_js_1 = require("./SubscriptionService-structs.cjs");
|
|
23
|
+
const types_js_1 = require("./types.cjs");
|
|
23
24
|
exports.serviceName = 'SubscriptionService';
|
|
24
25
|
const SUBSCRIPTION_URL = (env, path) => `${(0, constants_js_1.getEnvUrls)(env).subscriptionApiUrl}/v1/${path}`;
|
|
25
26
|
exports.SUBSCRIPTION_URL = SUBSCRIPTION_URL;
|
|
@@ -140,7 +141,8 @@ class SubscriptionService extends base_data_service_1.BaseDataService {
|
|
|
140
141
|
return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionStruct);
|
|
141
142
|
}
|
|
142
143
|
/**
|
|
143
|
-
* Starts a subscription
|
|
144
|
+
* Starts a card-paid subscription checkout session for the requested products
|
|
145
|
+
* (e.g. Shield or Money Account Plus).
|
|
144
146
|
*
|
|
145
147
|
* @param request - The start subscription request.
|
|
146
148
|
* @returns The checkout session response.
|
|
@@ -167,8 +169,15 @@ class SubscriptionService extends base_data_service_1.BaseDataService {
|
|
|
167
169
|
*
|
|
168
170
|
* @param request - The start crypto subscription request.
|
|
169
171
|
* @returns The created subscription response.
|
|
172
|
+
* @throws If `products` is empty.
|
|
173
|
+
* @throws If the request does not use exactly one of `rawTransaction`
|
|
174
|
+
* (ERC-20 approval) or `delegationHash` (delegation).
|
|
170
175
|
*/
|
|
171
176
|
async startSubscriptionWithCrypto(request) {
|
|
177
|
+
if (request.products.length === 0) {
|
|
178
|
+
throw new errors_js_1.SubscriptionServiceError(constants_js_1.SubscriptionControllerErrorMessage.SubscriptionProductsEmpty);
|
|
179
|
+
}
|
|
180
|
+
__classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_assertValidCryptoAuthCombo).call(this, request);
|
|
172
181
|
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
173
182
|
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
174
183
|
profileKey,
|
|
@@ -421,6 +430,19 @@ _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakM
|
|
|
421
430
|
cause: errorToCapture,
|
|
422
431
|
});
|
|
423
432
|
}
|
|
433
|
+
}, _SubscriptionService_assertValidCryptoAuthCombo = function _SubscriptionService_assertValidCryptoAuthCombo(request) {
|
|
434
|
+
const method = request.cryptoAuthMethod ?? types_js_1.CRYPTO_AUTH_METHODS.ERC20_APPROVAL;
|
|
435
|
+
const hasRawTransaction = Boolean(request.rawTransaction);
|
|
436
|
+
const hasDelegationHash = Boolean(request.delegationHash);
|
|
437
|
+
const isValidErc20Approval = method === types_js_1.CRYPTO_AUTH_METHODS.ERC20_APPROVAL &&
|
|
438
|
+
hasRawTransaction &&
|
|
439
|
+
!hasDelegationHash;
|
|
440
|
+
const isValidDelegation = method === types_js_1.CRYPTO_AUTH_METHODS.DELEGATION &&
|
|
441
|
+
hasDelegationHash &&
|
|
442
|
+
!hasRawTransaction;
|
|
443
|
+
if (!isValidErc20Approval && !isValidDelegation) {
|
|
444
|
+
throw new errors_js_1.SubscriptionServiceError(constants_js_1.SubscriptionServiceErrorMessage.InvalidCryptoAuthCombo);
|
|
445
|
+
}
|
|
424
446
|
}, _SubscriptionService_getAuthenticatedContext = async function _SubscriptionService_getAuthenticatedContext() {
|
|
425
447
|
try {
|
|
426
448
|
const [bearerToken, sessionProfile] = await Promise.all([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService.cjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,mEAA8D;AAE9D,iEAAmE;AAGnE,uDAA+C;AAI/C,kDAKwB;AACxB,4CAIqB;AACrB,4CAAgE;AAEhE,sFAU0C;AAuB7B,QAAA,WAAW,GAAG,qBAAqB,CAAC;AAE1C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAU,EAAE,CACjE,GAAG,IAAA,yBAAU,EAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AADxC,QAAA,gBAAgB,oBACwB;AAErD,MAAM,yBAAyB,GAAG;IAChC,kBAAkB;IAClB,oBAAoB;IACpB,sBAAsB;IACtB,2BAA2B;IAC3B,6BAA6B;IAC7B,yBAAyB;IACzB,2BAA2B;IAC3B,+BAA+B;IAC/B,iBAAiB;IACjB,oBAAoB;IACpB,0BAA0B;IAC1B,aAAa;IACb,YAAY;IACZ,qBAAqB;CACb,CAAC;AA4CX,MAAM,GAAG,GAAG,IAAA,8BAAkB,EAAC,yBAAa,EAAE,qBAA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I,6CAAkB,EAAE,KAAxB,IAAI,EACF,IAAA,6BAAiB,EACf,uCAAuC,YAAY,EAAE,EACrD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,CACzD,CACF,CAAC;QAEF,MAAM,IAAI,oCAAwB,CAChC,uCAAuC,YAAY,EAAE,EACrD;YACE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC;SAChE,CACF,CAAC;IACJ,CAAC;AACH,CAAC,uFAEgB,WAAmB;IAClC,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC,mGAEsB,IAAY;IACjC,IAAI,CAAC;QACH,OAAO,IAAI,GAAG,CAAC,IAAA,wBAAgB,EAAC,uBAAA,IAAI,gCAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,YAAY,GAChB,KAAK,YAAY,KAAK;YACpB,CAAC,CAAC,KAAK,CAAC,OAAO;YACf,CAAC,CAAC,iDAAiD,CAAC;QACxD,uBAAA,IAAI,6CAAkB,EAAE,KAAxB,IAAI,EACF,IAAA,6BAAiB,EACf,uCAAuC,YAAY,EAAE,EACrD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,CACzD,CACF,CAAC;QAEF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","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 SubscriptionEligibilityArrayStruct,\n SubscriptionStruct,\n UpdatePaymentMethodCardResponseStruct,\n} from './SubscriptionService-structs.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 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 '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 * 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: params,\n path,\n method: 'POST',\n body: {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\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 subscription with a card payment method.\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 */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\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 cacheTime: 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 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.cjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,mEAA8D;AAE9D,iEAAmE;AAGnE,uDAA+C;AAI/C,kDAKwB;AACxB,4CAIqB;AACrB,4CAAgE;AAEhE,sFAU0C;AAC1C,0CAAiD;AAuBpC,QAAA,WAAW,GAAG,qBAAqB,CAAC;AAE1C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAU,EAAE,CACjE,GAAG,IAAA,yBAAU,EAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AADxC,QAAA,gBAAgB,oBACwB;AAErD,MAAM,yBAAyB,GAAG;IAChC,kBAAkB;IAClB,oBAAoB;IACpB,sBAAsB;IACtB,2BAA2B;IAC3B,6BAA6B;IAC7B,yBAAyB;IACzB,2BAA2B;IAC3B,+BAA+B;IAC/B,iBAAiB;IACjB,oBAAoB;IACpB,0BAA0B;IAC1B,aAAa;IACb,YAAY;IACZ,qBAAqB;CACb,CAAC;AA4CX,MAAM,GAAG,GAAG,IAAA,8BAAkB,EAAC,yBAAa,EAAE,qBAAqB,CAAC,CAAC;AAErE,SAAS,gBAAgB,CAAC,KAAc;IACtC,IAAI,KAAK,YAAY,4BAAS,EAAE,CAAC;QAC/B,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,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IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,YAAY,GAChB,KAAK,YAAY,KAAK;YACpB,CAAC,CAAC,KAAK,CAAC,OAAO;YACf,CAAC,CAAC,iDAAiD,CAAC;QACxD,uBAAA,IAAI,6CAAkB,EAAE,KAAxB,IAAI,EACF,IAAA,6BAAiB,EACf,uCAAuC,YAAY,EAAE,EACrD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,CACzD,CACF,CAAC;QAEF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","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 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 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 '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 * 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: params,\n path,\n method: 'POST',\n body: {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\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 cacheTime: 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"]}
|
|
@@ -63,7 +63,8 @@ export declare class SubscriptionService extends BaseDataService<typeof serviceN
|
|
|
63
63
|
subscriptionId: string;
|
|
64
64
|
}): Promise<Subscription>;
|
|
65
65
|
/**
|
|
66
|
-
* Starts a subscription
|
|
66
|
+
* Starts a card-paid subscription checkout session for the requested products
|
|
67
|
+
* (e.g. Shield or Money Account Plus).
|
|
67
68
|
*
|
|
68
69
|
* @param request - The start subscription request.
|
|
69
70
|
* @returns The checkout session response.
|
|
@@ -74,6 +75,9 @@ export declare class SubscriptionService extends BaseDataService<typeof serviceN
|
|
|
74
75
|
*
|
|
75
76
|
* @param request - The start crypto subscription request.
|
|
76
77
|
* @returns The created subscription response.
|
|
78
|
+
* @throws If `products` is empty.
|
|
79
|
+
* @throws If the request does not use exactly one of `rawTransaction`
|
|
80
|
+
* (ERC-20 approval) or `delegationHash` (delegation).
|
|
77
81
|
*/
|
|
78
82
|
startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
|
|
79
83
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService.d.cts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EAAE,0BAA0B,EAAE,mCAAmC;AAE7E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAGlF,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,EACL,GAAG,EAIJ,wBAAuB;AAOxB,OAAO,KAAK,EAAE,gCAAgC,EAAE,sDAAqD;
|
|
1
|
+
{"version":3,"file":"SubscriptionService.d.cts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EAAE,0BAA0B,EAAE,mCAAmC;AAE7E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAGlF,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,EACL,GAAG,EAIJ,wBAAuB;AAOxB,OAAO,KAAK,EAAE,gCAAgC,EAAE,sDAAqD;AAarG,OAAO,KAAK,EACV,mBAAmB,EACnB,qBAAqB,EACrB,yBAAyB,EACzB,oCAAoC,EACpC,wBAAwB,EACxB,kBAAkB,EAClB,eAAe,EACf,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,+BAA+B,EAC/B,sBAAsB,EACtB,YAAY,EACZ,8BAA8B,EAC9B,uBAAuB,EACvB,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,EACjC,oBAAmB;AAEpB,eAAO,MAAM,WAAW,wBAAwB,CA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ceN
|
|
|
63
63
|
subscriptionId: string;
|
|
64
64
|
}): Promise<Subscription>;
|
|
65
65
|
/**
|
|
66
|
-
* Starts a subscription
|
|
66
|
+
* Starts a card-paid subscription checkout session for the requested products
|
|
67
|
+
* (e.g. Shield or Money Account Plus).
|
|
67
68
|
*
|
|
68
69
|
* @param request - The start subscription request.
|
|
69
70
|
* @returns The checkout session response.
|
|
@@ -74,6 +75,9 @@ export declare class SubscriptionService extends BaseDataService<typeof serviceN
|
|
|
74
75
|
*
|
|
75
76
|
* @param request - The start crypto subscription request.
|
|
76
77
|
* @returns The created subscription response.
|
|
78
|
+
* @throws If `products` is empty.
|
|
79
|
+
* @throws If the request does not use exactly one of `rawTransaction`
|
|
80
|
+
* (ERC-20 approval) or `delegationHash` (delegation).
|
|
77
81
|
*/
|
|
78
82
|
startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
|
|
79
83
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService.d.mts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EAAE,0BAA0B,EAAE,mCAAmC;AAE7E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAGlF,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,EACL,GAAG,EAIJ,wBAAuB;AAOxB,OAAO,KAAK,EAAE,gCAAgC,EAAE,sDAAqD;
|
|
1
|
+
{"version":3,"file":"SubscriptionService.d.mts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kC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C,GACxC,OAAO,CAAC,IAAI,CAAC;IAmBhB;;;;;OAKG;IACG,6BAA6B,CACjC,OAAO,CAAC,EAAE,oCAAoC,GAC7C,OAAO,CAAC,uBAAuB,EAAE,CAAC;IA8BrC;;;;;OAKG;IACG,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAcrE;;;;;OAKG;IACG,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAcrE;;;;;;;;OAQG;IACG,wBAAwB,CAC5B,OAAO,EAAE,+BAA+B,GACvC,OAAO,CAAC,IAAI,CAAC;IAehB;;;;;;OAMG;IACG,WAAW,CACf,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,8BAA8B,CAAC;IAgB1C;;;;OAIG;IACG,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;IAc5C;;;;OAIG;IACG,mBAAmB,IAAI,OAAO,CAAC,qBAAqB,CAAC;CAgL5D"}
|
|
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_fetchJson, _SubscriptionService_getAuthenticatedContext, _SubscriptionService_headersForToken, _SubscriptionService_getSubscriptionApiUrl;
|
|
12
|
+
var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_fetchJson, _SubscriptionService_assertValidCryptoAuthCombo, _SubscriptionService_getAuthenticatedContext, _SubscriptionService_headersForToken, _SubscriptionService_getSubscriptionApiUrl;
|
|
13
13
|
import { BaseDataService } from "@metamask/base-data-service";
|
|
14
14
|
import { handleWhen, HttpError } from "@metamask/controller-utils";
|
|
15
15
|
import { create } from "@metamask/superstruct";
|
|
@@ -17,6 +17,7 @@ import { Env, getEnvUrls, SubscriptionControllerErrorMessage, SubscriptionServic
|
|
|
17
17
|
import { createSentryError, getSubscriptionErrorFromResponse, SubscriptionServiceError } from "./errors.mjs";
|
|
18
18
|
import { createModuleLogger, projectLogger } from "./logger.mjs";
|
|
19
19
|
import { BillingPortalResponseStruct, GetSubscriptionsResponseStruct, PricingResponseStruct, StartCryptoSubscriptionResponseStruct, StartSubscriptionResponseStruct, SubscriptionApiGeneralResponseStruct, SubscriptionEligibilityArrayStruct, SubscriptionStruct, UpdatePaymentMethodCardResponseStruct } from "./SubscriptionService-structs.mjs";
|
|
20
|
+
import { CRYPTO_AUTH_METHODS } from "./types.mjs";
|
|
20
21
|
export const serviceName = 'SubscriptionService';
|
|
21
22
|
export const SUBSCRIPTION_URL = (env, path) => `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;
|
|
22
23
|
const MESSENGER_EXPOSED_METHODS = [
|
|
@@ -136,7 +137,8 @@ export class SubscriptionService extends BaseDataService {
|
|
|
136
137
|
return create(jsonResponse, SubscriptionStruct);
|
|
137
138
|
}
|
|
138
139
|
/**
|
|
139
|
-
* Starts a subscription
|
|
140
|
+
* Starts a card-paid subscription checkout session for the requested products
|
|
141
|
+
* (e.g. Shield or Money Account Plus).
|
|
140
142
|
*
|
|
141
143
|
* @param request - The start subscription request.
|
|
142
144
|
* @returns The checkout session response.
|
|
@@ -163,8 +165,15 @@ export class SubscriptionService extends BaseDataService {
|
|
|
163
165
|
*
|
|
164
166
|
* @param request - The start crypto subscription request.
|
|
165
167
|
* @returns The created subscription response.
|
|
168
|
+
* @throws If `products` is empty.
|
|
169
|
+
* @throws If the request does not use exactly one of `rawTransaction`
|
|
170
|
+
* (ERC-20 approval) or `delegationHash` (delegation).
|
|
166
171
|
*/
|
|
167
172
|
async startSubscriptionWithCrypto(request) {
|
|
173
|
+
if (request.products.length === 0) {
|
|
174
|
+
throw new SubscriptionServiceError(SubscriptionControllerErrorMessage.SubscriptionProductsEmpty);
|
|
175
|
+
}
|
|
176
|
+
__classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_assertValidCryptoAuthCombo).call(this, request);
|
|
168
177
|
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
169
178
|
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
170
179
|
profileKey,
|
|
@@ -416,6 +425,19 @@ _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakM
|
|
|
416
425
|
cause: errorToCapture,
|
|
417
426
|
});
|
|
418
427
|
}
|
|
428
|
+
}, _SubscriptionService_assertValidCryptoAuthCombo = function _SubscriptionService_assertValidCryptoAuthCombo(request) {
|
|
429
|
+
const method = request.cryptoAuthMethod ?? CRYPTO_AUTH_METHODS.ERC20_APPROVAL;
|
|
430
|
+
const hasRawTransaction = Boolean(request.rawTransaction);
|
|
431
|
+
const hasDelegationHash = Boolean(request.delegationHash);
|
|
432
|
+
const isValidErc20Approval = method === CRYPTO_AUTH_METHODS.ERC20_APPROVAL &&
|
|
433
|
+
hasRawTransaction &&
|
|
434
|
+
!hasDelegationHash;
|
|
435
|
+
const isValidDelegation = method === CRYPTO_AUTH_METHODS.DELEGATION &&
|
|
436
|
+
hasDelegationHash &&
|
|
437
|
+
!hasRawTransaction;
|
|
438
|
+
if (!isValidErc20Approval && !isValidDelegation) {
|
|
439
|
+
throw new SubscriptionServiceError(SubscriptionServiceErrorMessage.InvalidCryptoAuthCombo);
|
|
440
|
+
}
|
|
419
441
|
}, _SubscriptionService_getAuthenticatedContext = async function _SubscriptionService_getAuthenticatedContext() {
|
|
420
442
|
try {
|
|
421
443
|
const [bearerToken, sessionProfile] = await Promise.all([
|