@metamask/subscription-controller 6.2.2 → 8.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/dist/SubscriptionController-method-action-types.cjs.map +1 -1
  3. package/dist/SubscriptionController-method-action-types.d.cts +55 -18
  4. package/dist/SubscriptionController-method-action-types.d.cts.map +1 -1
  5. package/dist/SubscriptionController-method-action-types.d.mts +55 -18
  6. package/dist/SubscriptionController-method-action-types.d.mts.map +1 -1
  7. package/dist/SubscriptionController-method-action-types.mjs.map +1 -1
  8. package/dist/SubscriptionController.cjs +180 -68
  9. package/dist/SubscriptionController.cjs.map +1 -1
  10. package/dist/SubscriptionController.d.cts +58 -26
  11. package/dist/SubscriptionController.d.cts.map +1 -1
  12. package/dist/SubscriptionController.d.mts +58 -26
  13. package/dist/SubscriptionController.d.mts.map +1 -1
  14. package/dist/SubscriptionController.mjs +181 -69
  15. package/dist/SubscriptionController.mjs.map +1 -1
  16. package/dist/SubscriptionService-method-action-types.cjs +7 -0
  17. package/dist/SubscriptionService-method-action-types.cjs.map +1 -0
  18. package/dist/SubscriptionService-method-action-types.d.cts +155 -0
  19. package/dist/SubscriptionService-method-action-types.d.cts.map +1 -0
  20. package/dist/SubscriptionService-method-action-types.d.mts +155 -0
  21. package/dist/SubscriptionService-method-action-types.d.mts.map +1 -0
  22. package/dist/SubscriptionService-method-action-types.mjs +6 -0
  23. package/dist/SubscriptionService-method-action-types.mjs.map +1 -0
  24. package/dist/SubscriptionService-structs.cjs +158 -0
  25. package/dist/SubscriptionService-structs.cjs.map +1 -0
  26. package/dist/SubscriptionService-structs.d.cts +721 -0
  27. package/dist/SubscriptionService-structs.d.cts.map +1 -0
  28. package/dist/SubscriptionService-structs.d.mts +721 -0
  29. package/dist/SubscriptionService-structs.d.mts.map +1 -0
  30. package/dist/SubscriptionService-structs.mjs +155 -0
  31. package/dist/SubscriptionService-structs.mjs.map +1 -0
  32. package/dist/SubscriptionService.cjs +279 -87
  33. package/dist/SubscriptionService.cjs.map +1 -1
  34. package/dist/SubscriptionService.d.cts +94 -10
  35. package/dist/SubscriptionService.d.cts.map +1 -1
  36. package/dist/SubscriptionService.d.mts +94 -10
  37. package/dist/SubscriptionService.d.mts.map +1 -1
  38. package/dist/SubscriptionService.mjs +279 -87
  39. package/dist/SubscriptionService.mjs.map +1 -1
  40. package/dist/constants.cjs +2 -0
  41. package/dist/constants.cjs.map +1 -1
  42. package/dist/constants.d.cts +2 -0
  43. package/dist/constants.d.cts.map +1 -1
  44. package/dist/constants.d.mts +2 -0
  45. package/dist/constants.d.mts.map +1 -1
  46. package/dist/constants.mjs +2 -0
  47. package/dist/constants.mjs.map +1 -1
  48. package/dist/index.cjs +4 -1
  49. package/dist/index.cjs.map +1 -1
  50. package/dist/index.d.cts +7 -6
  51. package/dist/index.d.cts.map +1 -1
  52. package/dist/index.d.mts +7 -6
  53. package/dist/index.d.mts.map +1 -1
  54. package/dist/index.mjs +2 -2
  55. package/dist/index.mjs.map +1 -1
  56. package/dist/types.cjs +27 -1
  57. package/dist/types.cjs.map +1 -1
  58. package/dist/types.d.cts +171 -10
  59. package/dist/types.d.cts.map +1 -1
  60. package/dist/types.d.mts +171 -10
  61. package/dist/types.d.mts.map +1 -1
  62. package/dist/types.mjs +26 -0
  63. package/dist/types.mjs.map +1 -1
  64. package/package.json +5 -2
@@ -10,36 +10,105 @@ 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_makeRequest, _SubscriptionService_getAuthorizationHeader, _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
- exports.SubscriptionService = exports.SUBSCRIPTION_URL = void 0;
15
+ exports.SubscriptionService = exports.SUBSCRIPTION_URL = exports.serviceName = void 0;
16
+ const base_data_service_1 = require("@metamask/base-data-service");
17
+ const controller_utils_1 = require("@metamask/controller-utils");
18
+ const superstruct_1 = require("@metamask/superstruct");
16
19
  const constants_js_1 = require("./constants.cjs");
17
20
  const errors_js_1 = require("./errors.cjs");
18
21
  const logger_js_1 = require("./logger.cjs");
22
+ const SubscriptionService_structs_js_1 = require("./SubscriptionService-structs.cjs");
23
+ const types_js_1 = require("./types.cjs");
24
+ exports.serviceName = 'SubscriptionService';
19
25
  const SUBSCRIPTION_URL = (env, path) => `${(0, constants_js_1.getEnvUrls)(env).subscriptionApiUrl}/v1/${path}`;
20
26
  exports.SUBSCRIPTION_URL = SUBSCRIPTION_URL;
27
+ const MESSENGER_EXPOSED_METHODS = [
28
+ 'getSubscriptions',
29
+ 'cancelSubscription',
30
+ 'unCancelSubscription',
31
+ 'startSubscriptionWithCard',
32
+ 'startSubscriptionWithCrypto',
33
+ 'updatePaymentMethodCard',
34
+ 'updatePaymentMethodCrypto',
35
+ 'getSubscriptionsEligibilities',
36
+ 'submitUserEvent',
37
+ 'assignUserToCohort',
38
+ 'submitSponsorshipIntents',
39
+ 'linkRewards',
40
+ 'getPricing',
41
+ 'getBillingPortalUrl',
42
+ ];
21
43
  const log = (0, logger_js_1.createModuleLogger)(logger_js_1.projectLogger, 'SubscriptionService');
22
- class SubscriptionService {
23
- constructor(config) {
44
+ function isRetryableError(error) {
45
+ if (error instanceof controller_utils_1.HttpError) {
46
+ if (error.httpStatus === 429) {
47
+ return true;
48
+ }
49
+ return error.httpStatus < 400 || error.httpStatus >= 500;
50
+ }
51
+ return true;
52
+ }
53
+ const DEFAULT_POLICY_OPTIONS = {
54
+ retryFilterPolicy: (0, controller_utils_1.handleWhen)(isRetryableError),
55
+ };
56
+ /**
57
+ * Data service for the Subscription API.
58
+ *
59
+ * All requests are authenticated via JWT Bearer tokens obtained from the
60
+ * `AuthenticationController:getBearerToken` messenger action. Cached queries
61
+ * are scoped by `profileId` from
62
+ * `AuthenticationController:getSessionProfile`.
63
+ */
64
+ class SubscriptionService extends base_data_service_1.BaseDataService {
65
+ constructor({ messenger, fetchFunction = globalThis.fetch, env = constants_js_1.Env.PRD, captureException, queryClientConfig = {}, policyOptions = {}, }) {
66
+ super({
67
+ name: exports.serviceName,
68
+ messenger,
69
+ queryClientConfig,
70
+ policyOptions: { ...DEFAULT_POLICY_OPTIONS, ...policyOptions },
71
+ });
24
72
  _SubscriptionService_instances.add(this);
25
73
  _SubscriptionService_env.set(this, void 0);
26
74
  _SubscriptionService_fetch.set(this, void 0);
27
75
  _SubscriptionService_captureException.set(this, void 0);
28
- __classPrivateFieldSet(this, _SubscriptionService_env, config.env, "f");
29
- this.authUtils = config.auth;
30
- __classPrivateFieldSet(this, _SubscriptionService_fetch, config.fetchFunction, "f");
31
- __classPrivateFieldSet(this, _SubscriptionService_captureException, config.captureException, "f");
76
+ __classPrivateFieldSet(this, _SubscriptionService_env, env, "f");
77
+ __classPrivateFieldSet(this, _SubscriptionService_fetch, fetchFunction, "f");
78
+ __classPrivateFieldSet(this, _SubscriptionService_captureException, captureException, "f");
79
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
32
80
  }
81
+ /**
82
+ * Fetches the user's subscriptions.
83
+ *
84
+ * @returns The subscriptions response.
85
+ */
33
86
  async getSubscriptions() {
34
- const path = 'subscriptions';
35
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
36
- path,
87
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
88
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
89
+ profileKey,
90
+ bearerToken,
91
+ methodName: 'getSubscriptions',
92
+ requestParams: null,
93
+ path: 'subscriptions',
37
94
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetSubscriptions,
38
95
  });
96
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.GetSubscriptionsResponseStruct);
39
97
  }
98
+ /**
99
+ * Cancels a subscription.
100
+ *
101
+ * @param params - The cancel subscription request.
102
+ * @returns The updated subscription.
103
+ */
40
104
  async cancelSubscription(params) {
105
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
41
106
  const path = `subscriptions/${params.subscriptionId}/cancel`;
42
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
107
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
108
+ profileKey,
109
+ bearerToken,
110
+ methodName: 'cancelSubscription',
111
+ requestParams: params,
43
112
  path,
44
113
  method: 'POST',
45
114
  body: {
@@ -47,40 +116,95 @@ class SubscriptionService {
47
116
  },
48
117
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToCancelSubscription,
49
118
  });
119
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionStruct);
50
120
  }
121
+ /**
122
+ * Reverses a pending subscription cancellation.
123
+ *
124
+ * @param params - The uncancel subscription request.
125
+ * @param params.subscriptionId - The subscription ID to uncancel.
126
+ * @returns The updated subscription.
127
+ */
51
128
  async unCancelSubscription(params) {
129
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
52
130
  const path = `subscriptions/${params.subscriptionId}/uncancel`;
53
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
131
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
132
+ profileKey,
133
+ bearerToken,
134
+ methodName: 'unCancelSubscription',
135
+ requestParams: params,
54
136
  path,
55
137
  method: 'POST',
56
138
  body: {},
57
139
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToUncancelSubscription,
58
140
  });
141
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionStruct);
59
142
  }
143
+ /**
144
+ * Starts a card-paid subscription checkout session for the requested products
145
+ * (e.g. Shield or Money Account Plus).
146
+ *
147
+ * @param request - The start subscription request.
148
+ * @returns The checkout session response.
149
+ */
60
150
  async startSubscriptionWithCard(request) {
61
151
  if (request.products.length === 0) {
62
152
  throw new errors_js_1.SubscriptionServiceError(constants_js_1.SubscriptionControllerErrorMessage.SubscriptionProductsEmpty);
63
153
  }
64
- const path = 'subscriptions/card';
65
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
66
- path,
154
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
155
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
156
+ profileKey,
157
+ bearerToken,
158
+ methodName: 'startSubscriptionWithCard',
159
+ requestParams: request,
160
+ path: 'subscriptions/card',
67
161
  method: 'POST',
68
162
  body: request,
69
163
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,
70
164
  });
165
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.StartSubscriptionResponseStruct);
71
166
  }
167
+ /**
168
+ * Starts a subscription with a crypto payment method.
169
+ *
170
+ * @param request - The start crypto subscription request.
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).
175
+ */
72
176
  async startSubscriptionWithCrypto(request) {
73
- const path = 'subscriptions/crypto';
74
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
75
- path,
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);
181
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
182
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
183
+ profileKey,
184
+ bearerToken,
185
+ methodName: 'startSubscriptionWithCrypto',
186
+ requestParams: request,
187
+ path: 'subscriptions/crypto',
76
188
  method: 'POST',
77
189
  body: request,
78
190
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,
79
191
  });
192
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.StartCryptoSubscriptionResponseStruct);
80
193
  }
194
+ /**
195
+ * Updates a subscription's card payment method.
196
+ *
197
+ * @param request - The update payment method request.
198
+ * @returns The redirect URL response.
199
+ */
81
200
  async updatePaymentMethodCard(request) {
201
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
82
202
  const path = `subscriptions/${request.subscriptionId}/payment-method/card`;
83
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
203
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
204
+ profileKey,
205
+ bearerToken,
206
+ methodName: 'updatePaymentMethodCard',
207
+ requestParams: request,
84
208
  path,
85
209
  method: 'PATCH',
86
210
  body: {
@@ -89,10 +213,21 @@ class SubscriptionService {
89
213
  },
90
214
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,
91
215
  });
216
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.UpdatePaymentMethodCardResponseStruct);
92
217
  }
218
+ /**
219
+ * Updates a subscription's crypto payment method.
220
+ *
221
+ * @param request - The update payment method request.
222
+ */
93
223
  async updatePaymentMethodCrypto(request) {
224
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
94
225
  const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;
95
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
226
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
227
+ profileKey,
228
+ bearerToken,
229
+ methodName: 'updatePaymentMethodCrypto',
230
+ requestParams: request,
96
231
  path,
97
232
  method: 'PATCH',
98
233
  body: {
@@ -109,23 +244,28 @@ class SubscriptionService {
109
244
  * @returns The eligibility for a shield subscription
110
245
  */
111
246
  async getSubscriptionsEligibilities(request) {
112
- const path = 'subscriptions/eligibility';
113
- let query;
247
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
248
+ let queryParams;
114
249
  if (request?.balanceCategory !== undefined) {
115
- query = { balanceCategory: request.balanceCategory };
250
+ queryParams = { balanceCategory: request.balanceCategory };
116
251
  }
117
- const results = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
118
- path,
119
- queryParams: query,
252
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
253
+ profileKey,
254
+ bearerToken,
255
+ methodName: 'getSubscriptionsEligibilities',
256
+ requestParams: request ?? null,
257
+ path: 'subscriptions/eligibility',
258
+ queryParams,
120
259
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,
121
260
  });
261
+ const results = (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionEligibilityArrayStruct);
122
262
  return results.map((result) => ({
123
263
  ...result,
124
- canSubscribe: result.canSubscribe || false,
125
- canViewEntryModal: result.canViewEntryModal || false,
126
- cohorts: result.cohorts || [],
264
+ canSubscribe: result.canSubscribe ?? false,
265
+ canViewEntryModal: result.canViewEntryModal ?? false,
266
+ cohorts: result.cohorts ?? [],
127
267
  assignedCohort: result.assignedCohort ?? null,
128
- hasAssignedCohortExpired: result.hasAssignedCohortExpired || false,
268
+ hasAssignedCohortExpired: result.hasAssignedCohortExpired ?? false,
129
269
  }));
130
270
  }
131
271
  /**
@@ -135,9 +275,13 @@ class SubscriptionService {
135
275
  * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }
136
276
  */
137
277
  async submitUserEvent(request) {
138
- const path = 'user-events';
139
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
140
- path,
278
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
279
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
280
+ profileKey,
281
+ bearerToken,
282
+ methodName: 'submitUserEvent',
283
+ requestParams: request,
284
+ path: 'user-events',
141
285
  method: 'POST',
142
286
  body: request,
143
287
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,
@@ -150,9 +294,13 @@ class SubscriptionService {
150
294
  * @example { cohort: 'post_tx' }
151
295
  */
152
296
  async assignUserToCohort(request) {
153
- const path = 'cohorts/assign';
154
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
155
- path,
297
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
298
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
299
+ profileKey,
300
+ bearerToken,
301
+ methodName: 'assignUserToCohort',
302
+ requestParams: request,
303
+ path: 'cohorts/assign',
156
304
  method: 'POST',
157
305
  body: request,
158
306
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,
@@ -168,9 +316,13 @@ class SubscriptionService {
168
316
  * @example { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }
169
317
  */
170
318
  async submitSponsorshipIntents(request) {
171
- const path = 'transaction-sponsorship/intents';
172
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
173
- path,
319
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
320
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
321
+ profileKey,
322
+ bearerToken,
323
+ methodName: 'submitSponsorshipIntents',
324
+ requestParams: request,
325
+ path: 'transaction-sponsorship/intents',
174
326
  method: 'POST',
175
327
  body: request,
176
328
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,
@@ -184,81 +336,120 @@ class SubscriptionService {
184
336
  * @returns The response from the API.
185
337
  */
186
338
  async linkRewards(request) {
187
- const path = 'rewards/link';
188
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
189
- path,
339
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
340
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
341
+ profileKey,
342
+ bearerToken,
343
+ methodName: 'linkRewards',
344
+ requestParams: request,
345
+ path: 'rewards/link',
190
346
  method: 'POST',
191
347
  body: request,
192
348
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToLinkRewards,
193
349
  });
350
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionApiGeneralResponseStruct);
194
351
  }
352
+ /**
353
+ * Fetches subscription pricing information.
354
+ *
355
+ * @returns The pricing response.
356
+ */
195
357
  async getPricing() {
196
- const path = 'pricing';
197
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
198
- path,
358
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
359
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
360
+ profileKey,
361
+ bearerToken,
362
+ methodName: 'getPricing',
363
+ requestParams: null,
364
+ path: 'pricing',
199
365
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetPricing,
200
366
  });
367
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.PricingResponseStruct);
201
368
  }
369
+ /**
370
+ * Fetches the billing portal URL.
371
+ *
372
+ * @returns The billing portal response.
373
+ */
202
374
  async getBillingPortalUrl() {
203
- const path = 'billing-portal';
204
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
205
- path,
375
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
376
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
377
+ profileKey,
378
+ bearerToken,
379
+ methodName: 'getBillingPortalUrl',
380
+ requestParams: null,
381
+ path: 'billing-portal',
206
382
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,
207
383
  });
384
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.BillingPortalResponseStruct);
208
385
  }
209
386
  }
210
387
  exports.SubscriptionService = SubscriptionService;
211
- _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_makeRequest =
212
- /**
213
- * Makes a request to the Subscription Service backend.
214
- *
215
- * @param params - The request object containing the path, method, body, query parameters, and error message.
216
- * @param params.path - The path of the request.
217
- * @param params.method - The method of the request.
218
- * @param params.body - The body of the request.
219
- * @param params.queryParams - The query parameters of the request.
220
- * @param params.errorMessage - The error message to throw if the request fails.
221
- * @returns The result of the request.
222
- */
223
- async function _SubscriptionService_makeRequest({ path, method = 'GET', body, queryParams, errorMessage, }) {
388
+ _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_fetchJson = async function _SubscriptionService_fetchJson({ profileKey, bearerToken, methodName, requestParams, path, method = 'GET', body, queryParams, errorMessage, }) {
224
389
  const url = __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getSubscriptionApiUrl).call(this, path);
225
- const headers = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthorizationHeader).call(this);
390
+ if (queryParams) {
391
+ Object.entries(queryParams).forEach(([key, value]) => {
392
+ url.searchParams.append(key, value);
393
+ });
394
+ }
226
395
  try {
227
- if (queryParams) {
228
- Object.entries(queryParams).forEach(([key, value]) => {
229
- url.searchParams.append(key, value);
230
- });
231
- }
232
- const response = await __classPrivateFieldGet(this, _SubscriptionService_fetch, "f").call(this, url.toString(), {
233
- method,
234
- headers: {
235
- 'Content-Type': 'application/json',
236
- ...headers,
396
+ return await this.fetchQuery({
397
+ queryKey: [
398
+ `${this.name}:${methodName}`,
399
+ profileKey,
400
+ requestParams,
401
+ ],
402
+ staleTime: 0,
403
+ cacheTime: 0,
404
+ queryFn: async () => {
405
+ const response = await __classPrivateFieldGet(this, _SubscriptionService_fetch, "f").call(this, url.toString(), {
406
+ method,
407
+ headers: {
408
+ 'Content-Type': 'application/json',
409
+ ...__classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_headersForToken).call(this, bearerToken),
410
+ },
411
+ body: body ? JSON.stringify(body) : undefined,
412
+ });
413
+ if (!response.ok) {
414
+ const apiError = await (0, errors_js_1.getSubscriptionErrorFromResponse)(response);
415
+ throw new controller_utils_1.HttpError(response.status, apiError.message);
416
+ }
417
+ return response.json();
237
418
  },
238
- body: body ? JSON.stringify(body) : undefined,
239
419
  });
240
- if (!response.ok) {
241
- const error = await (0, errors_js_1.getSubscriptionErrorFromResponse)(response);
242
- throw error;
243
- }
244
- const data = await response.json();
245
- return data;
246
420
  }
247
421
  catch (error) {
248
422
  log(errorMessage, error);
249
423
  const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;
250
424
  const errorToCapture = error instanceof Error ? error : new Error(errorMessage);
251
425
  __classPrivateFieldGet(this, _SubscriptionService_captureException, "f")?.call(this, (0, errors_js_1.createSentryError)(errorMessageWithUrl, errorToCapture));
426
+ if (error instanceof errors_js_1.SubscriptionServiceError) {
427
+ throw error;
428
+ }
252
429
  throw new errors_js_1.SubscriptionServiceError(`Failed to make request. ${errorMessageWithUrl}`, {
253
430
  cause: errorToCapture,
254
431
  });
255
432
  }
256
- }, _SubscriptionService_getAuthorizationHeader =
257
- // eslint-disable-next-line @typescript-eslint/naming-convention
258
- async function _SubscriptionService_getAuthorizationHeader() {
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
+ }
446
+ }, _SubscriptionService_getAuthenticatedContext = async function _SubscriptionService_getAuthenticatedContext() {
259
447
  try {
260
- const accessToken = await this.authUtils.getAccessToken();
261
- return { Authorization: `Bearer ${accessToken}` };
448
+ const [bearerToken, sessionProfile] = await Promise.all([
449
+ this.messenger.call('AuthenticationController:getBearerToken'),
450
+ this.messenger.call('AuthenticationController:getSessionProfile'),
451
+ ]);
452
+ return { profileKey: sessionProfile.profileId, bearerToken };
262
453
  }
263
454
  catch (error) {
264
455
  const errorMessage = error instanceof Error
@@ -269,10 +460,11 @@ async function _SubscriptionService_getAuthorizationHeader() {
269
460
  cause: error instanceof Error ? error : new Error(errorMessage),
270
461
  });
271
462
  }
463
+ }, _SubscriptionService_headersForToken = function _SubscriptionService_headersForToken(bearerToken) {
464
+ return { Authorization: `Bearer ${bearerToken}` };
272
465
  }, _SubscriptionService_getSubscriptionApiUrl = function _SubscriptionService_getSubscriptionApiUrl(path) {
273
466
  try {
274
- const url = new URL((0, exports.SUBSCRIPTION_URL)(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
275
- return url;
467
+ return new URL((0, exports.SUBSCRIPTION_URL)(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
276
468
  }
277
469
  catch (error) {
278
470
  const errorMessage = error instanceof Error