@metamask-previews/subscription-controller 0.0.0-preview-ea6406b3 → 0.0.0-preview-9a5f096

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 CHANGED
@@ -17,5 +17,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
17
17
  - Add methods `startSubscriptionWithCrypto` and `getCryptoApproveTransactionParams` method ([#6456](https://github.com/MetaMask/core/pull/6456))
18
18
  - Added `triggerAccessTokenRefresh` to trigger an access token refresh ([#6374](https://github.com/MetaMask/core/pull/6374))
19
19
  - Add two new controller state metadata properties: `includeInStateLogs` and `usedInUi` ([#6504](https://github.com/MetaMask/core/pull/6504))
20
+ - Added `updatePaymentMethodCard` and `updatePaymentMethodCrypto` methods ([#6539](https://github.com/MetaMask/core/pull/6539))
20
21
 
21
22
  [Unreleased]: https://github.com/MetaMask/core/
@@ -41,6 +41,12 @@ const subscriptionControllerMetadata = {
41
41
  anonymous: false,
42
42
  usedInUi: true,
43
43
  },
44
+ pricing: {
45
+ includeInStateLogs: true,
46
+ persist: true,
47
+ anonymous: true,
48
+ usedInUi: true,
49
+ },
44
50
  };
45
51
  class SubscriptionController extends base_controller_1.BaseController {
46
52
  /**
@@ -72,7 +78,11 @@ class SubscriptionController extends base_controller_1.BaseController {
72
78
  * @returns The pricing information.
73
79
  */
74
80
  async getPricing() {
75
- return await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getPricing();
81
+ const pricing = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getPricing();
82
+ this.update((state) => {
83
+ state.pricing = pricing;
84
+ });
85
+ return pricing;
76
86
  }
77
87
  async getSubscriptions() {
78
88
  const { subscriptions } = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getSubscriptions();
@@ -101,7 +111,9 @@ class SubscriptionController extends base_controller_1.BaseController {
101
111
  }
102
112
  async startSubscriptionWithCrypto(request) {
103
113
  __classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_assertIsUserNotSubscribed).call(this, { products: request.products });
104
- return await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").startSubscriptionWithCrypto(request);
114
+ const response = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").startSubscriptionWithCrypto(request);
115
+ this.triggerAccessTokenRefresh();
116
+ return response;
105
117
  }
106
118
  /**
107
119
  * Get transaction params to create crypto approve transaction for subscription payment
@@ -143,6 +155,20 @@ class SubscriptionController extends base_controller_1.BaseController {
143
155
  chainId: request.chainId,
144
156
  };
145
157
  }
158
+ async updatePaymentMethod(opts) {
159
+ if (opts.paymentType === types_1.PaymentType.byCard) {
160
+ const { paymentType, ...cardRequest } = opts;
161
+ await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").updatePaymentMethodCard(cardRequest);
162
+ }
163
+ else if (opts.paymentType === types_1.PaymentType.byCrypto) {
164
+ const { paymentType, ...cryptoRequest } = opts;
165
+ await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").updatePaymentMethodCrypto(cryptoRequest);
166
+ }
167
+ else {
168
+ throw new Error('Invalid payment type');
169
+ }
170
+ await this.getSubscriptions();
171
+ }
146
172
  /**
147
173
  * Triggers an access token refresh.
148
174
  */
@@ -161,6 +187,7 @@ _SubscriptionController_subscriptionService = new WeakMap(), _SubscriptionContro
161
187
  this.messagingSystem.registerActionHandler('SubscriptionController:getPricing', this.getPricing.bind(this));
162
188
  this.messagingSystem.registerActionHandler('SubscriptionController:getCryptoApproveTransactionParams', this.getCryptoApproveTransactionParams.bind(this));
163
189
  this.messagingSystem.registerActionHandler('SubscriptionController:startSubscriptionWithCrypto', this.startSubscriptionWithCrypto.bind(this));
190
+ this.messagingSystem.registerActionHandler('SubscriptionController:updatePaymentMethod', this.updatePaymentMethod.bind(this));
164
191
  }, _SubscriptionController_getSubscriptionPriceAmount = function _SubscriptionController_getSubscriptionPriceAmount(price) {
165
192
  // no need to use BigInt since max unitDecimals are always 2 for price
166
193
  const amount = (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.cjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAMmC;AAGnC,+CAGqB;AAQrB,uCAQiB;AAsFjB;;;;GAIG;AACH,SAAgB,qCAAqC;IACnD,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAJD,sFAIC;AAED;;;;;;GAMG;AACH,MAAM,8BAA8B,GAClC;IACE,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEJ,MAAa,sBAAuB,SAAQ,gCAI3C;IAGC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,KAAK,EACL,mBAAmB,GACW;QAC9B,KAAK,CAAC;YACJ,IAAI,EAAE,0BAAc;YACpB,QAAQ,EAAE,8BAA8B;YACxC,KAAK,EAAE;gBACL,GAAG,qCAAqC,EAAE;gBAC1C,GAAG,KAAK;aACT;YACD,SAAS;SACV,CAAC,CAAC;;QAvBI,8DAA2C;QAyBlD,uBAAA,IAAI,+CAAwB,mBAAmB,MAAA,CAAC;QAChD,uBAAA,IAAI,0FAAyB,MAA7B,IAAI,CAA2B,CAAC;IAClC,CAAC;IAsCD;;;;OAIG;IACH,KAAK,CAAC,UAAU;QACd,OAAO,MAAM,uBAAA,IAAI,mDAAqB,CAAC,UAAU,EAAE,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,EAAE,aAAa,EAAE,GACrB,MAAM,uBAAA,IAAI,mDAAqB,CAAC,gBAAgB,EAAE,CAAC;QAErD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,aAAa,GA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AAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAC7C,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,8CAAkC,CAAC,qBAAqB,CAAC,CAAC;KAC3E;AACH,CAAC,2GAYuB,OAAmC;IACzD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAC5B,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,KAAK,OAAO,CAAC,cAAc,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,8CAAkC,CAAC,iBAAiB,CAAC,CAAC;KACvE;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type StateMetadata,\n type ControllerStateChangeEvent,\n type ControllerGetStateAction,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport {\n controllerName,\n SubscriptionControllerErrorMessage,\n} from './constants';\nimport type {\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n} from './types';\nimport {\n PaymentType,\n SubscriptionStatus,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n subscriptions: Subscription[];\n};\n\n// Messenger Actions\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `${typeof controllerName}:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `${typeof controllerName}:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\nexport type SubscriptionControllerStartShieldSubscriptionWithCardAction = {\n type: `${typeof controllerName}:startShieldSubscriptionWithCard`;\n handler: SubscriptionController['startShieldSubscriptionWithCard'];\n};\nexport type SubscriptionControllerGetPricingAction = {\n type: `${typeof controllerName}:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `${typeof controllerName}:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `${typeof controllerName}:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerStartShieldSubscriptionWithCardAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction;\n\nexport type AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerPerformSignOut;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n AuthenticationController.AuthenticationControllerStateChangeEvent;\n\n// Messenger\nexport type SubscriptionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Subscription service to use for the subscription controller.\n */\n subscriptionService: ISubscriptionService;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n };\n\nexport class SubscriptionController extends BaseController<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n readonly #subscriptionService: ISubscriptionService;\n\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.subscriptionService - The subscription service for communicating with subscription server.\n */\n constructor({\n messenger,\n state,\n subscriptionService,\n }: SubscriptionControllerOptions) {\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.#subscriptionService = subscriptionService;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getSubscriptions',\n this.getSubscriptions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:cancelSubscription',\n this.cancelSubscription.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startShieldSubscriptionWithCard',\n this.startShieldSubscriptionWithCard.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getPricing',\n this.getPricing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getCryptoApproveTransactionParams',\n this.getCryptoApproveTransactionParams.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startSubscriptionWithCrypto',\n this.startSubscriptionWithCrypto.bind(this),\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n return await this.#subscriptionService.getPricing();\n }\n\n async getSubscriptions() {\n const { subscriptions } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n await this.#subscriptionService.cancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, status: SubscriptionStatus.canceled }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(request: StartSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response =\n await this.#subscriptionService.startSubscriptionWithCard(request);\n\n this.triggerAccessTokenRefresh();\n\n return response;\n }\n\n async startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n return await this.#subscriptionService.startSubscriptionWithCrypto(request);\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n async getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): Promise<GetCryptoApproveTransactionResponse> {\n const pricing = await this.getPricing();\n const product = pricing.products.find(\n (p) => p.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find((p) => p.interval === request.interval);\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = pricing.paymentMethods.find(\n (t) => t.type === PaymentType.byCrypto,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (t) => t.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (t) => t.address === request.paymentTokenAddress,\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.#getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount.toString(),\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n /**\n * Calculate total subscription price amount from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice) {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount =\n (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n #getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ) {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // conversion rate is a float string e.g: \"1.0\"\n // We need to handle float conversion rates with integer math for BigInt.\n // We'll scale the conversion rate to an integer by multiplying by 10^4.\n // conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)\n // So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)\n // This allows us to avoid floating point math and keep precision.\n const SCALE = 10n ** 4n;\n const conversionRateScaled =\n BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;\n // price of the product\n const priceAmount = this.#getSubscriptionPriceAmount(price);\n const priceAmountScaled =\n BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;\n\n const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);\n\n const tokenAmount =\n (priceAmountScaled * tokenDecimal) / conversionRateScaled;\n return tokenAmount;\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }) {\n if (\n this.state.subscriptions.find((subscription) =>\n subscription.products.some((p) => products.includes(p.name)),\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh() {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }) {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionController.cjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAMmC;AAGnC,+CAGqB;AASrB,uCAQiB;AA4FjB;;;;GAIG;AACH,SAAgB,qCAAqC;IACnD,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAJD,sFAIC;AAED;;;;;;GAMG;AACH,MAAM,8BAA8B,GAClC;IACE,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,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,IAAI,6FAA4B,MAAhC,IAAI,EAA6B,KAAK,CAAC,CAAC;IAC5D,MAAM,iBAAiB,GACrB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;IAE1D,MAAM,YAAY,GAAG,MAAM,CAAC,EAAE,CAAC,IAAI,MAAM,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IAErE,MAAM,WAAW,GACf,CAAC,iBAAiB,GAAG,YAAY,CAAC,GAAG,oBAAoB,CAAC;IAC5D,OAAO,WAAW,CAAC;AACrB,CAAC,iHAE0B,EAAE,QAAQ,EAA+B;IAClE,IACE,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAC7C,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,8CAAkC,CAAC,qBAAqB,CAAC,CAAC;KAC3E;AACH,CAAC,2GAYuB,OAAmC;IACzD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAC5B,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,KAAK,OAAO,CAAC,cAAc,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,8CAAkC,CAAC,iBAAiB,CAAC,CAAC;KACvE;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type StateMetadata,\n type ControllerStateChangeEvent,\n type ControllerGetStateAction,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport {\n controllerName,\n SubscriptionControllerErrorMessage,\n} from './constants';\nimport type {\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodOpts,\n} from './types';\nimport {\n PaymentType,\n SubscriptionStatus,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n subscriptions: Subscription[];\n pricing?: PricingResponse;\n};\n\n// Messenger Actions\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `${typeof controllerName}:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `${typeof controllerName}:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\nexport type SubscriptionControllerStartShieldSubscriptionWithCardAction = {\n type: `${typeof controllerName}:startShieldSubscriptionWithCard`;\n handler: SubscriptionController['startShieldSubscriptionWithCard'];\n};\nexport type SubscriptionControllerGetPricingAction = {\n type: `${typeof controllerName}:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `${typeof controllerName}:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `${typeof controllerName}:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\nexport type SubscriptionControllerUpdatePaymentMethodAction = {\n type: `${typeof controllerName}:updatePaymentMethod`;\n handler: SubscriptionController['updatePaymentMethod'];\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerStartShieldSubscriptionWithCardAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction\n | SubscriptionControllerUpdatePaymentMethodAction;\n\nexport type AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerPerformSignOut;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n AuthenticationController.AuthenticationControllerStateChangeEvent;\n\n// Messenger\nexport type SubscriptionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Subscription service to use for the subscription controller.\n */\n subscriptionService: ISubscriptionService;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n pricing: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n };\n\nexport class SubscriptionController extends BaseController<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n readonly #subscriptionService: ISubscriptionService;\n\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.subscriptionService - The subscription service for communicating with subscription server.\n */\n constructor({\n messenger,\n state,\n subscriptionService,\n }: SubscriptionControllerOptions) {\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.#subscriptionService = subscriptionService;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getSubscriptions',\n this.getSubscriptions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:cancelSubscription',\n this.cancelSubscription.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startShieldSubscriptionWithCard',\n this.startShieldSubscriptionWithCard.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getPricing',\n this.getPricing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getCryptoApproveTransactionParams',\n this.getCryptoApproveTransactionParams.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startSubscriptionWithCrypto',\n this.startSubscriptionWithCrypto.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:updatePaymentMethod',\n this.updatePaymentMethod.bind(this),\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n const pricing = await this.#subscriptionService.getPricing();\n this.update((state) => {\n state.pricing = pricing;\n });\n return pricing;\n }\n\n async getSubscriptions() {\n const { subscriptions } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n await this.#subscriptionService.cancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, status: SubscriptionStatus.canceled }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(request: StartSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response =\n await this.#subscriptionService.startSubscriptionWithCard(request);\n\n this.triggerAccessTokenRefresh();\n\n return response;\n }\n\n async startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n const response =\n await this.#subscriptionService.startSubscriptionWithCrypto(request);\n this.triggerAccessTokenRefresh();\n return response;\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n async getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): Promise<GetCryptoApproveTransactionResponse> {\n const pricing = await this.getPricing();\n const product = pricing.products.find(\n (p) => p.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find((p) => p.interval === request.interval);\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = pricing.paymentMethods.find(\n (t) => t.type === PaymentType.byCrypto,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (t) => t.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (t) => t.address === request.paymentTokenAddress,\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.#getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount.toString(),\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(opts: UpdatePaymentMethodOpts) {\n if (opts.paymentType === PaymentType.byCard) {\n const { paymentType, ...cardRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCard(cardRequest);\n } else if (opts.paymentType === PaymentType.byCrypto) {\n const { paymentType, ...cryptoRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCrypto(cryptoRequest);\n } else {\n throw new Error('Invalid payment type');\n }\n await this.getSubscriptions();\n }\n\n /**\n * Calculate total subscription price amount from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice) {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount =\n (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n #getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ) {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // conversion rate is a float string e.g: \"1.0\"\n // We need to handle float conversion rates with integer math for BigInt.\n // We'll scale the conversion rate to an integer by multiplying by 10^4.\n // conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)\n // So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)\n // This allows us to avoid floating point math and keep precision.\n const SCALE = 10n ** 4n;\n const conversionRateScaled =\n BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;\n // price of the product\n const priceAmount = this.#getSubscriptionPriceAmount(price);\n const priceAmountScaled =\n BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;\n\n const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);\n\n const tokenAmount =\n (priceAmountScaled * tokenDecimal) / conversionRateScaled;\n return tokenAmount;\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }) {\n if (\n this.state.subscriptions.find((subscription) =>\n subscription.products.some((p) => products.includes(p.name)),\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh() {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }) {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { BaseController, type ControllerStateChangeEvent, type ControllerGetStateAction, type RestrictedMessenger } from "@metamask/base-controller";
2
2
  import type { AuthenticationController } from "@metamask/profile-sync-controller";
3
3
  import { controllerName } from "./constants.cjs";
4
- import type { GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, StartCryptoSubscriptionRequest } from "./types.cjs";
4
+ import type { GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, StartCryptoSubscriptionRequest, UpdatePaymentMethodOpts } from "./types.cjs";
5
5
  import { type ISubscriptionService, type PricingResponse, type StartSubscriptionRequest, type Subscription } from "./types.cjs";
6
6
  export type SubscriptionControllerState = {
7
7
  subscriptions: Subscription[];
8
+ pricing?: PricingResponse;
8
9
  };
9
10
  export type SubscriptionControllerGetSubscriptionsAction = {
10
11
  type: `${typeof controllerName}:getSubscriptions`;
@@ -30,8 +31,12 @@ export type SubscriptionControllerStartSubscriptionWithCryptoAction = {
30
31
  type: `${typeof controllerName}:startSubscriptionWithCrypto`;
31
32
  handler: SubscriptionController['startSubscriptionWithCrypto'];
32
33
  };
34
+ export type SubscriptionControllerUpdatePaymentMethodAction = {
35
+ type: `${typeof controllerName}:updatePaymentMethod`;
36
+ handler: SubscriptionController['updatePaymentMethod'];
37
+ };
33
38
  export type SubscriptionControllerGetStateAction = ControllerGetStateAction<typeof controllerName, SubscriptionControllerState>;
34
- export type SubscriptionControllerActions = SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerCancelSubscriptionAction | SubscriptionControllerStartShieldSubscriptionWithCardAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetCryptoApproveTransactionParamsAction | SubscriptionControllerStartSubscriptionWithCryptoAction;
39
+ export type SubscriptionControllerActions = SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerCancelSubscriptionAction | SubscriptionControllerStartShieldSubscriptionWithCardAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetCryptoApproveTransactionParamsAction | SubscriptionControllerStartSubscriptionWithCryptoAction | SubscriptionControllerUpdatePaymentMethodAction;
35
40
  export type AllowedActions = AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerPerformSignOut;
36
41
  export type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, SubscriptionControllerState>;
37
42
  export type SubscriptionControllerEvents = SubscriptionControllerStateChangeEvent;
@@ -91,6 +96,7 @@ export declare class SubscriptionController extends BaseController<typeof contro
91
96
  * @returns The crypto approve transaction params
92
97
  */
93
98
  getCryptoApproveTransactionParams(request: GetCryptoApproveTransactionRequest): Promise<GetCryptoApproveTransactionResponse>;
99
+ updatePaymentMethod(opts: UpdatePaymentMethodOpts): Promise<void>;
94
100
  /**
95
101
  * Triggers an access token refresh.
96
102
  */
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.d.cts","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAEd,KAAK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wC,CAAC;AAGpE,MAAM,MAAM,+BAA+B,GAAG,mBAAmB,CAC/D,OAAO,cAAc,EACrB,6BAA6B,GAAG,cAAc,EAC9C,4BAA4B,GAAG,aAAa,EAC5C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,SAAS,EAAE,+BAA+B,CAAC;IAE3C;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAE7C;;OAEG;IACH,mBAAmB,EAAE,oBAAoB,CAAC;CAC3C,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,qCAAqC,IAAI,2BAA2B,CAInF;AAyBD,qBAAa,sBAAuB,SAAQ,cAAc,CACxD,OAAO,cAAc,EACrB,2BAA2B,EAC3B,+BAA+B,CAChC;;IAGC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,KAAK,EACL,mBAAmB,GACpB,EAAE,6BAA6B;IAwDhC;;;;OAIG;IACG,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;IAQtC,gBAAgB;IAWhB,kBAAkB,CAAC,OAAO,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE;IAkBtD,+BAA+B,CAAC,OAAO,EAAE,wBAAwB;IAWjE,2BAA2B,CAAC,OAAO,EAAE,8BAA8B;IAQzE;;;;;;;;;OASG;IACG,iCAAiC,CACrC,OAAO,EAAE,kCAAkC,GAC1C,OAAO,CAAC,mCAAmC,CAAC;IA8CzC,mBAAmB,CAAC,IAAI,EAAE,uBAAuB;IA4EvD;;OAEG;IACH,yBAAyB;CAgB1B"}
@@ -1,10 +1,11 @@
1
1
  import { BaseController, type ControllerStateChangeEvent, type ControllerGetStateAction, type RestrictedMessenger } from "@metamask/base-controller";
2
2
  import type { AuthenticationController } from "@metamask/profile-sync-controller";
3
3
  import { controllerName } from "./constants.mjs";
4
- import type { GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, StartCryptoSubscriptionRequest } from "./types.mjs";
4
+ import type { GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, StartCryptoSubscriptionRequest, UpdatePaymentMethodOpts } from "./types.mjs";
5
5
  import { type ISubscriptionService, type PricingResponse, type StartSubscriptionRequest, type Subscription } from "./types.mjs";
6
6
  export type SubscriptionControllerState = {
7
7
  subscriptions: Subscription[];
8
+ pricing?: PricingResponse;
8
9
  };
9
10
  export type SubscriptionControllerGetSubscriptionsAction = {
10
11
  type: `${typeof controllerName}:getSubscriptions`;
@@ -30,8 +31,12 @@ export type SubscriptionControllerStartSubscriptionWithCryptoAction = {
30
31
  type: `${typeof controllerName}:startSubscriptionWithCrypto`;
31
32
  handler: SubscriptionController['startSubscriptionWithCrypto'];
32
33
  };
34
+ export type SubscriptionControllerUpdatePaymentMethodAction = {
35
+ type: `${typeof controllerName}:updatePaymentMethod`;
36
+ handler: SubscriptionController['updatePaymentMethod'];
37
+ };
33
38
  export type SubscriptionControllerGetStateAction = ControllerGetStateAction<typeof controllerName, SubscriptionControllerState>;
34
- export type SubscriptionControllerActions = SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerCancelSubscriptionAction | SubscriptionControllerStartShieldSubscriptionWithCardAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetCryptoApproveTransactionParamsAction | SubscriptionControllerStartSubscriptionWithCryptoAction;
39
+ export type SubscriptionControllerActions = SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerCancelSubscriptionAction | SubscriptionControllerStartShieldSubscriptionWithCardAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetCryptoApproveTransactionParamsAction | SubscriptionControllerStartSubscriptionWithCryptoAction | SubscriptionControllerUpdatePaymentMethodAction;
35
40
  export type AllowedActions = AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerPerformSignOut;
36
41
  export type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, SubscriptionControllerState>;
37
42
  export type SubscriptionControllerEvents = SubscriptionControllerStateChangeEvent;
@@ -91,6 +96,7 @@ export declare class SubscriptionController extends BaseController<typeof contro
91
96
  * @returns The crypto approve transaction params
92
97
  */
93
98
  getCryptoApproveTransactionParams(request: GetCryptoApproveTransactionRequest): Promise<GetCryptoApproveTransactionResponse>;
99
+ updatePaymentMethod(opts: UpdatePaymentMethodOpts): Promise<void>;
94
100
  /**
95
101
  * Triggers an access token refresh.
96
102
  */
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.d.mts","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAEd,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,mBAAmB,EACzB,kCAAkC;AACnC,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAElF,OAAO,EACL,cAAc,EAEf,wBAAoB;AACrB,OAAO,KAAK,EACV,kCAAkC,EAClC,mCAAmC,EAEnC,8BAA8B,EAE/B,oBAAgB;AACjB,OAAO,EAGL,KAAK,oBAAoB,EACzB,KAAK,eAAe,EAEpB,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EAClB,oBAAgB;AAEjB,MAAM,MAAM,2BAA2B,GAAG;IACxC,aAAa,EAAE,YAAY,EAAE,CAAC;CAC/B,CAAC;AAGF,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,GAAG,OAAO,cAAc,mBAAmB,CAAC;IAClD,OAAO,EAAE,sBAAsB,CAAC,kBAAkB,CAAC,CAAC;CACrD,CAAC;AACF,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,GAAG,OAAO,cAAc,qBAAqB,CAAC;IACpD,OAAO,EAAE,sBAAsB,CAAC,oBAAoB,CAAC,CAAC;CACvD,CAAC;AACF,MAAM,MAAM,2DAA2D,GAAG;IACxE,IAAI,EAAE,GAAG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AEF;;GAEG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,SAAS,EAAE,+BAA+B,CAAC;IAE3C;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAE7C;;OAEG;IACH,mBAAmB,EAAE,oBAAoB,CAAC;CAC3C,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,qCAAqC,IAAI,2BAA2B,CAInF;AAmBD,qBAAa,sBAAuB,SAAQ,cAAc,CACxD,OAAO,cAAc,EACrB,2BAA2B,EAC3B,+BAA+B,CAChC;;IAGC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,KAAK,EACL,mBAAmB,GACpB,EAAE,6BAA6B;IAmDhC;;;;OAIG;IACG,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;IAItC,gBAAgB;IAWhB,kBAAkB,CAAC,OAAO,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE;IAkBtD,+BAA+B,CAAC,OAAO,EAAE,wBAAwB;IAWjE,2BAA2B,CAAC,OAAO,EAAE,8BAA8B;IAKzE;;;;;;;;;OASG;IACG,iCAAiC,CACrC,OAAO,EAAE,kCAAkC,GAC1C,OAAO,CAAC,mCAAmC,CAAC;IA6G/C;;OAEG;IACH,yBAAyB;CAgB1B"}
1
+ {"version":3,"file":"SubscriptionController.d.mts","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAEd,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,mBAAmB,EACzB,kCAAkC;AACnC,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAElF,OAAO,EACL,cAAc,EAEf,wBAAoB;AACrB,OAAO,KAAK,EACV,kCAAkC,EAClC,mCAAmC,EAEnC,8BAA8B,EAE9B,uBAAuB,EACxB,oBAAgB;AACjB,OAAO,EAGL,KAAK,oBAAoB,EACzB,KAAK,eAAe,EAEpB,KAAK,wBAAwB,EA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M,CAAA;KAAE;IAkBtD,+BAA+B,CAAC,OAAO,EAAE,wBAAwB;IAWjE,2BAA2B,CAAC,OAAO,EAAE,8BAA8B;IAQzE;;;;;;;;;OASG;IACG,iCAAiC,CACrC,OAAO,EAAE,kCAAkC,GAC1C,OAAO,CAAC,mCAAmC,CAAC;IA8CzC,mBAAmB,CAAC,IAAI,EAAE,uBAAuB;IA4EvD;;OAEG;IACH,yBAAyB;CAgB1B"}
@@ -37,6 +37,12 @@ const subscriptionControllerMetadata = {
37
37
  anonymous: false,
38
38
  usedInUi: true,
39
39
  },
40
+ pricing: {
41
+ includeInStateLogs: true,
42
+ persist: true,
43
+ anonymous: true,
44
+ usedInUi: true,
45
+ },
40
46
  };
41
47
  export class SubscriptionController extends BaseController {
42
48
  /**
@@ -68,7 +74,11 @@ export class SubscriptionController extends BaseController {
68
74
  * @returns The pricing information.
69
75
  */
70
76
  async getPricing() {
71
- return await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getPricing();
77
+ const pricing = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getPricing();
78
+ this.update((state) => {
79
+ state.pricing = pricing;
80
+ });
81
+ return pricing;
72
82
  }
73
83
  async getSubscriptions() {
74
84
  const { subscriptions } = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getSubscriptions();
@@ -97,7 +107,9 @@ export class SubscriptionController extends BaseController {
97
107
  }
98
108
  async startSubscriptionWithCrypto(request) {
99
109
  __classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_assertIsUserNotSubscribed).call(this, { products: request.products });
100
- return await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").startSubscriptionWithCrypto(request);
110
+ const response = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").startSubscriptionWithCrypto(request);
111
+ this.triggerAccessTokenRefresh();
112
+ return response;
101
113
  }
102
114
  /**
103
115
  * Get transaction params to create crypto approve transaction for subscription payment
@@ -139,6 +151,20 @@ export class SubscriptionController extends BaseController {
139
151
  chainId: request.chainId,
140
152
  };
141
153
  }
154
+ async updatePaymentMethod(opts) {
155
+ if (opts.paymentType === PaymentType.byCard) {
156
+ const { paymentType, ...cardRequest } = opts;
157
+ await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").updatePaymentMethodCard(cardRequest);
158
+ }
159
+ else if (opts.paymentType === PaymentType.byCrypto) {
160
+ const { paymentType, ...cryptoRequest } = opts;
161
+ await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").updatePaymentMethodCrypto(cryptoRequest);
162
+ }
163
+ else {
164
+ throw new Error('Invalid payment type');
165
+ }
166
+ await this.getSubscriptions();
167
+ }
142
168
  /**
143
169
  * Triggers an access token refresh.
144
170
  */
@@ -156,6 +182,7 @@ _SubscriptionController_subscriptionService = new WeakMap(), _SubscriptionContro
156
182
  this.messagingSystem.registerActionHandler('SubscriptionController:getPricing', this.getPricing.bind(this));
157
183
  this.messagingSystem.registerActionHandler('SubscriptionController:getCryptoApproveTransactionParams', this.getCryptoApproveTransactionParams.bind(this));
158
184
  this.messagingSystem.registerActionHandler('SubscriptionController:startSubscriptionWithCrypto', this.startSubscriptionWithCrypto.bind(this));
185
+ this.messagingSystem.registerActionHandler('SubscriptionController:updatePaymentMethod', this.updatePaymentMethod.bind(this));
159
186
  }, _SubscriptionController_getSubscriptionPriceAmount = function _SubscriptionController_getSubscriptionPriceAmount(price) {
160
187
  // no need to use BigInt since max unitDecimals are always 2 for price
161
188
  const amount = (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.mjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EAKf,kCAAkC;AAGnC,OAAO,EACL,cAAc,EACd,kCAAkC,EACnC,wBAAoB;AAQrB,OAAO,EACL,WAAW,EACX,kBAAkB,EAMnB,oBAAgB;AAsFjB;;;;G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B,CAAC,CAAC;KAC3E;AACH,CAAC,2GAYuB,OAAmC;IACzD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAC5B,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,KAAK,OAAO,CAAC,cAAc,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,CAAC;KACvE;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type StateMetadata,\n type ControllerStateChangeEvent,\n type ControllerGetStateAction,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport {\n controllerName,\n SubscriptionControllerErrorMessage,\n} from './constants';\nimport type {\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n} from './types';\nimport {\n PaymentType,\n SubscriptionStatus,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n subscriptions: Subscription[];\n};\n\n// Messenger Actions\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `${typeof controllerName}:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `${typeof controllerName}:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\nexport type SubscriptionControllerStartShieldSubscriptionWithCardAction = {\n type: `${typeof controllerName}:startShieldSubscriptionWithCard`;\n handler: SubscriptionController['startShieldSubscriptionWithCard'];\n};\nexport type SubscriptionControllerGetPricingAction = {\n type: `${typeof controllerName}:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `${typeof controllerName}:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `${typeof controllerName}:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerStartShieldSubscriptionWithCardAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction;\n\nexport type AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerPerformSignOut;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n AuthenticationController.AuthenticationControllerStateChangeEvent;\n\n// Messenger\nexport type SubscriptionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Subscription service to use for the subscription controller.\n */\n subscriptionService: ISubscriptionService;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n };\n\nexport class SubscriptionController extends BaseController<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n readonly #subscriptionService: ISubscriptionService;\n\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.subscriptionService - The subscription service for communicating with subscription server.\n */\n constructor({\n messenger,\n state,\n subscriptionService,\n }: SubscriptionControllerOptions) {\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.#subscriptionService = subscriptionService;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getSubscriptions',\n this.getSubscriptions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:cancelSubscription',\n this.cancelSubscription.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startShieldSubscriptionWithCard',\n this.startShieldSubscriptionWithCard.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getPricing',\n this.getPricing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getCryptoApproveTransactionParams',\n this.getCryptoApproveTransactionParams.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startSubscriptionWithCrypto',\n this.startSubscriptionWithCrypto.bind(this),\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n return await this.#subscriptionService.getPricing();\n }\n\n async getSubscriptions() {\n const { subscriptions } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n await this.#subscriptionService.cancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, status: SubscriptionStatus.canceled }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(request: StartSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response =\n await this.#subscriptionService.startSubscriptionWithCard(request);\n\n this.triggerAccessTokenRefresh();\n\n return response;\n }\n\n async startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n return await this.#subscriptionService.startSubscriptionWithCrypto(request);\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n async getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): Promise<GetCryptoApproveTransactionResponse> {\n const pricing = await this.getPricing();\n const product = pricing.products.find(\n (p) => p.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find((p) => p.interval === request.interval);\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = pricing.paymentMethods.find(\n (t) => t.type === PaymentType.byCrypto,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (t) => t.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (t) => t.address === request.paymentTokenAddress,\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.#getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount.toString(),\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n /**\n * Calculate total subscription price amount from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice) {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount =\n (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n #getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ) {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // conversion rate is a float string e.g: \"1.0\"\n // We need to handle float conversion rates with integer math for BigInt.\n // We'll scale the conversion rate to an integer by multiplying by 10^4.\n // conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)\n // So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)\n // This allows us to avoid floating point math and keep precision.\n const SCALE = 10n ** 4n;\n const conversionRateScaled =\n BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;\n // price of the product\n const priceAmount = this.#getSubscriptionPriceAmount(price);\n const priceAmountScaled =\n BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;\n\n const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);\n\n const tokenAmount =\n (priceAmountScaled * tokenDecimal) / conversionRateScaled;\n return tokenAmount;\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }) {\n if (\n this.state.subscriptions.find((subscription) =>\n subscription.products.some((p) => products.includes(p.name)),\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh() {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }) {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionController.mjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EAKf,kCAAkC;AAGnC,OAAO,EACL,cAAc,EACd,kCAAkC,EACnC,wBAAoB;AASrB,OAAO,EACL,WAAW,EACX,kBAAkB,EAMnB,oBAAgB;AA4FjB;;;;GAIG;AACH,MAAM,UAAU,qCAAqC;IACnD,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,8BAA8B,GAClC;IACE,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEJ,MAAM,OAAO,sBAAuB,SAAQ,cAI3C;IAGC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,KAAK,EACL,mBAAmB,GACW;QAC9B,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YAC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M,YAAY,GAAG,MAAM,CAAC,EAAE,CAAC,IAAI,MAAM,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IAErE,MAAM,WAAW,GACf,CAAC,iBAAiB,GAAG,YAAY,CAAC,GAAG,oBAAoB,CAAC;IAC5D,OAAO,WAAW,CAAC;AACrB,CAAC,iHAE0B,EAAE,QAAQ,EAA+B;IAClE,IACE,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAC7C,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,CAAC;KAC3E;AACH,CAAC,2GAYuB,OAAmC;IACzD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAC5B,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,KAAK,OAAO,CAAC,cAAc,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,CAAC;KACvE;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type StateMetadata,\n type ControllerStateChangeEvent,\n type ControllerGetStateAction,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport {\n controllerName,\n SubscriptionControllerErrorMessage,\n} from './constants';\nimport type {\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodOpts,\n} from './types';\nimport {\n PaymentType,\n SubscriptionStatus,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n subscriptions: Subscription[];\n pricing?: PricingResponse;\n};\n\n// Messenger Actions\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `${typeof controllerName}:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `${typeof controllerName}:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\nexport type SubscriptionControllerStartShieldSubscriptionWithCardAction = {\n type: `${typeof controllerName}:startShieldSubscriptionWithCard`;\n handler: SubscriptionController['startShieldSubscriptionWithCard'];\n};\nexport type SubscriptionControllerGetPricingAction = {\n type: `${typeof controllerName}:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `${typeof controllerName}:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `${typeof controllerName}:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\nexport type SubscriptionControllerUpdatePaymentMethodAction = {\n type: `${typeof controllerName}:updatePaymentMethod`;\n handler: SubscriptionController['updatePaymentMethod'];\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerStartShieldSubscriptionWithCardAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction\n | SubscriptionControllerUpdatePaymentMethodAction;\n\nexport type AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerPerformSignOut;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n AuthenticationController.AuthenticationControllerStateChangeEvent;\n\n// Messenger\nexport type SubscriptionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Subscription service to use for the subscription controller.\n */\n subscriptionService: ISubscriptionService;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n pricing: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n };\n\nexport class SubscriptionController extends BaseController<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n readonly #subscriptionService: ISubscriptionService;\n\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.subscriptionService - The subscription service for communicating with subscription server.\n */\n constructor({\n messenger,\n state,\n subscriptionService,\n }: SubscriptionControllerOptions) {\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.#subscriptionService = subscriptionService;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getSubscriptions',\n this.getSubscriptions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:cancelSubscription',\n this.cancelSubscription.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startShieldSubscriptionWithCard',\n this.startShieldSubscriptionWithCard.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getPricing',\n this.getPricing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getCryptoApproveTransactionParams',\n this.getCryptoApproveTransactionParams.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startSubscriptionWithCrypto',\n this.startSubscriptionWithCrypto.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:updatePaymentMethod',\n this.updatePaymentMethod.bind(this),\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n const pricing = await this.#subscriptionService.getPricing();\n this.update((state) => {\n state.pricing = pricing;\n });\n return pricing;\n }\n\n async getSubscriptions() {\n const { subscriptions } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n await this.#subscriptionService.cancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, status: SubscriptionStatus.canceled }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(request: StartSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response =\n await this.#subscriptionService.startSubscriptionWithCard(request);\n\n this.triggerAccessTokenRefresh();\n\n return response;\n }\n\n async startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n const response =\n await this.#subscriptionService.startSubscriptionWithCrypto(request);\n this.triggerAccessTokenRefresh();\n return response;\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n async getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): Promise<GetCryptoApproveTransactionResponse> {\n const pricing = await this.getPricing();\n const product = pricing.products.find(\n (p) => p.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find((p) => p.interval === request.interval);\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = pricing.paymentMethods.find(\n (t) => t.type === PaymentType.byCrypto,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (t) => t.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (t) => t.address === request.paymentTokenAddress,\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.#getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount.toString(),\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(opts: UpdatePaymentMethodOpts) {\n if (opts.paymentType === PaymentType.byCard) {\n const { paymentType, ...cardRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCard(cardRequest);\n } else if (opts.paymentType === PaymentType.byCrypto) {\n const { paymentType, ...cryptoRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCrypto(cryptoRequest);\n } else {\n throw new Error('Invalid payment type');\n }\n await this.getSubscriptions();\n }\n\n /**\n * Calculate total subscription price amount from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice) {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount =\n (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n #getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ) {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // conversion rate is a float string e.g: \"1.0\"\n // We need to handle float conversion rates with integer math for BigInt.\n // We'll scale the conversion rate to an integer by multiplying by 10^4.\n // conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)\n // So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)\n // This allows us to avoid floating point math and keep precision.\n const SCALE = 10n ** 4n;\n const conversionRateScaled =\n BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;\n // price of the product\n const priceAmount = this.#getSubscriptionPriceAmount(price);\n const priceAmountScaled =\n BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;\n\n const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);\n\n const tokenAmount =\n (priceAmountScaled * tokenDecimal) / conversionRateScaled;\n return tokenAmount;\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }) {\n if (\n this.state.subscriptions.find((subscription) =>\n subscription.products.some((p) => products.includes(p.name)),\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh() {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }) {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n}\n"]}
@@ -44,6 +44,20 @@ class SubscriptionService {
44
44
  const path = 'subscriptions/crypto';
45
45
  return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
46
46
  }
47
+ async updatePaymentMethodCard(request) {
48
+ const path = `subscriptions/${request.subscriptionId}/payment-method/card`;
49
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'PATCH', {
50
+ ...request,
51
+ subscriptionId: undefined,
52
+ });
53
+ }
54
+ async updatePaymentMethodCrypto(request) {
55
+ const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;
56
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'PATCH', {
57
+ ...request,
58
+ subscriptionId: undefined,
59
+ });
60
+ }
47
61
  async getPricing() {
48
62
  const path = 'pricing';
49
63
  return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.cjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAAyD;AAEzD,+CAIqB;AACrB,yCAAoD;AAiB7C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,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,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAA+B,IAAI,CAAC,CAAC;IACxD,CAAC;CACF;AA7ED,kDA6EC;6HArCC,KAAK,2CACH,IAAY,EACZ,SAAsD,KAAK,EAC3D,IAA8B;IAE9B,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,uBAAA,IAAI,mFAAwB,MAA5B,IAAI,CAA0B,CAAC;QACrD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAA,wBAAgB,EAAC,uBAAA,IAAI,gCAAK,EAAE,IAAI,CAAC,CAAC,CAAC;QAEvD,MAAM,QAAQ,GAAG,MAAM,IAAA,8BAAW,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE;YACjD,MAAM;YACN,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;aACX;YACD,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;KACjB;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAExE,MAAM,IAAI,iCAAwB,CAChC,2BAA2B,YAAY,EAAE,CAC1C,CAAC;KACH;AACH,CAAC,gDAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: { subscriptionId: string }): Promise<void> {\n const path = `subscriptions/${params.subscriptionId}`;\n return await this.#makeRequest(path, 'DELETE');\n }\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 const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionService.cjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAAyD;AAEzD,+CAIqB;AACrB,yCAAoD;AAmB7C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,IAAA,sBAAU,EAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AADxC,QAAA,gBAAgB,oBACwB;AAErD,MAAa,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,MAAkC;QACzD,MAAM,IAAI,GAAG,iBAAiB,MAAM,CAAC,cAAc,EAAE,CAAC;QACtD,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAC7B,OAAiC;QAEjC,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,MAAM,IAAI,iCAAwB,CAChC,8CAAkC,CAAC,yBAAyB,CAC7D,CAAC;SACH;Q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AAI,gCAAK,EAAE,IAAI,CAAC,CAAC,CAAC;QAEvD,MAAM,QAAQ,GAAG,MAAM,IAAA,8BAAW,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE;YACjD,MAAM;YACN,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;aACX;YACD,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;KACjB;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAExE,MAAM,IAAI,iCAAwB,CAChC,2BAA2B,YAAY,EAAE,CAC1C,CAAC;KACH;AACH,CAAC,gDAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCryptoRequest,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: { subscriptionId: string }): Promise<void> {\n const path = `subscriptions/${params.subscriptionId}`;\n return await this.#makeRequest(path, 'DELETE');\n }\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 const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type Env } from "./constants.cjs";
2
- import type { AuthUtils, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse } from "./types.cjs";
2
+ import type { AuthUtils, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCryptoRequest } from "./types.cjs";
3
3
  export type SubscriptionServiceConfig = {
4
4
  env: Env;
5
5
  auth: AuthUtils;
@@ -15,6 +15,8 @@ export declare class SubscriptionService implements ISubscriptionService {
15
15
  }): Promise<void>;
16
16
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
17
17
  startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
18
+ updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest): Promise<void>;
19
+ updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest): Promise<void>;
18
20
  getPricing(): Promise<PricingResponse>;
19
21
  }
20
22
  //# sourceMappingURL=SubscriptionService.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.d.cts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,GAAG,EACT,wBAAoB;AAErB,OAAO,KAAK,EACV,SAAS,EACT,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,+B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KvC,gBAAgB,IAAI,OAAO,CAAC,wBAAwB,CAAC;IAKrD,kBAAkB,CAAC,MAAM,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrE,yBAAyB,CAC7B,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC;IAW/B,2BAA2B,CAC/B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,+BAA+B,CAAC;IAKrC,uBAAuB,CAAC,OAAO,EAAE,8BAA8B;IAQ/D,yBAAyB,CAAC,OAAO,EAAE,gCAAgC;IAyCnE,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;CAI7C"}
@@ -1,5 +1,5 @@
1
1
  import { type Env } from "./constants.mjs";
2
- import type { AuthUtils, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse } from "./types.mjs";
2
+ import type { AuthUtils, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCryptoRequest } from "./types.mjs";
3
3
  export type SubscriptionServiceConfig = {
4
4
  env: Env;
5
5
  auth: AuthUtils;
@@ -15,6 +15,8 @@ export declare class SubscriptionService implements ISubscriptionService {
15
15
  }): Promise<void>;
16
16
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
17
17
  startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
18
+ updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest): Promise<void>;
19
+ updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest): Promise<void>;
18
20
  getPricing(): Promise<PricingResponse>;
19
21
  }
20
22
  //# sourceMappingURL=SubscriptionService.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.d.mts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,GAAG,EACT,wBAAoB;AAErB,OAAO,KAAK,EACV,SAAS,EACT,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EAC1B,oBAAgB;AAEjB,MAAM,MAAM,yBAAyB,GAAG;IACtC,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAS,GAAG,QAAQ,MAAM,WACH,CAAC;AAErD,qBAAa,mBAAoB,YAAW,oBAAoB;;IAGvD,SAAS,EAAE,SAAS,CAAC;gBAEhB,MAAM,EAAE,yBAAyB;IAKvC,gBAAgB,IAAI,OAAO,CAAC,wBAAwB,CAAC;IAKrD,kBAAkB,CAAC,MAAM,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrE,yBAAyB,CAC7B,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC;IAW/B,2BAA2B,CAC/B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,+BAA+B,CAAC;IAsCrC,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;CAI7C"}
1
+ {"version":3,"file":"SubscriptionService.d.mts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,GAAG,EACT,wBAAoB;AAErB,OAAO,KAAK,EACV,SAAS,EACT,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,8BAA8B,EAC9B,gCAAgC,EACjC,oBAAgB;AAEjB,MAAM,MAAM,yBAAyB,GAAG;IACtC,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAS,GAAG,QAAQ,MAAM,WACH,CAAC;AAErD,qBAAa,mBAAoB,YAAW,oBAAoB;;IAGvD,SAAS,EAAE,SAAS,CAAC;gBAEhB,MAAM,EAAE,yBAAyB;IAKvC,gBAAgB,IAAI,OAAO,CAAC,wBAAwB,CAAC;IAKrD,kBAAkB,CAAC,MAAM,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrE,yBAAyB,CAC7B,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC;IAW/B,2BAA2B,CAC/B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,+BAA+B,CAAC;IAKrC,uBAAuB,CAAC,OAAO,EAAE,8BAA8B;IAQ/D,yBAAyB,CAAC,OAAO,EAAE,gCAAgC;IAyCnE,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;CAI7C"}
@@ -40,6 +40,20 @@ export class SubscriptionService {
40
40
  const path = 'subscriptions/crypto';
41
41
  return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
42
42
  }
43
+ async updatePaymentMethodCard(request) {
44
+ const path = `subscriptions/${request.subscriptionId}/payment-method/card`;
45
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'PATCH', {
46
+ ...request,
47
+ subscriptionId: undefined,
48
+ });
49
+ }
50
+ async updatePaymentMethodCrypto(request) {
51
+ const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;
52
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'PATCH', {
53
+ ...request,
54
+ subscriptionId: undefined,
55
+ });
56
+ }
43
57
  async getPricing() {
44
58
  const path = 'pricing';
45
59
  return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EACL,UAAU,EACV,kCAAkC,EAEnC,wBAAoB;AACrB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AAiBpD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AAErD,MAAM,OAAO,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,MAAkC;QACzD,MAAM,IAAI,GAAG,iBAAiB,MAAM,CAAC,cAAc,EAAE,CAAC;QACtD,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAC7B,OAAiC;QAEjC,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,MAAM,IAAI,wBAAwB,CAChC,kCAAkC,CAAC,yBAAyB,CAC7D,CAAC;SACH;QACD,MAAM,IAAI,GAAG,oBAAoB,CAAC;QAElC,OAAO,MAAM,uBAAA,IAAI,wEAA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,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: { subscriptionId: string }): Promise<void> {\n const path = `subscriptions/${params.subscriptionId}`;\n return await this.#makeRequest(path, 'DELETE');\n }\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 const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EACL,UAAU,EACV,kCAAkC,EAEnC,wBAAoB;AACrB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AAmBpD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AAErD,MAAM,OAAO,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IA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CAAC,UAAU;QACd,MAAM,IAAI,GAAG,SAAS,CAAC;QACvB,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAA+B,IAAI,CAAC,CAAC;IACxD,CAAC;CACF;6HArCC,KAAK,2CACH,IAAY,EACZ,SAAsD,KAAK,EAC3D,IAA8B;IAE9B,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,uBAAA,IAAI,mFAAwB,MAA5B,IAAI,CAA0B,CAAC;QACrD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,uBAAA,IAAI,gCAAK,EAAE,IAAI,CAAC,CAAC,CAAC;QAEvD,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE;YACjD,MAAM;YACN,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;aACX;YACD,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;KACjB;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAExE,MAAM,IAAI,wBAAwB,CAChC,2BAA2B,YAAY,EAAE,CAC1C,CAAC;KACH;AACH,CAAC,gDAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCryptoRequest,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: { subscriptionId: string }): Promise<void> {\n const path = `subscriptions/${params.subscriptionId}`;\n return await this.#makeRequest(path, 'DELETE');\n }\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 const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAeA,uEAGkC;AAFhC,gIAAA,sBAAsB,OAAA;AACtB,+IAAA,qCAAqC,OAAA;AAyBvC,uCAAoD;AAA3C,kHAAA,wBAAwB,OAAA;AACjC,6CAAsE;AAA7D,gGAAA,GAAG,OAAA;AAAE,+HAAA,kCAAkC,OAAA;AAEhD,iEAA4D;AAAnD,0HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAeA,uEAGkC;AAFhC,gIAAA,sBAAsB,OAAA;AACtB,+IAAA,qCAAqC,OAAA;AA0BvC,uCAAoD;AAA3C,kHAAA,wBAAwB,OAAA;AACjC,6CAAsE;AAA7D,gGAAA,GAAG,OAAA;AAAE,+HAAA,kCAAkC,OAAA;AAEhD,iEAA4D;AAAnD,0HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type { SubscriptionControllerActions, SubscriptionControllerState, SubscriptionControllerEvents, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerCancelSubscriptionAction, SubscriptionControllerStartShieldSubscriptionWithCardAction, SubscriptionControllerGetPricingAction, SubscriptionControllerGetCryptoApproveTransactionParamsAction, SubscriptionControllerStartSubscriptionWithCryptoAction, SubscriptionControllerGetStateAction, SubscriptionControllerMessenger, SubscriptionControllerOptions, SubscriptionControllerStateChangeEvent, } from "./SubscriptionController.cjs";
2
2
  export { SubscriptionController, getDefaultSubscriptionControllerState, } from "./SubscriptionController.cjs";
3
- export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, } from "./types.cjs";
3
+ export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, } from "./types.cjs";
4
4
  export { SubscriptionServiceError } from "./errors.cjs";
5
5
  export { Env, SubscriptionControllerErrorMessage } from "./constants.cjs";
6
6
  export type { SubscriptionServiceConfig } from "./SubscriptionService.cjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,GAChB,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,EACf,uBAAuB,GACxB,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  export type { SubscriptionControllerActions, SubscriptionControllerState, SubscriptionControllerEvents, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerCancelSubscriptionAction, SubscriptionControllerStartShieldSubscriptionWithCardAction, SubscriptionControllerGetPricingAction, SubscriptionControllerGetCryptoApproveTransactionParamsAction, SubscriptionControllerStartSubscriptionWithCryptoAction, SubscriptionControllerGetStateAction, SubscriptionControllerMessenger, SubscriptionControllerOptions, SubscriptionControllerStateChangeEvent, } from "./SubscriptionController.mjs";
2
2
  export { SubscriptionController, getDefaultSubscriptionControllerState, } from "./SubscriptionController.mjs";
3
- export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, } from "./types.mjs";
3
+ export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, } from "./types.mjs";
4
4
  export { SubscriptionServiceError } from "./errors.mjs";
5
5
  export { Env, SubscriptionControllerErrorMessage } from "./constants.mjs";
6
6
  export type { SubscriptionServiceConfig } from "./SubscriptionService.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,GAChB,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,EACf,uBAAuB,GACxB,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACtC,qCAAiC;AAwBlC,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AAEtE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACtC,qCAAiC;AAyBlC,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AAEtE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,gCAAiB,CAAA;AACnB,CAAC,EAFW,WAAW,2BAAX,WAAW,QAEtB;AAYD,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,8BAAe,CAAA;IACf,kCAAmB,CAAA;AACrB,CAAC,EAHW,WAAW,2BAAX,WAAW,QAGtB;AAED,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,oCAAe,CAAA;IACf,kCAAa,CAAA;AACf,CAAC,EAHW,iBAAiB,iCAAjB,iBAAiB,QAG5B;AAED,IAAY,kBAmBX;AAnBD,WAAY,kBAAkB;IAC5B,iBAAiB;IACjB,+CAAyB,CAAA;IACzB,8DAAwC,CAAA;IAExC,gBAAgB;IAChB,iDAA2B,CAAA;IAC3B,2CAAqB,CAAA;IACrB,uCAAiB,CAAA;IAEjB,iBAAiB;IACjB,0CAAoB,CAAA;IACpB,uCAAiB,CAAA;IAEjB,mBAAmB;IACnB,2CAAqB,CAAA;IAErB,gBAAgB;IAChB,uCAAiB,CAAA;AACnB,CAAC,EAnBW,kBAAkB,kCAAlB,kBAAkB,QAmB7B","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nexport enum ProductType {\n SHIELD = 'shield',\n}\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n id: string;\n currency: Currency;\n amount: number;\n};\n\nexport enum PaymentType {\n byCard = 'card',\n byCrypto = 'crypto',\n}\n\nexport enum RecurringInterval {\n month = 'month',\n year = 'year',\n}\n\nexport enum SubscriptionStatus {\n // Initial states\n incomplete = 'incomplete',\n incompleteExpired = 'incomplete_expired',\n\n // Active states\n provisional = 'provisional',\n trialing = 'trialing',\n active = 'active',\n\n // Payment issues\n pastDue = 'past_due',\n unpaid = 'unpaid',\n\n // Cancelled states\n canceled = 'canceled',\n\n // Paused states\n paused = 'paused',\n}\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart: string; // ISO 8601\n currentPeriodEnd: string; // ISO 8601\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n};\n\nexport type SubscriptionPaymentMethod = {\n type: PaymentType;\n crypto?: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n };\n};\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\nexport type StartCryptoSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n rawTransaction: Hex;\n};\n\nexport type StartCryptoSubscriptionResponse = {\n subscriptionId: string;\n status: SubscriptionStatus;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n minBillingCycles: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\nexport type TokenPaymentInfo = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate: {\n usd: string;\n };\n};\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n tokens: TokenPaymentInfo[];\n};\n\nexport type PricingPaymentMethod = {\n type: PaymentType;\n chains?: ChainPaymentInfo[];\n};\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n cancelSubscription(request: { subscriptionId: string }): Promise<void>;\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n};\n"]}
1
+ {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,gCAAiB,CAAA;AACnB,CAAC,EAFW,WAAW,2BAAX,WAAW,QAEtB;AAYD,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,8BAAe,CAAA;IACf,kCAAmB,CAAA;AACrB,CAAC,EAHW,WAAW,2BAAX,WAAW,QAGtB;AAED,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,oCAAe,CAAA;IACf,kCAAa,CAAA;AACf,CAAC,EAHW,iBAAiB,iCAAjB,iBAAiB,QAG5B;AAED,IAAY,kBAmBX;AAnBD,WAAY,kBAAkB;IAC5B,iBAAiB;IACjB,+CAAyB,CAAA;IACzB,8DAAwC,CAAA;IAExC,gBAAgB;IAChB,iDAA2B,CAAA;IAC3B,2CAAqB,CAAA;IACrB,uCAAiB,CAAA;IAEjB,iBAAiB;IACjB,0CAAoB,CAAA;IACpB,uCAAiB,CAAA;IAEjB,mBAAmB;IACnB,2CAAqB,CAAA;IAErB,gBAAgB;IAChB,uCAAiB,CAAA;AACnB,CAAC,EAnBW,kBAAkB,kCAAlB,kBAAkB,QAmB7B","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nexport enum ProductType {\n SHIELD = 'shield',\n}\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n id: string;\n currency: Currency;\n amount: number;\n};\n\nexport enum PaymentType {\n byCard = 'card',\n byCrypto = 'crypto',\n}\n\nexport enum RecurringInterval {\n month = 'month',\n year = 'year',\n}\n\nexport enum SubscriptionStatus {\n // Initial states\n incomplete = 'incomplete',\n incompleteExpired = 'incomplete_expired',\n\n // Active states\n provisional = 'provisional',\n trialing = 'trialing',\n active = 'active',\n\n // Payment issues\n pastDue = 'past_due',\n unpaid = 'unpaid',\n\n // Cancelled states\n canceled = 'canceled',\n\n // Paused states\n paused = 'paused',\n}\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart: string; // ISO 8601\n currentPeriodEnd: string; // ISO 8601\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n};\n\nexport type SubscriptionPaymentMethod = {\n type: PaymentType;\n crypto?: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n };\n};\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\nexport type StartCryptoSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n rawTransaction: Hex;\n};\n\nexport type StartCryptoSubscriptionResponse = {\n subscriptionId: string;\n status: SubscriptionStatus;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n minBillingCycles: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\nexport type TokenPaymentInfo = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate: {\n usd: string;\n };\n};\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n tokens: TokenPaymentInfo[];\n};\n\nexport type PricingPaymentMethod = {\n type: PaymentType;\n chains?: ChainPaymentInfo[];\n};\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n cancelSubscription(request: { subscriptionId: string }): Promise<void>;\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<void>;\n updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void>;\n};\n\nexport type UpdatePaymentMethodOpts =\n | ({\n paymentType: PaymentType.byCard;\n } & UpdatePaymentMethodCardRequest)\n | ({\n paymentType: PaymentType.byCrypto;\n } & UpdatePaymentMethodCryptoRequest);\n\nexport type UpdatePaymentMethodCardRequest = {\n /**\n * Subscription ID\n */\n subscriptionId: string;\n\n /**\n * Recurring interval\n */\n recurringInterval: RecurringInterval;\n};\n\nexport type UpdatePaymentMethodCryptoRequest = {\n subscriptionId: string;\n chainId: Hex;\n payerAddress: Hex;\n tokenSymbol: string;\n rawTransaction: Hex;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n"]}
package/dist/types.d.cts CHANGED
@@ -154,5 +154,31 @@ export type ISubscriptionService = {
154
154
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
155
155
  getPricing(): Promise<PricingResponse>;
156
156
  startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
157
+ updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest): Promise<void>;
158
+ updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest): Promise<void>;
159
+ };
160
+ export type UpdatePaymentMethodOpts = ({
161
+ paymentType: PaymentType.byCard;
162
+ } & UpdatePaymentMethodCardRequest) | ({
163
+ paymentType: PaymentType.byCrypto;
164
+ } & UpdatePaymentMethodCryptoRequest);
165
+ export type UpdatePaymentMethodCardRequest = {
166
+ /**
167
+ * Subscription ID
168
+ */
169
+ subscriptionId: string;
170
+ /**
171
+ * Recurring interval
172
+ */
173
+ recurringInterval: RecurringInterval;
174
+ };
175
+ export type UpdatePaymentMethodCryptoRequest = {
176
+ subscriptionId: string;
177
+ chainId: Hex;
178
+ payerAddress: Hex;
179
+ tokenSymbol: string;
180
+ rawTransaction: Hex;
181
+ recurringInterval: RecurringInterval;
182
+ billingCycles: number;
157
183
  };
158
184
  //# sourceMappingURL=types.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,oBAAY,WAAW;IACrB,MAAM,WAAW;CAClB;AAED,uBAAuB;AACvB,MAAM,MAAM,QAAQ,GAAG,KAAK,CAAC;AAE7B,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,WAAW,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,oBAAY,WAAW;IACrB,MAAM,SAAS;IACf,QAAQ,WAAW;CACpB;AAED,oBAAY,iBAAiB;IAC3B,KAAK,UAAU;IACf,IAAI,S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EAAE,WAAW,CAAC,MAAM,CAAC;CACjC,GAAG,8BAA8B,CAAC,GACnC,CAAC;IACC,WAAW,EAAE,WAAW,CAAC,QAAQ,CAAC;CACnC,GAAG,gCAAgC,CAAC,CAAC;AAE1C,MAAM,MAAM,8BAA8B,GAAG;IAC3C;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IAEvB;;OAEG;IACH,iBAAiB,EAAE,iBAAiB,CAAC;CACtC,CAAC;AAEF,MAAM,MAAM,gCAAgC,GAAG;IAC7C,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,GAAG,CAAC;IACb,YAAY,EAAE,GAAG,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,GAAG,CAAC;IACpB,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC"}
package/dist/types.d.mts CHANGED
@@ -154,5 +154,31 @@ export type ISubscriptionService = {
154
154
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
155
155
  getPricing(): Promise<PricingResponse>;
156
156
  startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
157
+ updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest): Promise<void>;
158
+ updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest): Promise<void>;
159
+ };
160
+ export type UpdatePaymentMethodOpts = ({
161
+ paymentType: PaymentType.byCard;
162
+ } & UpdatePaymentMethodCardRequest) | ({
163
+ paymentType: PaymentType.byCrypto;
164
+ } & UpdatePaymentMethodCryptoRequest);
165
+ export type UpdatePaymentMethodCardRequest = {
166
+ /**
167
+ * Subscription ID
168
+ */
169
+ subscriptionId: string;
170
+ /**
171
+ * Recurring interval
172
+ */
173
+ recurringInterval: RecurringInterval;
174
+ };
175
+ export type UpdatePaymentMethodCryptoRequest = {
176
+ subscriptionId: string;
177
+ chainId: Hex;
178
+ payerAddress: Hex;
179
+ tokenSymbol: string;
180
+ rawTransaction: Hex;
181
+ recurringInterval: RecurringInterval;
182
+ billingCycles: number;
157
183
  };
158
184
  //# sourceMappingURL=types.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,oBAAY,WAAW;IACrB,MAAM,WAAW;CAClB;AAED,uBAAuB;AACvB,MAAM,MAAM,QAAQ,GAAG,KAAK,CAAC;AAE7B,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,WAAW,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,oBAAY,WAAW;IACrB,MAAM,SAAS;IACf,QAAQ,WAAW;CACpB;AAED,oBAAY,iBAAiB;IAC3B,KAAK,UAAU;IACf,IAAI,SAAS;CACd;AAED,oBAAY,kBAAkB;IAE5B,UAAU,eAAe;IACzB,iBAAiB,uBAAuB;IAGxC,WAAW,gBAAgB;IAC3B,QAAQ,aAAa;IACrB,MAAM,WAAW;IAGjB,OAAO,aAAa;IACpB,MAAM,WAAW;IAGjB,QAAQ,aAAa;IAGrB,MAAM,WAAW;CAClB;AAGD,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,aAAa,EAAE,yBAAyB,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,CAAC,EAAE;QACP,YAAY,EAAE,GAAG,CAAC;QA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[],"mappings":"AAEA,MAAM,CAAN,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,gCAAiB,CAAA;AACnB,CAAC,EAFW,WAAW,KAAX,WAAW,QAEtB;AAYD,MAAM,CAAN,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,8BAAe,CAAA;IACf,kCAAmB,CAAA;AACrB,CAAC,EAHW,WAAW,KAAX,WAAW,QAGtB;AAED,MAAM,CAAN,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,oCAAe,CAAA;IACf,kCAAa,CAAA;AACf,CAAC,EAHW,iBAAiB,KAAjB,iBAAiB,QAG5B;AAED,MAAM,CAAN,IAAY,kBAmBX;AAnBD,WAAY,kBAAkB;IAC5B,iBAAiB;IACjB,+CAAyB,CAAA;IACzB,8DAAwC,CAAA;IAExC,gBAAgB;IAChB,iDAA2B,CAAA;IAC3B,2CAAqB,CAAA;IACrB,uCAAiB,CAAA;IAEjB,iBAAiB;IACjB,0CAAoB,CAAA;IACpB,uCAAiB,CAAA;IAEjB,mBAAmB;IACnB,2CAAqB,CAAA;IAErB,gBAAgB;IAChB,uCAAiB,CAAA;AACnB,CAAC,EAnBW,kBAAkB,KAAlB,kBAAkB,QAmB7B","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nexport enum ProductType {\n SHIELD = 'shield',\n}\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n id: string;\n currency: Currency;\n amount: number;\n};\n\nexport enum PaymentType {\n byCard = 'card',\n byCrypto = 'crypto',\n}\n\nexport enum RecurringInterval {\n month = 'month',\n year = 'year',\n}\n\nexport enum SubscriptionStatus {\n // Initial states\n incomplete = 'incomplete',\n incompleteExpired = 'incomplete_expired',\n\n // Active states\n provisional = 'provisional',\n trialing = 'trialing',\n active = 'active',\n\n // Payment issues\n pastDue = 'past_due',\n unpaid = 'unpaid',\n\n // Cancelled states\n canceled = 'canceled',\n\n // Paused states\n paused = 'paused',\n}\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart: string; // ISO 8601\n currentPeriodEnd: string; // ISO 8601\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n};\n\nexport type SubscriptionPaymentMethod = {\n type: PaymentType;\n crypto?: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n };\n};\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\nexport type StartCryptoSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n rawTransaction: Hex;\n};\n\nexport type StartCryptoSubscriptionResponse = {\n subscriptionId: string;\n status: SubscriptionStatus;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n minBillingCycles: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\nexport type TokenPaymentInfo = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate: {\n usd: string;\n };\n};\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n tokens: TokenPaymentInfo[];\n};\n\nexport type PricingPaymentMethod = {\n type: PaymentType;\n chains?: ChainPaymentInfo[];\n};\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n cancelSubscription(request: { subscriptionId: string }): Promise<void>;\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n};\n"]}
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,gCAAiB,CAAA;AACnB,CAAC,EAFW,WAAW,KAAX,WAAW,QAEtB;AAYD,MAAM,CAAN,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,8BAAe,CAAA;IACf,kCAAmB,CAAA;AACrB,CAAC,EAHW,WAAW,KAAX,WAAW,QAGtB;AAED,MAAM,CAAN,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,oCAAe,CAAA;IACf,kCAAa,CAAA;AACf,CAAC,EAHW,iBAAiB,KAAjB,iBAAiB,QAG5B;AAED,MAAM,CAAN,IAAY,kBAmBX;AAnBD,WAAY,kBAAkB;IAC5B,iBAAiB;IACjB,+CAAyB,CAAA;IACzB,8DAAwC,CAAA;IAExC,gBAAgB;IAChB,iDAA2B,CAAA;IAC3B,2CAAqB,CAAA;IACrB,uCAAiB,CAAA;IAEjB,iBAAiB;IACjB,0CAAoB,CAAA;IACpB,uCAAiB,CAAA;IAEjB,mBAAmB;IACnB,2CAAqB,CAAA;IAErB,gBAAgB;IAChB,uCAAiB,CAAA;AACnB,CAAC,EAnBW,kBAAkB,KAAlB,kBAAkB,QAmB7B","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nexport enum ProductType {\n SHIELD = 'shield',\n}\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n id: string;\n currency: Currency;\n amount: number;\n};\n\nexport enum PaymentType {\n byCard = 'card',\n byCrypto = 'crypto',\n}\n\nexport enum RecurringInterval {\n month = 'month',\n year = 'year',\n}\n\nexport enum SubscriptionStatus {\n // Initial states\n incomplete = 'incomplete',\n incompleteExpired = 'incomplete_expired',\n\n // Active states\n provisional = 'provisional',\n trialing = 'trialing',\n active = 'active',\n\n // Payment issues\n pastDue = 'past_due',\n unpaid = 'unpaid',\n\n // Cancelled states\n canceled = 'canceled',\n\n // Paused states\n paused = 'paused',\n}\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart: string; // ISO 8601\n currentPeriodEnd: string; // ISO 8601\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n};\n\nexport type SubscriptionPaymentMethod = {\n type: PaymentType;\n crypto?: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n };\n};\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\nexport type StartCryptoSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n rawTransaction: Hex;\n};\n\nexport type StartCryptoSubscriptionResponse = {\n subscriptionId: string;\n status: SubscriptionStatus;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n minBillingCycles: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\nexport type TokenPaymentInfo = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate: {\n usd: string;\n };\n};\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n tokens: TokenPaymentInfo[];\n};\n\nexport type PricingPaymentMethod = {\n type: PaymentType;\n chains?: ChainPaymentInfo[];\n};\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n cancelSubscription(request: { subscriptionId: string }): Promise<void>;\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<void>;\n updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void>;\n};\n\nexport type UpdatePaymentMethodOpts =\n | ({\n paymentType: PaymentType.byCard;\n } & UpdatePaymentMethodCardRequest)\n | ({\n paymentType: PaymentType.byCrypto;\n } & UpdatePaymentMethodCryptoRequest);\n\nexport type UpdatePaymentMethodCardRequest = {\n /**\n * Subscription ID\n */\n subscriptionId: string;\n\n /**\n * Recurring interval\n */\n recurringInterval: RecurringInterval;\n};\n\nexport type UpdatePaymentMethodCryptoRequest = {\n subscriptionId: string;\n chainId: Hex;\n payerAddress: Hex;\n tokenSymbol: string;\n rawTransaction: Hex;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/subscription-controller",
3
- "version": "0.0.0-preview-ea6406b3",
3
+ "version": "0.0.0-preview-9a5f096",
4
4
  "description": "Handle user subscription",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -53,7 +53,7 @@
53
53
  },
54
54
  "devDependencies": {
55
55
  "@metamask/auto-changelog": "^3.4.4",
56
- "@metamask/profile-sync-controller": "^24.0.0",
56
+ "@metamask/profile-sync-controller": "^25.0.0",
57
57
  "@types/jest": "^27.4.1",
58
58
  "deepmerge": "^4.2.2",
59
59
  "jest": "^27.5.1",