@metamask/subscription-controller 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/LICENSE +20 -0
- package/README.md +19 -0
- package/dist/SubscriptionController.cjs +266 -0
- package/dist/SubscriptionController.cjs.map +1 -0
- package/dist/SubscriptionController.d.cts +124 -0
- package/dist/SubscriptionController.d.cts.map +1 -0
- package/dist/SubscriptionController.d.mts +124 -0
- package/dist/SubscriptionController.d.mts.map +1 -0
- package/dist/SubscriptionController.mjs +261 -0
- package/dist/SubscriptionController.mjs.map +1 -0
- package/dist/SubscriptionService.cjs +97 -0
- package/dist/SubscriptionService.cjs.map +1 -0
- package/dist/SubscriptionService.d.cts +26 -0
- package/dist/SubscriptionService.d.cts.map +1 -0
- package/dist/SubscriptionService.d.mts +26 -0
- package/dist/SubscriptionService.d.mts.map +1 -0
- package/dist/SubscriptionService.mjs +92 -0
- package/dist/SubscriptionService.mjs.map +1 -0
- package/dist/constants.cjs +42 -0
- package/dist/constants.cjs.map +1 -0
- package/dist/constants.d.cts +24 -0
- package/dist/constants.d.cts.map +1 -0
- package/dist/constants.d.mts +24 -0
- package/dist/constants.d.mts.map +1 -0
- package/dist/constants.mjs +38 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/errors.cjs +11 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +4 -0
- package/dist/errors.d.cts.map +1 -0
- package/dist/errors.d.mts +4 -0
- package/dist/errors.d.mts.map +1 -0
- package/dist/errors.mjs +7 -0
- package/dist/errors.mjs.map +1 -0
- package/dist/index.cjs +19 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +9 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +6 -0
- package/dist/index.mjs.map +1 -0
- package/dist/types.cjs +31 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +211 -0
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.mts +211 -0
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +28 -0
- package/dist/types.mjs.map +1 -0
- package/package.json +75 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.1.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Initial release of the subscription controller ([#6233](https://github.com/MetaMask/core/pull/6233))
|
|
15
|
+
- `getSubscription`: Retrieve current user subscription info if exist.
|
|
16
|
+
- `cancelSubscription`: Cancel user active subscription.
|
|
17
|
+
- `startShieldSubscriptionWithCard`: start shield subscription via card (with trial option) ([#6300](https://github.com/MetaMask/core/pull/6300))
|
|
18
|
+
- Add `getPricing` method ([#6356](https://github.com/MetaMask/core/pull/6356))
|
|
19
|
+
- Add methods `startSubscriptionWithCrypto` and `getCryptoApproveTransactionParams` method ([#6456](https://github.com/MetaMask/core/pull/6456))
|
|
20
|
+
- Added `triggerAccessTokenRefresh` to trigger an access token refresh ([#6374](https://github.com/MetaMask/core/pull/6374))
|
|
21
|
+
- Add two new controller state metadata properties: `includeInStateLogs` and `usedInUi` ([#6504](https://github.com/MetaMask/core/pull/6504))
|
|
22
|
+
- Added `updatePaymentMethodCard` and `updatePaymentMethodCrypto` methods ([#6539](https://github.com/MetaMask/core/pull/6539))
|
|
23
|
+
- Added `getBillingPortalUrl` method ([#6580](https://github.com/MetaMask/core/pull/6580))
|
|
24
|
+
- Added `unCancelSubscription` method ([#6596](https://github.com/MetaMask/core/pull/6596))
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- Bump `@metamask/controller-utils` from `^11.12.0` to `^11.14.0` ([#6620](https://github.com/MetaMask/core/pull/6620), [#6629](https://github.com/MetaMask/core/pull/6629))
|
|
29
|
+
- Bump `@metamask/utils` from `^11.4.2` to `^11.8.0` ([#6588](https://github.com/MetaMask/core/pull/6588))
|
|
30
|
+
|
|
31
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/subscription-controller@0.1.0...HEAD
|
|
32
|
+
[0.1.0]: https://github.com/MetaMask/core/releases/tag/@metamask/subscription-controller@0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 MetaMask
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
package/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# `@metamask/subscription-controller`
|
|
2
|
+
|
|
3
|
+
Handle user subscription
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
`yarn add @metamask/subscription-controller`
|
|
8
|
+
|
|
9
|
+
or
|
|
10
|
+
|
|
11
|
+
`npm install @metamask/subscription-controller`
|
|
12
|
+
|
|
13
|
+
## Architecture
|
|
14
|
+
|
|
15
|
+
[Reference](./ARCHITECTURE.md)
|
|
16
|
+
|
|
17
|
+
## Contributing
|
|
18
|
+
|
|
19
|
+
This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _SubscriptionController_instances, _SubscriptionController_subscriptionService, _SubscriptionController_registerMessageHandlers, _SubscriptionController_getSubscriptionPriceAmount, _SubscriptionController_assertIsUserNotSubscribed, _SubscriptionController_assertIsUserSubscribed;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.SubscriptionController = exports.getDefaultSubscriptionControllerState = void 0;
|
|
16
|
+
const base_controller_1 = require("@metamask/base-controller");
|
|
17
|
+
const constants_1 = require("./constants.cjs");
|
|
18
|
+
const types_1 = require("./types.cjs");
|
|
19
|
+
/**
|
|
20
|
+
* Get the default state for the Subscription Controller.
|
|
21
|
+
*
|
|
22
|
+
* @returns The default state for the Subscription Controller.
|
|
23
|
+
*/
|
|
24
|
+
function getDefaultSubscriptionControllerState() {
|
|
25
|
+
return {
|
|
26
|
+
subscriptions: [],
|
|
27
|
+
trialedProducts: [],
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
exports.getDefaultSubscriptionControllerState = getDefaultSubscriptionControllerState;
|
|
31
|
+
/**
|
|
32
|
+
* Seedless Onboarding Controller State Metadata.
|
|
33
|
+
*
|
|
34
|
+
* This allows us to choose if fields of the state should be persisted or not
|
|
35
|
+
* using the `persist` flag; and if they can be sent to Sentry or not, using
|
|
36
|
+
* the `anonymous` flag.
|
|
37
|
+
*/
|
|
38
|
+
const subscriptionControllerMetadata = {
|
|
39
|
+
subscriptions: {
|
|
40
|
+
includeInStateLogs: true,
|
|
41
|
+
persist: true,
|
|
42
|
+
anonymous: false,
|
|
43
|
+
usedInUi: true,
|
|
44
|
+
},
|
|
45
|
+
customerId: {
|
|
46
|
+
includeInStateLogs: true,
|
|
47
|
+
persist: true,
|
|
48
|
+
anonymous: false,
|
|
49
|
+
usedInUi: true,
|
|
50
|
+
},
|
|
51
|
+
trialedProducts: {
|
|
52
|
+
includeInStateLogs: true,
|
|
53
|
+
persist: true,
|
|
54
|
+
anonymous: true,
|
|
55
|
+
usedInUi: true,
|
|
56
|
+
},
|
|
57
|
+
pricing: {
|
|
58
|
+
includeInStateLogs: true,
|
|
59
|
+
persist: true,
|
|
60
|
+
anonymous: true,
|
|
61
|
+
usedInUi: true,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
class SubscriptionController extends base_controller_1.BaseController {
|
|
65
|
+
/**
|
|
66
|
+
* Creates a new SubscriptionController instance.
|
|
67
|
+
*
|
|
68
|
+
* @param options - The options for the SubscriptionController.
|
|
69
|
+
* @param options.messenger - A restricted messenger.
|
|
70
|
+
* @param options.state - Initial state to set on this controller.
|
|
71
|
+
* @param options.subscriptionService - The subscription service for communicating with subscription server.
|
|
72
|
+
*/
|
|
73
|
+
constructor({ messenger, state, subscriptionService, }) {
|
|
74
|
+
super({
|
|
75
|
+
name: constants_1.controllerName,
|
|
76
|
+
metadata: subscriptionControllerMetadata,
|
|
77
|
+
state: {
|
|
78
|
+
...getDefaultSubscriptionControllerState(),
|
|
79
|
+
...state,
|
|
80
|
+
},
|
|
81
|
+
messenger,
|
|
82
|
+
});
|
|
83
|
+
_SubscriptionController_instances.add(this);
|
|
84
|
+
_SubscriptionController_subscriptionService.set(this, void 0);
|
|
85
|
+
__classPrivateFieldSet(this, _SubscriptionController_subscriptionService, subscriptionService, "f");
|
|
86
|
+
__classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_registerMessageHandlers).call(this);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Gets the pricing information from the subscription service.
|
|
90
|
+
*
|
|
91
|
+
* @returns The pricing information.
|
|
92
|
+
*/
|
|
93
|
+
async getPricing() {
|
|
94
|
+
const pricing = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getPricing();
|
|
95
|
+
this.update((state) => {
|
|
96
|
+
state.pricing = pricing;
|
|
97
|
+
});
|
|
98
|
+
return pricing;
|
|
99
|
+
}
|
|
100
|
+
async getSubscriptions() {
|
|
101
|
+
const { subscriptions, customerId, trialedProducts } = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getSubscriptions();
|
|
102
|
+
this.update((state) => {
|
|
103
|
+
state.subscriptions = subscriptions;
|
|
104
|
+
state.customerId = customerId;
|
|
105
|
+
state.trialedProducts = trialedProducts;
|
|
106
|
+
});
|
|
107
|
+
return subscriptions;
|
|
108
|
+
}
|
|
109
|
+
async cancelSubscription(request) {
|
|
110
|
+
__classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_assertIsUserSubscribed).call(this, { subscriptionId: request.subscriptionId });
|
|
111
|
+
const cancelledSubscription = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").cancelSubscription({
|
|
112
|
+
subscriptionId: request.subscriptionId,
|
|
113
|
+
});
|
|
114
|
+
this.update((state) => {
|
|
115
|
+
state.subscriptions = state.subscriptions.map((subscription) => subscription.id === request.subscriptionId
|
|
116
|
+
? { ...subscription, ...cancelledSubscription }
|
|
117
|
+
: subscription);
|
|
118
|
+
});
|
|
119
|
+
this.triggerAccessTokenRefresh();
|
|
120
|
+
}
|
|
121
|
+
async unCancelSubscription(request) {
|
|
122
|
+
__classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_assertIsUserSubscribed).call(this, { subscriptionId: request.subscriptionId });
|
|
123
|
+
const uncancelledSubscription = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").unCancelSubscription({
|
|
124
|
+
subscriptionId: request.subscriptionId,
|
|
125
|
+
});
|
|
126
|
+
this.update((state) => {
|
|
127
|
+
state.subscriptions = state.subscriptions.map((subscription) => subscription.id === request.subscriptionId
|
|
128
|
+
? { ...subscription, ...uncancelledSubscription }
|
|
129
|
+
: subscription);
|
|
130
|
+
});
|
|
131
|
+
this.triggerAccessTokenRefresh();
|
|
132
|
+
}
|
|
133
|
+
async startShieldSubscriptionWithCard(request) {
|
|
134
|
+
__classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_assertIsUserNotSubscribed).call(this, { products: request.products });
|
|
135
|
+
const response = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").startSubscriptionWithCard(request);
|
|
136
|
+
this.triggerAccessTokenRefresh();
|
|
137
|
+
return response;
|
|
138
|
+
}
|
|
139
|
+
async startSubscriptionWithCrypto(request) {
|
|
140
|
+
__classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_assertIsUserNotSubscribed).call(this, { products: request.products });
|
|
141
|
+
const response = await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").startSubscriptionWithCrypto(request);
|
|
142
|
+
this.triggerAccessTokenRefresh();
|
|
143
|
+
return response;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Get transaction params to create crypto approve transaction for subscription payment
|
|
147
|
+
*
|
|
148
|
+
* @param request - The request object
|
|
149
|
+
* @param request.chainId - The chain ID
|
|
150
|
+
* @param request.tokenAddress - The address of the token
|
|
151
|
+
* @param request.productType - The product type
|
|
152
|
+
* @param request.interval - The interval
|
|
153
|
+
* @returns The crypto approve transaction params
|
|
154
|
+
*/
|
|
155
|
+
async getCryptoApproveTransactionParams(request) {
|
|
156
|
+
const pricing = await this.getPricing();
|
|
157
|
+
const product = pricing.products.find((p) => p.name === request.productType);
|
|
158
|
+
if (!product) {
|
|
159
|
+
throw new Error('Product price not found');
|
|
160
|
+
}
|
|
161
|
+
const price = product.prices.find((p) => p.interval === request.interval);
|
|
162
|
+
if (!price) {
|
|
163
|
+
throw new Error('Price not found');
|
|
164
|
+
}
|
|
165
|
+
const chainsPaymentInfo = pricing.paymentMethods.find((t) => t.type === types_1.PAYMENT_TYPES.byCrypto);
|
|
166
|
+
if (!chainsPaymentInfo) {
|
|
167
|
+
throw new Error('Chains payment info not found');
|
|
168
|
+
}
|
|
169
|
+
const chainPaymentInfo = chainsPaymentInfo.chains?.find((t) => t.chainId === request.chainId);
|
|
170
|
+
if (!chainPaymentInfo) {
|
|
171
|
+
throw new Error('Invalid chain id');
|
|
172
|
+
}
|
|
173
|
+
const tokenPaymentInfo = chainPaymentInfo.tokens.find((t) => t.address === request.paymentTokenAddress);
|
|
174
|
+
if (!tokenPaymentInfo) {
|
|
175
|
+
throw new Error('Invalid token address');
|
|
176
|
+
}
|
|
177
|
+
const tokenApproveAmount = this.getTokenApproveAmount(price, tokenPaymentInfo);
|
|
178
|
+
return {
|
|
179
|
+
approveAmount: tokenApproveAmount,
|
|
180
|
+
paymentAddress: chainPaymentInfo.paymentAddress,
|
|
181
|
+
paymentTokenAddress: request.paymentTokenAddress,
|
|
182
|
+
chainId: request.chainId,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
async updatePaymentMethod(opts) {
|
|
186
|
+
if (opts.paymentType === types_1.PAYMENT_TYPES.byCard) {
|
|
187
|
+
const { paymentType, ...cardRequest } = opts;
|
|
188
|
+
await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").updatePaymentMethodCard(cardRequest);
|
|
189
|
+
}
|
|
190
|
+
else if (opts.paymentType === types_1.PAYMENT_TYPES.byCrypto) {
|
|
191
|
+
const { paymentType, ...cryptoRequest } = opts;
|
|
192
|
+
await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").updatePaymentMethodCrypto(cryptoRequest);
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
throw new Error('Invalid payment type');
|
|
196
|
+
}
|
|
197
|
+
await this.getSubscriptions();
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Calculate token approve amount from price info
|
|
201
|
+
*
|
|
202
|
+
* @param price - The price info
|
|
203
|
+
* @param tokenPaymentInfo - The token price info
|
|
204
|
+
* @returns The token approve amount
|
|
205
|
+
*/
|
|
206
|
+
getTokenApproveAmount(price, tokenPaymentInfo) {
|
|
207
|
+
const conversionRate = tokenPaymentInfo.conversionRate[price.currency];
|
|
208
|
+
if (!conversionRate) {
|
|
209
|
+
throw new Error('Conversion rate not found');
|
|
210
|
+
}
|
|
211
|
+
// conversion rate is a float string e.g: "1.0"
|
|
212
|
+
// We need to handle float conversion rates with integer math for BigInt.
|
|
213
|
+
// We'll scale the conversion rate to an integer by multiplying by 10^4.
|
|
214
|
+
// conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)
|
|
215
|
+
// So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)
|
|
216
|
+
// This allows us to avoid floating point math and keep precision.
|
|
217
|
+
const SCALE = 10n ** 4n;
|
|
218
|
+
const conversionRateScaled = BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;
|
|
219
|
+
// price of the product
|
|
220
|
+
const priceAmount = __classPrivateFieldGet(this, _SubscriptionController_instances, "m", _SubscriptionController_getSubscriptionPriceAmount).call(this, price);
|
|
221
|
+
const priceAmountScaled = BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;
|
|
222
|
+
const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);
|
|
223
|
+
const tokenAmount = (priceAmountScaled * tokenDecimal) / conversionRateScaled;
|
|
224
|
+
return tokenAmount.toString();
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Triggers an access token refresh.
|
|
228
|
+
*/
|
|
229
|
+
triggerAccessTokenRefresh() {
|
|
230
|
+
// We perform a sign out to clear the access token from the authentication
|
|
231
|
+
// controller. Next time the access token is requested, a new access token
|
|
232
|
+
// will be fetched.
|
|
233
|
+
this.messagingSystem.call('AuthenticationController:performSignOut');
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Gets the billing portal URL.
|
|
237
|
+
*
|
|
238
|
+
* @returns The billing portal URL
|
|
239
|
+
*/
|
|
240
|
+
async getBillingPortalUrl() {
|
|
241
|
+
return await __classPrivateFieldGet(this, _SubscriptionController_subscriptionService, "f").getBillingPortalUrl();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
exports.SubscriptionController = SubscriptionController;
|
|
245
|
+
_SubscriptionController_subscriptionService = new WeakMap(), _SubscriptionController_instances = new WeakSet(), _SubscriptionController_registerMessageHandlers = function _SubscriptionController_registerMessageHandlers() {
|
|
246
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:getSubscriptions', this.getSubscriptions.bind(this));
|
|
247
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:cancelSubscription', this.cancelSubscription.bind(this));
|
|
248
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:startShieldSubscriptionWithCard', this.startShieldSubscriptionWithCard.bind(this));
|
|
249
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:getPricing', this.getPricing.bind(this));
|
|
250
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:getCryptoApproveTransactionParams', this.getCryptoApproveTransactionParams.bind(this));
|
|
251
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:startSubscriptionWithCrypto', this.startSubscriptionWithCrypto.bind(this));
|
|
252
|
+
this.messagingSystem.registerActionHandler('SubscriptionController:updatePaymentMethod', this.updatePaymentMethod.bind(this));
|
|
253
|
+
}, _SubscriptionController_getSubscriptionPriceAmount = function _SubscriptionController_getSubscriptionPriceAmount(price) {
|
|
254
|
+
// no need to use BigInt since max unitDecimals are always 2 for price
|
|
255
|
+
const amount = (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;
|
|
256
|
+
return amount;
|
|
257
|
+
}, _SubscriptionController_assertIsUserNotSubscribed = function _SubscriptionController_assertIsUserNotSubscribed({ products }) {
|
|
258
|
+
if (this.state.subscriptions.find((subscription) => subscription.products.some((p) => products.includes(p.name)))) {
|
|
259
|
+
throw new Error(constants_1.SubscriptionControllerErrorMessage.UserAlreadySubscribed);
|
|
260
|
+
}
|
|
261
|
+
}, _SubscriptionController_assertIsUserSubscribed = function _SubscriptionController_assertIsUserSubscribed(request) {
|
|
262
|
+
if (!this.state.subscriptions.find((subscription) => subscription.id === request.subscriptionId)) {
|
|
263
|
+
throw new Error(constants_1.SubscriptionControllerErrorMessage.UserNotSubscribed);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
//# sourceMappingURL=SubscriptionController.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SubscriptionController.cjs","sourceRoot":"","sources":["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AAC,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 BillingPortalResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodOpts,\n} from './types';\nimport {\n PAYMENT_TYPES,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n customerId?: string;\n trialedProducts: ProductType[];\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 trialedProducts: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n customerId: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n trialedProducts: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\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, customerId, trialedProducts } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n state.customerId = customerId;\n state.trialedProducts = trialedProducts;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const cancelledSubscription =\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, ...cancelledSubscription }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async unCancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const uncancelledSubscription =\n await this.#subscriptionService.unCancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...uncancelledSubscription }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(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 === PAYMENT_TYPES.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,\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(opts: UpdatePaymentMethodOpts) {\n if (opts.paymentType === PAYMENT_TYPES.byCard) {\n const { paymentType, ...cardRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCard(cardRequest);\n } else if (opts.paymentType === PAYMENT_TYPES.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 ): string {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // 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.toString();\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 /**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n return await this.#subscriptionService.getBillingPortalUrl();\n }\n}\n"]}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { BaseController, type ControllerStateChangeEvent, type ControllerGetStateAction, type RestrictedMessenger } from "@metamask/base-controller";
|
|
2
|
+
import type { AuthenticationController } from "@metamask/profile-sync-controller";
|
|
3
|
+
import { controllerName } from "./constants.cjs";
|
|
4
|
+
import type { BillingPortalResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, ProductPrice, StartCryptoSubscriptionRequest, TokenPaymentInfo, UpdatePaymentMethodOpts } from "./types.cjs";
|
|
5
|
+
import { type ISubscriptionService, type PricingResponse, type ProductType, type StartSubscriptionRequest, type Subscription } from "./types.cjs";
|
|
6
|
+
export type SubscriptionControllerState = {
|
|
7
|
+
customerId?: string;
|
|
8
|
+
trialedProducts: ProductType[];
|
|
9
|
+
subscriptions: Subscription[];
|
|
10
|
+
pricing?: PricingResponse;
|
|
11
|
+
};
|
|
12
|
+
export type SubscriptionControllerGetSubscriptionsAction = {
|
|
13
|
+
type: `${typeof controllerName}:getSubscriptions`;
|
|
14
|
+
handler: SubscriptionController['getSubscriptions'];
|
|
15
|
+
};
|
|
16
|
+
export type SubscriptionControllerCancelSubscriptionAction = {
|
|
17
|
+
type: `${typeof controllerName}:cancelSubscription`;
|
|
18
|
+
handler: SubscriptionController['cancelSubscription'];
|
|
19
|
+
};
|
|
20
|
+
export type SubscriptionControllerStartShieldSubscriptionWithCardAction = {
|
|
21
|
+
type: `${typeof controllerName}:startShieldSubscriptionWithCard`;
|
|
22
|
+
handler: SubscriptionController['startShieldSubscriptionWithCard'];
|
|
23
|
+
};
|
|
24
|
+
export type SubscriptionControllerGetPricingAction = {
|
|
25
|
+
type: `${typeof controllerName}:getPricing`;
|
|
26
|
+
handler: SubscriptionController['getPricing'];
|
|
27
|
+
};
|
|
28
|
+
export type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {
|
|
29
|
+
type: `${typeof controllerName}:getCryptoApproveTransactionParams`;
|
|
30
|
+
handler: SubscriptionController['getCryptoApproveTransactionParams'];
|
|
31
|
+
};
|
|
32
|
+
export type SubscriptionControllerStartSubscriptionWithCryptoAction = {
|
|
33
|
+
type: `${typeof controllerName}:startSubscriptionWithCrypto`;
|
|
34
|
+
handler: SubscriptionController['startSubscriptionWithCrypto'];
|
|
35
|
+
};
|
|
36
|
+
export type SubscriptionControllerUpdatePaymentMethodAction = {
|
|
37
|
+
type: `${typeof controllerName}:updatePaymentMethod`;
|
|
38
|
+
handler: SubscriptionController['updatePaymentMethod'];
|
|
39
|
+
};
|
|
40
|
+
export type SubscriptionControllerGetStateAction = ControllerGetStateAction<typeof controllerName, SubscriptionControllerState>;
|
|
41
|
+
export type SubscriptionControllerActions = SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerCancelSubscriptionAction | SubscriptionControllerStartShieldSubscriptionWithCardAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetCryptoApproveTransactionParamsAction | SubscriptionControllerStartSubscriptionWithCryptoAction | SubscriptionControllerUpdatePaymentMethodAction;
|
|
42
|
+
export type AllowedActions = AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerPerformSignOut;
|
|
43
|
+
export type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, SubscriptionControllerState>;
|
|
44
|
+
export type SubscriptionControllerEvents = SubscriptionControllerStateChangeEvent;
|
|
45
|
+
export type AllowedEvents = AuthenticationController.AuthenticationControllerStateChangeEvent;
|
|
46
|
+
export type SubscriptionControllerMessenger = RestrictedMessenger<typeof controllerName, SubscriptionControllerActions | AllowedActions, SubscriptionControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
47
|
+
/**
|
|
48
|
+
* Subscription Controller Options.
|
|
49
|
+
*/
|
|
50
|
+
export type SubscriptionControllerOptions = {
|
|
51
|
+
messenger: SubscriptionControllerMessenger;
|
|
52
|
+
/**
|
|
53
|
+
* Initial state to set on this controller.
|
|
54
|
+
*/
|
|
55
|
+
state?: Partial<SubscriptionControllerState>;
|
|
56
|
+
/**
|
|
57
|
+
* Subscription service to use for the subscription controller.
|
|
58
|
+
*/
|
|
59
|
+
subscriptionService: ISubscriptionService;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Get the default state for the Subscription Controller.
|
|
63
|
+
*
|
|
64
|
+
* @returns The default state for the Subscription Controller.
|
|
65
|
+
*/
|
|
66
|
+
export declare function getDefaultSubscriptionControllerState(): SubscriptionControllerState;
|
|
67
|
+
export declare class SubscriptionController extends BaseController<typeof controllerName, SubscriptionControllerState, SubscriptionControllerMessenger> {
|
|
68
|
+
#private;
|
|
69
|
+
/**
|
|
70
|
+
* Creates a new SubscriptionController instance.
|
|
71
|
+
*
|
|
72
|
+
* @param options - The options for the SubscriptionController.
|
|
73
|
+
* @param options.messenger - A restricted messenger.
|
|
74
|
+
* @param options.state - Initial state to set on this controller.
|
|
75
|
+
* @param options.subscriptionService - The subscription service for communicating with subscription server.
|
|
76
|
+
*/
|
|
77
|
+
constructor({ messenger, state, subscriptionService, }: SubscriptionControllerOptions);
|
|
78
|
+
/**
|
|
79
|
+
* Gets the pricing information from the subscription service.
|
|
80
|
+
*
|
|
81
|
+
* @returns The pricing information.
|
|
82
|
+
*/
|
|
83
|
+
getPricing(): Promise<PricingResponse>;
|
|
84
|
+
getSubscriptions(): Promise<Subscription[]>;
|
|
85
|
+
cancelSubscription(request: {
|
|
86
|
+
subscriptionId: string;
|
|
87
|
+
}): Promise<void>;
|
|
88
|
+
unCancelSubscription(request: {
|
|
89
|
+
subscriptionId: string;
|
|
90
|
+
}): Promise<void>;
|
|
91
|
+
startShieldSubscriptionWithCard(request: StartSubscriptionRequest): Promise<import("./types.cjs").StartSubscriptionResponse>;
|
|
92
|
+
startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<import("./types.cjs").StartCryptoSubscriptionResponse>;
|
|
93
|
+
/**
|
|
94
|
+
* Get transaction params to create crypto approve transaction for subscription payment
|
|
95
|
+
*
|
|
96
|
+
* @param request - The request object
|
|
97
|
+
* @param request.chainId - The chain ID
|
|
98
|
+
* @param request.tokenAddress - The address of the token
|
|
99
|
+
* @param request.productType - The product type
|
|
100
|
+
* @param request.interval - The interval
|
|
101
|
+
* @returns The crypto approve transaction params
|
|
102
|
+
*/
|
|
103
|
+
getCryptoApproveTransactionParams(request: GetCryptoApproveTransactionRequest): Promise<GetCryptoApproveTransactionResponse>;
|
|
104
|
+
updatePaymentMethod(opts: UpdatePaymentMethodOpts): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Calculate token approve amount from price info
|
|
107
|
+
*
|
|
108
|
+
* @param price - The price info
|
|
109
|
+
* @param tokenPaymentInfo - The token price info
|
|
110
|
+
* @returns The token approve amount
|
|
111
|
+
*/
|
|
112
|
+
getTokenApproveAmount(price: ProductPrice, tokenPaymentInfo: TokenPaymentInfo): string;
|
|
113
|
+
/**
|
|
114
|
+
* Triggers an access token refresh.
|
|
115
|
+
*/
|
|
116
|
+
triggerAccessTokenRefresh(): void;
|
|
117
|
+
/**
|
|
118
|
+
* Gets the billing portal URL.
|
|
119
|
+
*
|
|
120
|
+
* @returns The billing portal URL
|
|
121
|
+
*/
|
|
122
|
+
getBillingPortalUrl(): Promise<BillingPortalResponse>;
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=SubscriptionController.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SubscriptionController.d.cts","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,qBAAqB,EACrB,kCAAkC,EAClC,mCAAmC,EACnC,YAAY,EACZ,8BAA8B,EAC9B,gBAAgB,EAChB,uBAAuB,EACxB,oBAAgB;AACjB,OAAO,EAEL,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,WAAW,EAChB,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EAClB,oBAAgB;AAEjB,MAAM,MAAM,2BAA2B,GAAG;IACxC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,WAAW,EAAE,CAAC;IAC/B,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,OAAO,CAAC,EAAE,eAAe,CAAC;CAC3B,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,OAAO,cAAc,kCAAkC,CAAC;IACjE,OAAO,EAAE,sBAAsB,CAAC,iCAAiC,CAAC,CAAC;CACpE,CAAC;AACF,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EA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AAM,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,CAKnF;AAqCD,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;IAahB,kBAAkB,CAAC,OAAO,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE;IAmBtD,oBAAoB,CAAC,OAAO,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE;IAmBxD,+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;IA2BvD;;;;;;OAMG;IACH,qBAAqB,CACnB,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,gBAAgB,GACjC,MAAM;IAuCT;;OAEG;IACH,yBAAyB;IAiBzB;;;;OAIG;IACG,mBAAmB,IAAI,OAAO,CAAC,qBAAqB,CAAC;CAG5D"}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { BaseController, type ControllerStateChangeEvent, type ControllerGetStateAction, type RestrictedMessenger } from "@metamask/base-controller";
|
|
2
|
+
import type { AuthenticationController } from "@metamask/profile-sync-controller";
|
|
3
|
+
import { controllerName } from "./constants.mjs";
|
|
4
|
+
import type { BillingPortalResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, ProductPrice, StartCryptoSubscriptionRequest, TokenPaymentInfo, UpdatePaymentMethodOpts } from "./types.mjs";
|
|
5
|
+
import { type ISubscriptionService, type PricingResponse, type ProductType, type StartSubscriptionRequest, type Subscription } from "./types.mjs";
|
|
6
|
+
export type SubscriptionControllerState = {
|
|
7
|
+
customerId?: string;
|
|
8
|
+
trialedProducts: ProductType[];
|
|
9
|
+
subscriptions: Subscription[];
|
|
10
|
+
pricing?: PricingResponse;
|
|
11
|
+
};
|
|
12
|
+
export type SubscriptionControllerGetSubscriptionsAction = {
|
|
13
|
+
type: `${typeof controllerName}:getSubscriptions`;
|
|
14
|
+
handler: SubscriptionController['getSubscriptions'];
|
|
15
|
+
};
|
|
16
|
+
export type SubscriptionControllerCancelSubscriptionAction = {
|
|
17
|
+
type: `${typeof controllerName}:cancelSubscription`;
|
|
18
|
+
handler: SubscriptionController['cancelSubscription'];
|
|
19
|
+
};
|
|
20
|
+
export type SubscriptionControllerStartShieldSubscriptionWithCardAction = {
|
|
21
|
+
type: `${typeof controllerName}:startShieldSubscriptionWithCard`;
|
|
22
|
+
handler: SubscriptionController['startShieldSubscriptionWithCard'];
|
|
23
|
+
};
|
|
24
|
+
export type SubscriptionControllerGetPricingAction = {
|
|
25
|
+
type: `${typeof controllerName}:getPricing`;
|
|
26
|
+
handler: SubscriptionController['getPricing'];
|
|
27
|
+
};
|
|
28
|
+
export type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {
|
|
29
|
+
type: `${typeof controllerName}:getCryptoApproveTransactionParams`;
|
|
30
|
+
handler: SubscriptionController['getCryptoApproveTransactionParams'];
|
|
31
|
+
};
|
|
32
|
+
export type SubscriptionControllerStartSubscriptionWithCryptoAction = {
|
|
33
|
+
type: `${typeof controllerName}:startSubscriptionWithCrypto`;
|
|
34
|
+
handler: SubscriptionController['startSubscriptionWithCrypto'];
|
|
35
|
+
};
|
|
36
|
+
export type SubscriptionControllerUpdatePaymentMethodAction = {
|
|
37
|
+
type: `${typeof controllerName}:updatePaymentMethod`;
|
|
38
|
+
handler: SubscriptionController['updatePaymentMethod'];
|
|
39
|
+
};
|
|
40
|
+
export type SubscriptionControllerGetStateAction = ControllerGetStateAction<typeof controllerName, SubscriptionControllerState>;
|
|
41
|
+
export type SubscriptionControllerActions = SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerCancelSubscriptionAction | SubscriptionControllerStartShieldSubscriptionWithCardAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetCryptoApproveTransactionParamsAction | SubscriptionControllerStartSubscriptionWithCryptoAction | SubscriptionControllerUpdatePaymentMethodAction;
|
|
42
|
+
export type AllowedActions = AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerPerformSignOut;
|
|
43
|
+
export type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, SubscriptionControllerState>;
|
|
44
|
+
export type SubscriptionControllerEvents = SubscriptionControllerStateChangeEvent;
|
|
45
|
+
export type AllowedEvents = AuthenticationController.AuthenticationControllerStateChangeEvent;
|
|
46
|
+
export type SubscriptionControllerMessenger = RestrictedMessenger<typeof controllerName, SubscriptionControllerActions | AllowedActions, SubscriptionControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
47
|
+
/**
|
|
48
|
+
* Subscription Controller Options.
|
|
49
|
+
*/
|
|
50
|
+
export type SubscriptionControllerOptions = {
|
|
51
|
+
messenger: SubscriptionControllerMessenger;
|
|
52
|
+
/**
|
|
53
|
+
* Initial state to set on this controller.
|
|
54
|
+
*/
|
|
55
|
+
state?: Partial<SubscriptionControllerState>;
|
|
56
|
+
/**
|
|
57
|
+
* Subscription service to use for the subscription controller.
|
|
58
|
+
*/
|
|
59
|
+
subscriptionService: ISubscriptionService;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Get the default state for the Subscription Controller.
|
|
63
|
+
*
|
|
64
|
+
* @returns The default state for the Subscription Controller.
|
|
65
|
+
*/
|
|
66
|
+
export declare function getDefaultSubscriptionControllerState(): SubscriptionControllerState;
|
|
67
|
+
export declare class SubscriptionController extends BaseController<typeof controllerName, SubscriptionControllerState, SubscriptionControllerMessenger> {
|
|
68
|
+
#private;
|
|
69
|
+
/**
|
|
70
|
+
* Creates a new SubscriptionController instance.
|
|
71
|
+
*
|
|
72
|
+
* @param options - The options for the SubscriptionController.
|
|
73
|
+
* @param options.messenger - A restricted messenger.
|
|
74
|
+
* @param options.state - Initial state to set on this controller.
|
|
75
|
+
* @param options.subscriptionService - The subscription service for communicating with subscription server.
|
|
76
|
+
*/
|
|
77
|
+
constructor({ messenger, state, subscriptionService, }: SubscriptionControllerOptions);
|
|
78
|
+
/**
|
|
79
|
+
* Gets the pricing information from the subscription service.
|
|
80
|
+
*
|
|
81
|
+
* @returns The pricing information.
|
|
82
|
+
*/
|
|
83
|
+
getPricing(): Promise<PricingResponse>;
|
|
84
|
+
getSubscriptions(): Promise<Subscription[]>;
|
|
85
|
+
cancelSubscription(request: {
|
|
86
|
+
subscriptionId: string;
|
|
87
|
+
}): Promise<void>;
|
|
88
|
+
unCancelSubscription(request: {
|
|
89
|
+
subscriptionId: string;
|
|
90
|
+
}): Promise<void>;
|
|
91
|
+
startShieldSubscriptionWithCard(request: StartSubscriptionRequest): Promise<import("./types.mjs").StartSubscriptionResponse>;
|
|
92
|
+
startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<import("./types.mjs").StartCryptoSubscriptionResponse>;
|
|
93
|
+
/**
|
|
94
|
+
* Get transaction params to create crypto approve transaction for subscription payment
|
|
95
|
+
*
|
|
96
|
+
* @param request - The request object
|
|
97
|
+
* @param request.chainId - The chain ID
|
|
98
|
+
* @param request.tokenAddress - The address of the token
|
|
99
|
+
* @param request.productType - The product type
|
|
100
|
+
* @param request.interval - The interval
|
|
101
|
+
* @returns The crypto approve transaction params
|
|
102
|
+
*/
|
|
103
|
+
getCryptoApproveTransactionParams(request: GetCryptoApproveTransactionRequest): Promise<GetCryptoApproveTransactionResponse>;
|
|
104
|
+
updatePaymentMethod(opts: UpdatePaymentMethodOpts): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Calculate token approve amount from price info
|
|
107
|
+
*
|
|
108
|
+
* @param price - The price info
|
|
109
|
+
* @param tokenPaymentInfo - The token price info
|
|
110
|
+
* @returns The token approve amount
|
|
111
|
+
*/
|
|
112
|
+
getTokenApproveAmount(price: ProductPrice, tokenPaymentInfo: TokenPaymentInfo): string;
|
|
113
|
+
/**
|
|
114
|
+
* Triggers an access token refresh.
|
|
115
|
+
*/
|
|
116
|
+
triggerAccessTokenRefresh(): void;
|
|
117
|
+
/**
|
|
118
|
+
* Gets the billing portal URL.
|
|
119
|
+
*
|
|
120
|
+
* @returns The billing portal URL
|
|
121
|
+
*/
|
|
122
|
+
getBillingPortalUrl(): Promise<BillingPortalResponse>;
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=SubscriptionController.d.mts.map
|