@metamask-previews/subscription-controller 9.0.1-preview-2b92c5a1c → 9.0.1-preview-e8a256c39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/constants.d.ts +16 -0
  3. package/dist/constants.d.ts.map +1 -1
  4. package/dist/constants.js +17 -0
  5. package/dist/constants.js.map +1 -1
  6. package/dist/index.d.ts +7 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +3 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts +44 -0
  11. package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts.map +1 -0
  12. package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js +6 -0
  13. package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js.map +1 -0
  14. package/dist/subscription-delegation/SubscriptionDelegationService.d.ts +93 -0
  15. package/dist/subscription-delegation/SubscriptionDelegationService.d.ts.map +1 -0
  16. package/dist/subscription-delegation/SubscriptionDelegationService.js +290 -0
  17. package/dist/subscription-delegation/SubscriptionDelegationService.js.map +1 -0
  18. package/dist/subscription-delegation/amount.d.ts +49 -0
  19. package/dist/subscription-delegation/amount.d.ts.map +1 -0
  20. package/dist/subscription-delegation/amount.js +84 -0
  21. package/dist/subscription-delegation/amount.js.map +1 -0
  22. package/dist/subscription-delegation/caveats.d.ts +41 -0
  23. package/dist/subscription-delegation/caveats.d.ts.map +1 -0
  24. package/dist/subscription-delegation/caveats.js +59 -0
  25. package/dist/subscription-delegation/caveats.js.map +1 -0
  26. package/dist/subscription-delegation/fingerprint.d.ts +42 -0
  27. package/dist/subscription-delegation/fingerprint.d.ts.map +1 -0
  28. package/dist/subscription-delegation/fingerprint.js +80 -0
  29. package/dist/subscription-delegation/fingerprint.js.map +1 -0
  30. package/dist/subscription-delegation/types.d.ts +73 -0
  31. package/dist/subscription-delegation/types.d.ts.map +1 -0
  32. package/dist/subscription-delegation/types.js +10 -0
  33. package/dist/subscription-delegation/types.js.map +1 -0
  34. package/package.json +11 -2
@@ -0,0 +1,290 @@
1
+ import { hashDelegation } from '@metamask/delegation-core';
2
+ import { DELEGATOR_CONTRACTS } from '@metamask/delegation-deployments';
3
+ import { getMoneyAccountVaultConfig, MUSD_DECIMALS, } from '@metamask/money-account-utils';
4
+ import { add0x, hexToNumber } from '@metamask/utils';
5
+ import { SubscriptionDelegationServiceErrorMessage } from '../constants.js';
6
+ import { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';
7
+ import { assertPositiveInteger, calculatePeriodAmount, getDelegationStartDate, getPeriodDuration, } from './amount.js';
8
+ import { buildUnsignedSubscriptionDelegation } from './caveats.js';
9
+ import { equalsIgnoreCase, makeMatchesSubscriptionDelegation, } from './fingerprint.js';
10
+ import { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';
11
+ /**
12
+ * The name of the {@link SubscriptionDelegationService}, used to namespace the
13
+ * service's actions and events.
14
+ */
15
+ export const serviceName = 'SubscriptionDelegationService';
16
+ const MESSENGER_EXPOSED_METHODS = [
17
+ 'prepareDelegation',
18
+ 'checkMoneyAccountBalance',
19
+ ];
20
+ const DELEGATION_FRAMEWORK_VERSION = '1.3.0';
21
+ function resolveEnforcers(chainId) {
22
+ const contracts = DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION]?.[hexToNumber(chainId)];
23
+ if (!contracts?.ValueLteEnforcer ||
24
+ !contracts.ERC20PeriodTransferEnforcer ||
25
+ !contracts.RedeemerEnforcer) {
26
+ throw new Error(`${SubscriptionDelegationServiceErrorMessage.DelegationContractsNotFound}: ${chainId}`);
27
+ }
28
+ return {
29
+ valueLte: contracts.ValueLteEnforcer,
30
+ erc20TokenPeriodTransfer: contracts.ERC20PeriodTransferEnforcer,
31
+ redeemer: contracts.RedeemerEnforcer,
32
+ };
33
+ }
34
+ /**
35
+ * Stateless orchestrator for cash-subscription delegation setup.
36
+ *
37
+ * Owns the workflow: size periodic caveats → sign → CHOMP verify → persist to
38
+ * Authenticated User Storage → register CHOMP intent. Returns a verified
39
+ * `delegationHash` for `SubscriptionController.startSubscriptionWithCrypto`.
40
+ *
41
+ * Alpha callers must pass `skipChompInteractions: true` until a follow-up
42
+ * `@metamask/chomp-api-service` release accepts `'cash-subscription'` intent
43
+ * metadata. The CHOMP-enabled path (`skipChompInteractions` unset/false)
44
+ * remains dormant and is not production-ready without that package support.
45
+ *
46
+ * Each call resolves the Money Account chain from remote feature flags, then
47
+ * resolves its price, payment token, and delegate from `SubscriptionController`
48
+ * pricing. The pricing `delegateAddress` is used as both the delegation
49
+ * `delegate` and the RedeemerEnforcer redeemer.
50
+ *
51
+ * Does not own subscription state; `SubscriptionController` does not depend on
52
+ * this service. Only Money Account Plus is supported.
53
+ */
54
+ export class SubscriptionDelegationService {
55
+ name = serviceName;
56
+ #messenger;
57
+ constructor(options) {
58
+ this.#messenger = options.messenger;
59
+ this.#messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
60
+ }
61
+ /**
62
+ * Checks whether the Money Account holds enough convertible mUSD value to
63
+ * cover pricing `unitAmount × minBillingCyclesForBalance`.
64
+ *
65
+ * @param request - Payer address and pricing amount fields.
66
+ * @returns Balance comparison in mUSD base units (6 decimals).
67
+ */
68
+ async checkMoneyAccountBalance(request) {
69
+ const { price } = await this.#resolveConfiguration(request.product, request.recurringInterval);
70
+ return this.#compareMoneyAccountBalance(request.payerAddress, price);
71
+ }
72
+ async #compareMoneyAccountBalance(payerAddress, price) {
73
+ assertPositiveInteger(price.minBillingCyclesForBalance, SubscriptionDelegationServiceErrorMessage.InvalidMinimumFundingCycles);
74
+ const periodAmount = calculatePeriodAmount({
75
+ unitAmount: price.unitAmount,
76
+ unitDecimals: price.unitDecimals,
77
+ tokenDecimals: MUSD_DECIMALS,
78
+ });
79
+ const requiredBalance = periodAmount * BigInt(price.minBillingCyclesForBalance);
80
+ const { totalBalance } = await this.#messenger.call('MoneyAccountBalanceService:fetchBalanceWithFallback', payerAddress);
81
+ return {
82
+ hasSufficientBalance: BigInt(totalBalance) >= requiredBalance,
83
+ balance: totalBalance,
84
+ requiredBalance: requiredBalance.toString(),
85
+ };
86
+ }
87
+ /**
88
+ * Prepares a cash-subscription delegation and returns its hash.
89
+ *
90
+ * Reuses a stored AUS delegation that matches the semantic fingerprint when
91
+ * one exists (ensuring a CHOMP intent is active for its hash, unless
92
+ * `skipChompInteractions` is true). Reuse classifies period `startDate` as
93
+ * trial-deferred (`> now`) vs immediately redeemable, matching creation.
94
+ * If there is no match, builds, signs, optionally verifies with CHOMP,
95
+ * persists, and optionally registers a new delegation.
96
+ *
97
+ * When `skipChompInteractions` is true (required for alpha), CHOMP verify
98
+ * and intent calls are skipped; the returned hash is computed locally. The
99
+ * default CHOMP-enabled path requires a follow-up chomp-api-service release
100
+ * that accepts `'cash-subscription'` intent metadata.
101
+ *
102
+ * @param request - Authoritative pricing and payer details for the delegation.
103
+ * @returns The delegation hash (CHOMP-verified unless skipped) and whether it
104
+ * was created or reused.
105
+ */
106
+ async prepareDelegation(request) {
107
+ if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {
108
+ throw new Error(SubscriptionDelegationServiceErrorMessage.UnsupportedProduct);
109
+ }
110
+ const skipChomp = Boolean(request.skipChompInteractions);
111
+ const { chainId, delegateAddress, enforcers, price, token } = await this.#resolveConfiguration(request.product, request.recurringInterval);
112
+ if (request.checkBalance) {
113
+ const { hasSufficientBalance } = await this.#compareMoneyAccountBalance(request.payerAddress, price);
114
+ if (!hasSufficientBalance) {
115
+ throw new Error(SubscriptionDelegationServiceErrorMessage.InsufficientBalance);
116
+ }
117
+ }
118
+ const periodAmount = calculatePeriodAmount({
119
+ unitAmount: price.unitAmount,
120
+ unitDecimals: price.unitDecimals,
121
+ tokenDecimals: token.decimals,
122
+ });
123
+ const periodDuration = getPeriodDuration(request.recurringInterval);
124
+ const nowSeconds = Math.floor(Date.now() / 1000);
125
+ const startDate = getDelegationStartDate({
126
+ nowSeconds,
127
+ trialPeriodDays: request.isTrialRequested
128
+ ? price.trialPeriodDays
129
+ : undefined,
130
+ });
131
+ const isTrialDeferred = startDate > nowSeconds;
132
+ const matches = makeMatchesSubscriptionDelegation({
133
+ delegatorAddress: request.payerAddress,
134
+ delegateAddress,
135
+ chainId,
136
+ tokenAddress: token.address,
137
+ periodAmount,
138
+ periodDuration,
139
+ nowSeconds,
140
+ isTrialDeferred,
141
+ enforcers,
142
+ });
143
+ const existingDelegations = await this.#messenger.call('AuthenticatedUserStorageService:listDelegations');
144
+ const reusable = existingDelegations.find(matches);
145
+ if (reusable) {
146
+ if (!skipChomp) {
147
+ await this.#ensureIntent({
148
+ account: request.payerAddress,
149
+ chainId,
150
+ delegationHash: reusable.metadata.delegationHash,
151
+ allowance: reusable.metadata.allowance,
152
+ tokenSymbol: reusable.metadata.tokenSymbol,
153
+ tokenAddress: reusable.metadata.tokenAddress,
154
+ });
155
+ }
156
+ return {
157
+ delegationHash: reusable.metadata.delegationHash,
158
+ disposition: 'reused',
159
+ };
160
+ }
161
+ const unsigned = buildUnsignedSubscriptionDelegation({
162
+ delegateAddress,
163
+ delegatorAddress: request.payerAddress,
164
+ enforcers,
165
+ tokenAddress: token.address,
166
+ periodAmount,
167
+ periodDuration,
168
+ startDate,
169
+ });
170
+ const signature = (await this.#messenger.call('DelegationController:signDelegation', { delegation: unsigned, chainId }));
171
+ const signedDelegation = { ...unsigned, signature };
172
+ const delegationHash = hashDelegation({
173
+ ...unsigned,
174
+ salt: BigInt(unsigned.salt),
175
+ signature,
176
+ });
177
+ if (!skipChomp) {
178
+ const verifyResult = await this.#messenger.call('ChompApiService:verifyDelegation', {
179
+ signedDelegation,
180
+ chainId,
181
+ });
182
+ if (!verifyResult.valid) {
183
+ throw new Error(`${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${verifyResult.errors?.join(', ') ?? 'unknown error'}`);
184
+ }
185
+ if (!verifyResult.delegationHash) {
186
+ throw new Error(SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash);
187
+ }
188
+ if (!equalsIgnoreCase(verifyResult.delegationHash, delegationHash)) {
189
+ throw new Error(SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch);
190
+ }
191
+ }
192
+ const allowance = add0x(periodAmount.toString(16));
193
+ await this.#messenger.call('AuthenticatedUserStorageService:createDelegation', {
194
+ signedDelegation,
195
+ metadata: {
196
+ delegationHash,
197
+ chainIdHex: chainId,
198
+ allowance,
199
+ tokenSymbol: token.symbol,
200
+ tokenAddress: token.address,
201
+ type: CASH_SUBSCRIPTION_DELEGATION_TYPE,
202
+ },
203
+ });
204
+ if (!skipChomp) {
205
+ await this.#createIntent({
206
+ account: request.payerAddress,
207
+ chainId,
208
+ delegationHash,
209
+ allowance,
210
+ tokenSymbol: token.symbol,
211
+ tokenAddress: token.address,
212
+ });
213
+ }
214
+ return {
215
+ delegationHash,
216
+ disposition: 'created',
217
+ };
218
+ }
219
+ async #resolveConfiguration(product, recurringInterval) {
220
+ const { remoteFeatureFlags } = this.#messenger.call('RemoteFeatureFlagController:getState');
221
+ const vaultConfig = getMoneyAccountVaultConfig(remoteFeatureFlags);
222
+ if (!vaultConfig) {
223
+ throw new Error(SubscriptionDelegationServiceErrorMessage.MissingMoneyAccountVaultConfig);
224
+ }
225
+ const { chainId } = vaultConfig;
226
+ const enforcers = resolveEnforcers(chainId);
227
+ const pricing = await this.#messenger.call('SubscriptionController:getPricing');
228
+ const price = pricing.products
229
+ .find((entry) => entry.name === product)
230
+ ?.prices.find((entry) => entry.interval === recurringInterval);
231
+ const paymentMethod = pricing.paymentMethods.find((entry) => entry.type === PAYMENT_TYPES.byCrypto &&
232
+ entry.cryptoAuthMethod === CRYPTO_AUTH_METHODS.DELEGATION &&
233
+ entry.products?.includes(product) === true);
234
+ const chain = paymentMethod?.chains?.find((entry) => entry.chainId === chainId);
235
+ const token = chain?.tokens[0];
236
+ if (!price || !chain?.delegateAddress || !token) {
237
+ throw new Error(SubscriptionDelegationServiceErrorMessage.PricingConfigurationNotFound);
238
+ }
239
+ return {
240
+ chainId,
241
+ delegateAddress: chain.delegateAddress,
242
+ enforcers,
243
+ price,
244
+ token,
245
+ };
246
+ }
247
+ /**
248
+ * Ensures an active CHOMP intent exists for the given delegation hash,
249
+ * registering one when missing or revoked.
250
+ *
251
+ * @param params - Intent identity and metadata.
252
+ * @param params.account - Delegator / payer address.
253
+ * @param params.chainId - Chain ID of the delegation.
254
+ * @param params.delegationHash - Hash of the stored delegation.
255
+ * @param params.allowance - Period allowance stored with the delegation.
256
+ * @param params.tokenSymbol - Payment token symbol.
257
+ * @param params.tokenAddress - Payment token address.
258
+ */
259
+ async #ensureIntent(params) {
260
+ const existingIntents = await this.#messenger.call('ChompApiService:getIntentsByAddress', params.account);
261
+ const hasActiveIntent = existingIntents.some((intent) => equalsIgnoreCase(intent.delegationHash, params.delegationHash) &&
262
+ intent.status === 'active');
263
+ if (hasActiveIntent) {
264
+ return;
265
+ }
266
+ await this.#createIntent(params);
267
+ }
268
+ async #createIntent(params) {
269
+ // Published `@metamask/chomp-api-service` only types intent metadata as
270
+ // `'cash-deposit' | 'cash-withdrawal'`. The dormant production path still
271
+ // passes `'cash-subscription'`; a follow-up chomp-api-service release must
272
+ // accept that discriminator before this path is production-ready. Alpha
273
+ // callers must use `skipChompInteractions: true` so this method is not
274
+ // reached.
275
+ await this.#messenger.call('ChompApiService:createIntents', [
276
+ {
277
+ account: params.account,
278
+ delegationHash: params.delegationHash,
279
+ chainId: params.chainId,
280
+ metadata: {
281
+ allowance: params.allowance,
282
+ tokenSymbol: params.tokenSymbol,
283
+ tokenAddress: params.tokenAddress,
284
+ type: CASH_SUBSCRIPTION_DELEGATION_TYPE,
285
+ },
286
+ },
287
+ ]);
288
+ }
289
+ }
290
+ //# sourceMappingURL=SubscriptionDelegationService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubscriptionDelegationService.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAGvE,OAAO,EACL,0BAA0B,EAC1B,aAAa,GACd,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGrD,OAAO,EAAE,yCAAyC,EAAE,MAAM,iBAAiB,CAAC;AAE5E,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAQhF,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mCAAmC,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EACL,gBAAgB,EAChB,iCAAiC,GAClC,MAAM,kBAAkB,CAAC;AAS1B,OAAO,EAAE,iCAAiC,EAAE,MAAM,YAAY,CAAC;AAE/D;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,+BAA+B,CAAC;AAE3D,MAAM,yBAAyB,GAAG;IAChC,mBAAmB;IACnB,0BAA0B;CAClB,CAAC;AAEX,MAAM,4BAA4B,GAAG,OAAO,CAAC;AAE7C,SAAS,gBAAgB,CAAC,OAAY;IACpC,MAAM,SAAS,GACb,mBAAmB,CAAC,4BAA4B,CAAC,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;IAE5E,IACE,CAAC,SAAS,EAAE,gBAAgB;QAC5B,CAAC,SAAS,CAAC,2BAA2B;QACtC,CAAC,SAAS,CAAC,gBAAgB,EAC3B,CAAC;QACD,MAAM,IAAI,KAAK,CACb,GAAG,yCAAyC,CAAC,2BAA2B,KAAK,OAAO,EAAE,CACvF,C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C,aAAa,CAAC,MAAgC;QAClD,wEAAwE;QACxE,0EAA0E;QAC1E,2EAA2E;QAC3E,wEAAwE;QACxE,uEAAuE;QACvE,WAAW;QACX,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,+BAA+B,EAAE;YAC1D;gBACE,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,cAAc,EAAE,MAAM,CAAC,cAAc;gBACrC,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,QAAQ,EAAE;oBACR,SAAS,EAAE,MAAM,CAAC,SAAS;oBAC3B,WAAW,EAAE,MAAM,CAAC,WAAW;oBAC/B,YAAY,EAAE,MAAM,CAAC,YAAY;oBACjC,IAAI,EAAE,iCAEe;iBACtB;aACF;SACF,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AuthenticatedUserStorageServiceCreateDelegationAction,\n AuthenticatedUserStorageServiceListDelegationsAction,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ChompApiServiceCreateIntentsAction,\n ChompApiServiceGetIntentsByAddressAction,\n ChompApiServiceVerifyDelegationAction,\n} from '@metamask/chomp-api-service';\nimport type { DelegationControllerSignDelegationAction } from '@metamask/delegation-controller';\nimport { hashDelegation } from '@metamask/delegation-core';\nimport { DELEGATOR_CONTRACTS } from '@metamask/delegation-deployments';\nimport type { Messenger } from '@metamask/messenger';\nimport type { MoneyAccountBalanceServiceFetchBalanceWithFallbackAction } from '@metamask/money-account-balance-service';\nimport {\n getMoneyAccountVaultConfig,\n MUSD_DECIMALS,\n} from '@metamask/money-account-utils';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport { add0x, hexToNumber } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { SubscriptionDelegationServiceErrorMessage } from '../constants.js';\nimport type { SubscriptionControllerGetPricingAction } from '../SubscriptionController-method-action-types.js';\nimport { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';\nimport type {\n ProductPrice,\n ProductType,\n PricingCryptoPaymentMethod,\n RecurringInterval,\n TokenPaymentInfo,\n} from '../types.js';\nimport {\n assertPositiveInteger,\n calculatePeriodAmount,\n getDelegationStartDate,\n getPeriodDuration,\n} from './amount.js';\nimport { buildUnsignedSubscriptionDelegation } from './caveats.js';\nimport {\n equalsIgnoreCase,\n makeMatchesSubscriptionDelegation,\n} from './fingerprint.js';\nimport type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';\nimport type {\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PreparedSubscriptionDelegation,\n SubscriptionDelegationEnforcers,\n} from './types.js';\nimport { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';\n\n/**\n * The name of the {@link SubscriptionDelegationService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'SubscriptionDelegationService';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'prepareDelegation',\n 'checkMoneyAccountBalance',\n] as const;\n\nconst DELEGATION_FRAMEWORK_VERSION = '1.3.0';\n\nfunction resolveEnforcers(chainId: Hex): SubscriptionDelegationEnforcers {\n const contracts =\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION]?.[hexToNumber(chainId)];\n\n if (\n !contracts?.ValueLteEnforcer ||\n !contracts.ERC20PeriodTransferEnforcer ||\n !contracts.RedeemerEnforcer\n ) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.DelegationContractsNotFound}: ${chainId}`,\n );\n }\n\n return {\n valueLte: contracts.ValueLteEnforcer,\n erc20TokenPeriodTransfer: contracts.ERC20PeriodTransferEnforcer,\n redeemer: contracts.RedeemerEnforcer,\n };\n}\n\n/**\n * Actions that {@link SubscriptionDelegationService} exposes to other consumers.\n */\nexport type SubscriptionDelegationServiceActions =\n SubscriptionDelegationServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link SubscriptionDelegationServiceMessenger} calls.\n */\ntype AllowedActions =\n | AuthenticatedUserStorageServiceListDelegationsAction\n | AuthenticatedUserStorageServiceCreateDelegationAction\n | ChompApiServiceVerifyDelegationAction\n | ChompApiServiceCreateIntentsAction\n | ChompApiServiceGetIntentsByAddressAction\n | DelegationControllerSignDelegationAction\n | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction\n | RemoteFeatureFlagControllerGetStateAction\n | SubscriptionControllerGetPricingAction;\n\n/**\n * Events that {@link SubscriptionDelegationService} exposes to other consumers.\n */\nexport type SubscriptionDelegationServiceEvents = never;\n\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link SubscriptionDelegationService}.\n */\nexport type SubscriptionDelegationServiceMessenger = Messenger<\n typeof serviceName,\n SubscriptionDelegationServiceActions | AllowedActions,\n SubscriptionDelegationServiceEvents | AllowedEvents\n>;\n\n/**\n * Options for constructing {@link SubscriptionDelegationService}.\n */\nexport type SubscriptionDelegationServiceOptions = {\n messenger: SubscriptionDelegationServiceMessenger;\n};\n\ntype SubscriptionIntentParams = {\n account: Hex;\n chainId: Hex;\n delegationHash: Hex;\n allowance: Hex;\n tokenSymbol: string;\n tokenAddress: Hex;\n};\n\ntype ResolvedSubscriptionDelegationConfig = {\n chainId: Hex;\n delegateAddress: Hex;\n enforcers: SubscriptionDelegationEnforcers;\n price: ProductPrice;\n token: TokenPaymentInfo;\n};\n\n/**\n * Stateless orchestrator for cash-subscription delegation setup.\n *\n * Owns the workflow: size periodic caveats → sign → CHOMP verify → persist to\n * Authenticated User Storage → register CHOMP intent. Returns a verified\n * `delegationHash` for `SubscriptionController.startSubscriptionWithCrypto`.\n *\n * Alpha callers must pass `skipChompInteractions: true` until a follow-up\n * `@metamask/chomp-api-service` release accepts `'cash-subscription'` intent\n * metadata. The CHOMP-enabled path (`skipChompInteractions` unset/false)\n * remains dormant and is not production-ready without that package support.\n *\n * Each call resolves the Money Account chain from remote feature flags, then\n * resolves its price, payment token, and delegate from `SubscriptionController`\n * pricing. The pricing `delegateAddress` is used as both the delegation\n * `delegate` and the RedeemerEnforcer redeemer.\n *\n * Does not own subscription state; `SubscriptionController` does not depend on\n * this service. Only Money Account Plus is supported.\n */\nexport class SubscriptionDelegationService {\n readonly name: typeof serviceName = serviceName;\n\n readonly #messenger: SubscriptionDelegationServiceMessenger;\n\n constructor(options: SubscriptionDelegationServiceOptions) {\n this.#messenger = options.messenger;\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Checks whether the Money Account holds enough convertible mUSD value to\n * cover pricing `unitAmount × minBillingCyclesForBalance`.\n *\n * @param request - Payer address and pricing amount fields.\n * @returns Balance comparison in mUSD base units (6 decimals).\n */\n async checkMoneyAccountBalance(\n request: MoneyAccountBalanceCheckRequest,\n ): Promise<MoneyAccountBalanceCheckResult> {\n const { price } = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n return this.#compareMoneyAccountBalance(request.payerAddress, price);\n }\n\n async #compareMoneyAccountBalance(\n payerAddress: Hex,\n price: ProductPrice,\n ): Promise<MoneyAccountBalanceCheckResult> {\n assertPositiveInteger(\n price.minBillingCyclesForBalance,\n SubscriptionDelegationServiceErrorMessage.InvalidMinimumFundingCycles,\n );\n\n const periodAmount = calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: MUSD_DECIMALS,\n });\n const requiredBalance =\n periodAmount * BigInt(price.minBillingCyclesForBalance);\n\n const { totalBalance } = await this.#messenger.call(\n 'MoneyAccountBalanceService:fetchBalanceWithFallback',\n payerAddress,\n );\n\n return {\n hasSufficientBalance: BigInt(totalBalance) >= requiredBalance,\n balance: totalBalance,\n requiredBalance: requiredBalance.toString(),\n };\n }\n\n /**\n * Prepares a cash-subscription delegation and returns its hash.\n *\n * Reuses a stored AUS delegation that matches the semantic fingerprint when\n * one exists (ensuring a CHOMP intent is active for its hash, unless\n * `skipChompInteractions` is true). Reuse classifies period `startDate` as\n * trial-deferred (`> now`) vs immediately redeemable, matching creation.\n * If there is no match, builds, signs, optionally verifies with CHOMP,\n * persists, and optionally registers a new delegation.\n *\n * When `skipChompInteractions` is true (required for alpha), CHOMP verify\n * and intent calls are skipped; the returned hash is computed locally. The\n * default CHOMP-enabled path requires a follow-up chomp-api-service release\n * that accepts `'cash-subscription'` intent metadata.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @returns The delegation hash (CHOMP-verified unless skipped) and whether it\n * was created or reused.\n */\n async prepareDelegation(\n request: PrepareSubscriptionDelegationRequest,\n ): Promise<PreparedSubscriptionDelegation> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const skipChomp = Boolean(request.skipChompInteractions);\n\n const { chainId, delegateAddress, enforcers, price, token } =\n await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n\n if (request.checkBalance) {\n const { hasSufficientBalance } = await this.#compareMoneyAccountBalance(\n request.payerAddress,\n price,\n );\n if (!hasSufficientBalance) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.InsufficientBalance,\n );\n }\n }\n\n const periodAmount = calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: token.decimals,\n });\n const periodDuration = getPeriodDuration(request.recurringInterval);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const startDate = getDelegationStartDate({\n nowSeconds,\n trialPeriodDays: request.isTrialRequested\n ? price.trialPeriodDays\n : undefined,\n });\n const isTrialDeferred = startDate > nowSeconds;\n\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress,\n chainId,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n\n const existingDelegations = await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n );\n const reusable = existingDelegations.find(matches);\n if (reusable) {\n if (!skipChomp) {\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId,\n delegationHash: reusable.metadata.delegationHash,\n allowance: reusable.metadata.allowance,\n tokenSymbol: reusable.metadata.tokenSymbol,\n tokenAddress: reusable.metadata.tokenAddress,\n });\n }\n return {\n delegationHash: reusable.metadata.delegationHash,\n disposition: 'reused',\n };\n }\n\n const unsigned = buildUnsignedSubscriptionDelegation({\n delegateAddress,\n delegatorAddress: request.payerAddress,\n enforcers,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n { delegation: unsigned, chainId },\n )) as Hex;\n\n const signedDelegation = { ...unsigned, signature };\n\n const delegationHash = hashDelegation({\n ...unsigned,\n salt: BigInt(unsigned.salt),\n signature,\n });\n\n if (!skipChomp) {\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n {\n signedDelegation,\n chainId,\n },\n );\n\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (!equalsIgnoreCase(verifyResult.delegationHash, delegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\n }\n }\n\n const allowance: Hex = add0x(periodAmount.toString(16));\n\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: chainId,\n allowance,\n tokenSymbol: token.symbol,\n tokenAddress: token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n\n if (!skipChomp) {\n await this.#createIntent({\n account: request.payerAddress,\n chainId,\n delegationHash,\n allowance,\n tokenSymbol: token.symbol,\n tokenAddress: token.address,\n });\n }\n\n return {\n delegationHash,\n disposition: 'created',\n };\n }\n\n async #resolveConfiguration(\n product: ProductType,\n recurringInterval: RecurringInterval,\n ): Promise<ResolvedSubscriptionDelegationConfig> {\n const { remoteFeatureFlags } = this.#messenger.call(\n 'RemoteFeatureFlagController:getState',\n );\n const vaultConfig = getMoneyAccountVaultConfig(remoteFeatureFlags);\n if (!vaultConfig) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.MissingMoneyAccountVaultConfig,\n );\n }\n\n const { chainId } = vaultConfig;\n const enforcers = resolveEnforcers(chainId);\n const pricing = await this.#messenger.call(\n 'SubscriptionController:getPricing',\n );\n const price = pricing.products\n .find((entry) => entry.name === product)\n ?.prices.find((entry) => entry.interval === recurringInterval);\n const paymentMethod = pricing.paymentMethods.find(\n (entry): entry is PricingCryptoPaymentMethod =>\n entry.type === PAYMENT_TYPES.byCrypto &&\n entry.cryptoAuthMethod === CRYPTO_AUTH_METHODS.DELEGATION &&\n entry.products?.includes(product) === true,\n );\n const chain = paymentMethod?.chains?.find(\n (entry) => entry.chainId === chainId,\n );\n const token = chain?.tokens[0];\n if (!price || !chain?.delegateAddress || !token) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.PricingConfigurationNotFound,\n );\n }\n\n return {\n chainId,\n delegateAddress: chain.delegateAddress,\n enforcers,\n price,\n token,\n };\n }\n\n /**\n * Ensures an active CHOMP intent exists for the given delegation hash,\n * registering one when missing or revoked.\n *\n * @param params - Intent identity and metadata.\n * @param params.account - Delegator / payer address.\n * @param params.chainId - Chain ID of the delegation.\n * @param params.delegationHash - Hash of the stored delegation.\n * @param params.allowance - Period allowance stored with the delegation.\n * @param params.tokenSymbol - Payment token symbol.\n * @param params.tokenAddress - Payment token address.\n */\n async #ensureIntent(params: SubscriptionIntentParams): Promise<void> {\n const existingIntents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n params.account,\n );\n\n const hasActiveIntent = existingIntents.some(\n (intent) =>\n equalsIgnoreCase(intent.delegationHash, params.delegationHash) &&\n intent.status === 'active',\n );\n\n if (hasActiveIntent) {\n return;\n }\n\n await this.#createIntent(params);\n }\n\n async #createIntent(params: SubscriptionIntentParams): Promise<void> {\n // Published `@metamask/chomp-api-service` only types intent metadata as\n // `'cash-deposit' | 'cash-withdrawal'`. The dormant production path still\n // passes `'cash-subscription'`; a follow-up chomp-api-service release must\n // accept that discriminator before this path is production-ready. Alpha\n // callers must use `skipChompInteractions: true` so this method is not\n // reached.\n await this.#messenger.call('ChompApiService:createIntents', [\n {\n account: params.account,\n delegationHash: params.delegationHash,\n chainId: params.chainId,\n metadata: {\n allowance: params.allowance,\n tokenSymbol: params.tokenSymbol,\n tokenAddress: params.tokenAddress,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE as\n | 'cash-deposit'\n | 'cash-withdrawal',\n },\n },\n ]);\n }\n}\n"]}
@@ -0,0 +1,49 @@
1
+ import type { RecurringInterval } from '../types.js';
2
+ /**
3
+ * Rescales a plan fee from pricing `unitDecimals` into token base units.
4
+ *
5
+ * Uses a 1:1 numeric mapping (ADR 0057): the period amount is one billing
6
+ * interval's fee, not `fee × minimumFundingCycles`.
7
+ *
8
+ * @param params - Amount and decimal inputs.
9
+ * @param params.unitAmount - Fee in pricing minor units (non-negative integer).
10
+ * @param params.unitDecimals - Decimals of `unitAmount`.
11
+ * @param params.tokenDecimals - Decimals of the payment token.
12
+ * @returns The period amount in token base units.
13
+ * @throws If inputs are not non-negative integers, or downscaling would lose precision.
14
+ */
15
+ export declare function calculatePeriodAmount({ unitAmount, unitDecimals, tokenDecimals, }: {
16
+ unitAmount: number;
17
+ unitDecimals: number;
18
+ tokenDecimals: number;
19
+ }): bigint;
20
+ /**
21
+ * Plan-scoped ERC-20 period duration in seconds (ADR 0057).
22
+ *
23
+ * - Monthly: 28 days (minimum Stripe monthly invoice gap).
24
+ * - Yearly: 365 days.
25
+ *
26
+ * @param recurringInterval - Subscription billing interval.
27
+ * @returns Period duration in seconds.
28
+ */
29
+ export declare function getPeriodDuration(recurringInterval: RecurringInterval): number;
30
+ /**
31
+ * Computes the ERC20TokenPeriodTransfer `startDate` for a subscription
32
+ * delegation, optionally deferred by a pricing trial.
33
+ *
34
+ * @param params - Clock and optional trial length.
35
+ * @param params.nowSeconds - Current unix timestamp in seconds.
36
+ * @param params.trialPeriodDays - Optional non-negative trial length in days.
37
+ * Defaults to `0` (no offset) when omitted.
38
+ * @returns Unix timestamp when the first period transfer may begin.
39
+ */
40
+ export declare function getDelegationStartDate({ nowSeconds, trialPeriodDays, }: {
41
+ nowSeconds: number;
42
+ trialPeriodDays?: number;
43
+ }): number;
44
+ /**
45
+ * @param value - Candidate number.
46
+ * @param message - Error message when invalid.
47
+ */
48
+ export declare function assertPositiveInteger(value: number, message: string): void;
49
+ //# sourceMappingURL=amount.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"amount.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/amount.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAIrD;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,UAAU,EACV,YAAY,EACZ,aAAa,GACd,EAAE;IACD,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,MAAM,CA6BT;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,iBAAiB,EAAE,iBAAiB,GACnC,MAAM,CAUR;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,EACrC,UAAU,EACV,eAAmB,GACpB,EAAE;IACD,UAAU,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,GAAG,MAAM,CAMT;AAYD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAI1E"}
@@ -0,0 +1,84 @@
1
+ import { SubscriptionDelegationServiceErrorMessage } from '../constants.js';
2
+ import { RECURRING_INTERVALS } from '../types.js';
3
+ const SECONDS_PER_DAY = 86_400;
4
+ /**
5
+ * Rescales a plan fee from pricing `unitDecimals` into token base units.
6
+ *
7
+ * Uses a 1:1 numeric mapping (ADR 0057): the period amount is one billing
8
+ * interval's fee, not `fee × minimumFundingCycles`.
9
+ *
10
+ * @param params - Amount and decimal inputs.
11
+ * @param params.unitAmount - Fee in pricing minor units (non-negative integer).
12
+ * @param params.unitDecimals - Decimals of `unitAmount`.
13
+ * @param params.tokenDecimals - Decimals of the payment token.
14
+ * @returns The period amount in token base units.
15
+ * @throws If inputs are not non-negative integers, or downscaling would lose precision.
16
+ */
17
+ export function calculatePeriodAmount({ unitAmount, unitDecimals, tokenDecimals, }) {
18
+ assertNonNegativeInteger(unitAmount, SubscriptionDelegationServiceErrorMessage.InvalidAmount);
19
+ assertNonNegativeInteger(unitDecimals, SubscriptionDelegationServiceErrorMessage.InvalidDecimals);
20
+ assertNonNegativeInteger(tokenDecimals, SubscriptionDelegationServiceErrorMessage.InvalidDecimals);
21
+ const amount = BigInt(unitAmount);
22
+ if (tokenDecimals === unitDecimals) {
23
+ return amount;
24
+ }
25
+ if (tokenDecimals > unitDecimals) {
26
+ return amount * 10n ** BigInt(tokenDecimals - unitDecimals);
27
+ }
28
+ const divisor = 10n ** BigInt(unitDecimals - tokenDecimals);
29
+ if (amount % divisor !== 0n) {
30
+ throw new Error(SubscriptionDelegationServiceErrorMessage.LossyAmountScale);
31
+ }
32
+ return amount / divisor;
33
+ }
34
+ /**
35
+ * Plan-scoped ERC-20 period duration in seconds (ADR 0057).
36
+ *
37
+ * - Monthly: 28 days (minimum Stripe monthly invoice gap).
38
+ * - Yearly: 365 days.
39
+ *
40
+ * @param recurringInterval - Subscription billing interval.
41
+ * @returns Period duration in seconds.
42
+ */
43
+ export function getPeriodDuration(recurringInterval) {
44
+ if (recurringInterval === RECURRING_INTERVALS.month) {
45
+ return 28 * SECONDS_PER_DAY;
46
+ }
47
+ if (recurringInterval === RECURRING_INTERVALS.year) {
48
+ return 365 * SECONDS_PER_DAY;
49
+ }
50
+ throw new Error(SubscriptionDelegationServiceErrorMessage.UnsupportedRecurringInterval);
51
+ }
52
+ /**
53
+ * Computes the ERC20TokenPeriodTransfer `startDate` for a subscription
54
+ * delegation, optionally deferred by a pricing trial.
55
+ *
56
+ * @param params - Clock and optional trial length.
57
+ * @param params.nowSeconds - Current unix timestamp in seconds.
58
+ * @param params.trialPeriodDays - Optional non-negative trial length in days.
59
+ * Defaults to `0` (no offset) when omitted.
60
+ * @returns Unix timestamp when the first period transfer may begin.
61
+ */
62
+ export function getDelegationStartDate({ nowSeconds, trialPeriodDays = 0, }) {
63
+ assertNonNegativeInteger(trialPeriodDays, SubscriptionDelegationServiceErrorMessage.InvalidTrialPeriodDays);
64
+ return nowSeconds + trialPeriodDays * SECONDS_PER_DAY;
65
+ }
66
+ /**
67
+ * @param value - Candidate number.
68
+ * @param message - Error message when invalid.
69
+ */
70
+ function assertNonNegativeInteger(value, message) {
71
+ if (!Number.isInteger(value) || value < 0) {
72
+ throw new Error(message);
73
+ }
74
+ }
75
+ /**
76
+ * @param value - Candidate number.
77
+ * @param message - Error message when invalid.
78
+ */
79
+ export function assertPositiveInteger(value, message) {
80
+ if (!Number.isInteger(value) || value <= 0) {
81
+ throw new Error(message);
82
+ }
83
+ }
84
+ //# sourceMappingURL=amount.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"amount.js","sourceRoot":"","sources":["../../src/subscription-delegation/amount.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yCAAyC,EAAE,MAAM,iBAAiB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAGlD,MAAM,eAAe,GAAG,MAAM,CAAC;AAE/B;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qB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eAAe,EACf,yCAAyC,CAAC,sBAAsB,CACjE,CAAC;IACF,OAAO,UAAU,GAAG,eAAe,GAAG,eAAe,CAAC;AACxD,CAAC;AAED;;;GAGG;AACH,SAAS,wBAAwB,CAAC,KAAa,EAAE,OAAe;IAC9D,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAAa,EAAE,OAAe;IAClE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;AACH,CAAC","sourcesContent":["import { SubscriptionDelegationServiceErrorMessage } from '../constants.js';\nimport { RECURRING_INTERVALS } from '../types.js';\nimport type { RecurringInterval } from '../types.js';\n\nconst SECONDS_PER_DAY = 86_400;\n\n/**\n * Rescales a plan fee from pricing `unitDecimals` into token base units.\n *\n * Uses a 1:1 numeric mapping (ADR 0057): the period amount is one billing\n * interval's fee, not `fee × minimumFundingCycles`.\n *\n * @param params - Amount and decimal inputs.\n * @param params.unitAmount - Fee in pricing minor units (non-negative integer).\n * @param params.unitDecimals - Decimals of `unitAmount`.\n * @param params.tokenDecimals - Decimals of the payment token.\n * @returns The period amount in token base units.\n * @throws If inputs are not non-negative integers, or downscaling would lose precision.\n */\nexport function calculatePeriodAmount({\n unitAmount,\n unitDecimals,\n tokenDecimals,\n}: {\n unitAmount: number;\n unitDecimals: number;\n tokenDecimals: number;\n}): bigint {\n assertNonNegativeInteger(\n unitAmount,\n SubscriptionDelegationServiceErrorMessage.InvalidAmount,\n );\n assertNonNegativeInteger(\n unitDecimals,\n SubscriptionDelegationServiceErrorMessage.InvalidDecimals,\n );\n assertNonNegativeInteger(\n tokenDecimals,\n SubscriptionDelegationServiceErrorMessage.InvalidDecimals,\n );\n\n const amount = BigInt(unitAmount);\n\n if (tokenDecimals === unitDecimals) {\n return amount;\n }\n\n if (tokenDecimals > unitDecimals) {\n return amount * 10n ** BigInt(tokenDecimals - unitDecimals);\n }\n\n const divisor = 10n ** BigInt(unitDecimals - tokenDecimals);\n if (amount % divisor !== 0n) {\n throw new Error(SubscriptionDelegationServiceErrorMessage.LossyAmountScale);\n }\n return amount / divisor;\n}\n\n/**\n * Plan-scoped ERC-20 period duration in seconds (ADR 0057).\n *\n * - Monthly: 28 days (minimum Stripe monthly invoice gap).\n * - Yearly: 365 days.\n *\n * @param recurringInterval - Subscription billing interval.\n * @returns Period duration in seconds.\n */\nexport function getPeriodDuration(\n recurringInterval: RecurringInterval,\n): number {\n if (recurringInterval === RECURRING_INTERVALS.month) {\n return 28 * SECONDS_PER_DAY;\n }\n if (recurringInterval === RECURRING_INTERVALS.year) {\n return 365 * SECONDS_PER_DAY;\n }\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedRecurringInterval,\n );\n}\n\n/**\n * Computes the ERC20TokenPeriodTransfer `startDate` for a subscription\n * delegation, optionally deferred by a pricing trial.\n *\n * @param params - Clock and optional trial length.\n * @param params.nowSeconds - Current unix timestamp in seconds.\n * @param params.trialPeriodDays - Optional non-negative trial length in days.\n * Defaults to `0` (no offset) when omitted.\n * @returns Unix timestamp when the first period transfer may begin.\n */\nexport function getDelegationStartDate({\n nowSeconds,\n trialPeriodDays = 0,\n}: {\n nowSeconds: number;\n trialPeriodDays?: number;\n}): number {\n assertNonNegativeInteger(\n trialPeriodDays,\n SubscriptionDelegationServiceErrorMessage.InvalidTrialPeriodDays,\n );\n return nowSeconds + trialPeriodDays * SECONDS_PER_DAY;\n}\n\n/**\n * @param value - Candidate number.\n * @param message - Error message when invalid.\n */\nfunction assertNonNegativeInteger(value: number, message: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(message);\n }\n}\n\n/**\n * @param value - Candidate number.\n * @param message - Error message when invalid.\n */\nexport function assertPositiveInteger(value: number, message: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(message);\n }\n}\n"]}
@@ -0,0 +1,41 @@
1
+ import type { SignedDelegation } from '@metamask/authenticated-user-storage';
2
+ import type { Hex } from '@metamask/utils';
3
+ import type { SubscriptionDelegationEnforcers } from './types.js';
4
+ export type UnsignedSubscriptionDelegation = Omit<SignedDelegation, 'signature'>;
5
+ export type BuildSubscriptionCaveatsParams = {
6
+ enforcers: SubscriptionDelegationEnforcers;
7
+ delegateAddress: Hex;
8
+ tokenAddress: Hex;
9
+ periodAmount: bigint;
10
+ periodDuration: number;
11
+ startDate: number;
12
+ };
13
+ /**
14
+ * Builds the caveat list for a cash-subscription delegation:
15
+ * `ValueLte(0)` then `ERC20TokenPeriodTransfer(...)`.
16
+ * RedeemerEnforcer is temporarily omitted pending CHOMP guidance.
17
+ *
18
+ * @param params - Enforcer addresses, parties, and period terms.
19
+ * @param params.enforcers - Delegation Framework enforcer addresses.
20
+ * @param params.tokenAddress - Subscription settlement token.
21
+ * @param params.periodAmount - Maximum token amount per period.
22
+ * @param params.periodDuration - Period length in seconds.
23
+ * @param params.startDate - Unix timestamp when transfers may begin.
24
+ * @returns Caveats in enforcer order.
25
+ */
26
+ export declare function buildSubscriptionCaveats({ enforcers, tokenAddress, periodAmount, periodDuration, startDate, }: BuildSubscriptionCaveatsParams): SignedDelegation['caveats'];
27
+ export type BuildUnsignedSubscriptionDelegationParams = BuildSubscriptionCaveatsParams & {
28
+ delegatorAddress: Hex;
29
+ /**
30
+ * Optional salt for tests. When omitted, a random 32-byte salt is generated.
31
+ */
32
+ salt?: Hex;
33
+ };
34
+ /**
35
+ * Builds an unsigned root cash-subscription delegation.
36
+ *
37
+ * @param params - Delegation parties, enforcers, and period terms.
38
+ * @returns An unsigned delegation ready for signing.
39
+ */
40
+ export declare function buildUnsignedSubscriptionDelegation(params: BuildUnsignedSubscriptionDelegationParams): UnsignedSubscriptionDelegation;
41
+ //# sourceMappingURL=caveats.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caveats.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/caveats.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAO7E,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAElE,MAAM,MAAM,8BAA8B,GAAG,IAAI,CAC/C,gBAAgB,EAChB,WAAW,CACZ,CAAC;AAEF,MAAM,MAAM,8BAA8B,GAAG;IAC3C,SAAS,EAAE,+BAA+B,CAAC;IAC3C,eAAe,EAAE,GAAG,CAAC;IACrB,YAAY,EAAE,GAAG,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CAAC,EACvC,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,SAAS,GACV,EAAE,8BAA8B,GAAG,gBAAgB,CAAC,SAAS,CAAC,CAyB9D;AAED,MAAM,MAAM,yCAAyC,GACnD,8BAA8B,GAAG;IAC/B,gBAAgB,EAAE,GAAG,CAAC;IACtB;;OAEG;IACH,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ,CAAC;AAEJ;;;;;GAKG;AACH,wBAAgB,mCAAmC,CACjD,MAAM,EAAE,yCAAyC,GAChD,8BAA8B,CAYhC"}
@@ -0,0 +1,59 @@
1
+ import { ROOT_AUTHORITY, createERC20TokenPeriodTransferTerms, createValueLteTerms, } from '@metamask/delegation-core';
2
+ import { bytesToHex } from '@metamask/utils';
3
+ /**
4
+ * Builds the caveat list for a cash-subscription delegation:
5
+ * `ValueLte(0)` then `ERC20TokenPeriodTransfer(...)`.
6
+ * RedeemerEnforcer is temporarily omitted pending CHOMP guidance.
7
+ *
8
+ * @param params - Enforcer addresses, parties, and period terms.
9
+ * @param params.enforcers - Delegation Framework enforcer addresses.
10
+ * @param params.tokenAddress - Subscription settlement token.
11
+ * @param params.periodAmount - Maximum token amount per period.
12
+ * @param params.periodDuration - Period length in seconds.
13
+ * @param params.startDate - Unix timestamp when transfers may begin.
14
+ * @returns Caveats in enforcer order.
15
+ */
16
+ export function buildSubscriptionCaveats({ enforcers, tokenAddress, periodAmount, periodDuration, startDate, }) {
17
+ return [
18
+ {
19
+ enforcer: enforcers.valueLte,
20
+ terms: createValueLteTerms({ maxValue: 0n }),
21
+ args: '0x',
22
+ },
23
+ {
24
+ enforcer: enforcers.erc20TokenPeriodTransfer,
25
+ terms: createERC20TokenPeriodTransferTerms({
26
+ tokenAddress,
27
+ periodAmount,
28
+ periodDuration,
29
+ startDate,
30
+ }),
31
+ args: '0x',
32
+ },
33
+ // TODO: recheck with CHOMP team if we should set redeemer to subscription payment address
34
+ // or use allowed call data
35
+ // {
36
+ // enforcer: enforcers.redeemer,
37
+ // terms: createRedeemerTerms({ redeemers: [delegateAddress] }),
38
+ // args: '0x',
39
+ // },
40
+ ];
41
+ }
42
+ /**
43
+ * Builds an unsigned root cash-subscription delegation.
44
+ *
45
+ * @param params - Delegation parties, enforcers, and period terms.
46
+ * @returns An unsigned delegation ready for signing.
47
+ */
48
+ export function buildUnsignedSubscriptionDelegation(params) {
49
+ const salt = params.salt ??
50
+ bytesToHex(globalThis.crypto.getRandomValues(new Uint8Array(32)));
51
+ return {
52
+ delegate: params.delegateAddress,
53
+ delegator: params.delegatorAddress,
54
+ authority: ROOT_AUTHORITY,
55
+ caveats: buildSubscriptionCaveats(params),
56
+ salt,
57
+ };
58
+ }
59
+ //# sourceMappingURL=caveats.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caveats.js","sourceRoot":"","sources":["../../src/subscription-delegation/caveats.ts"],"names":[],"mappings":"AACA,OAAO,EACL,cAAc,EACd,mCAAmC,EACnC,mBAAmB,GACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAmB7C;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,wBAAwB,CAAC,EACvC,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,SAAS,GACsB;IAC/B,OAAO;QACL;YACE,QAAQ,EAAE,SAAS,CAAC,QAAQ;YAC5B,KAAK,EAAE,mBAAmB,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;YAC5C,IAAI,EAAE,IAAI;SACX;QACD;YACE,QAAQ,EAAE,SAAS,CAAC,wBAAwB;YAC5C,KAAK,EAAE,mCAAmC,CAAC;gBACzC,YAAY;gBACZ,YAAY;gBACZ,cAAc;gBACd,SAAS;aACV,CAAC;YACF,IAAI,EAAE,IAAI;SACX;QACD,0FAA0F;QAC1F,2BAA2B;QAC3B,IAAI;QACJ,kCAAkC;QAClC,kEAAkE;QAClE,gBAAgB;QAChB,KAAK;KACN,CAAC;AACJ,CAAC;AAWD;;;;;GAKG;AACH,MAAM,UAAU,mCAAmC,CACjD,MAAiD;IAEjD,MAAM,IAAI,GACR,MAAM,CAAC,IAAI;QACX,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAEpE,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,eAAe;QAChC,SAAS,EAAE,MAAM,CAAC,gBAAgB;QAClC,SAAS,EAAE,cAAc;QACzB,OAAO,EAAE,wBAAwB,CAAC,MAAM,CAAC;QACzC,IAAI;KACL,CAAC;AACJ,CAAC","sourcesContent":["import type { SignedDelegation } from '@metamask/authenticated-user-storage';\nimport {\n ROOT_AUTHORITY,\n createERC20TokenPeriodTransferTerms,\n createValueLteTerms,\n} from '@metamask/delegation-core';\nimport { bytesToHex } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport type { SubscriptionDelegationEnforcers } from './types.js';\n\nexport type UnsignedSubscriptionDelegation = Omit<\n SignedDelegation,\n 'signature'\n>;\n\nexport type BuildSubscriptionCaveatsParams = {\n enforcers: SubscriptionDelegationEnforcers;\n delegateAddress: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n startDate: number;\n};\n\n/**\n * Builds the caveat list for a cash-subscription delegation:\n * `ValueLte(0)` then `ERC20TokenPeriodTransfer(...)`.\n * RedeemerEnforcer is temporarily omitted pending CHOMP guidance.\n *\n * @param params - Enforcer addresses, parties, and period terms.\n * @param params.enforcers - Delegation Framework enforcer addresses.\n * @param params.tokenAddress - Subscription settlement token.\n * @param params.periodAmount - Maximum token amount per period.\n * @param params.periodDuration - Period length in seconds.\n * @param params.startDate - Unix timestamp when transfers may begin.\n * @returns Caveats in enforcer order.\n */\nexport function buildSubscriptionCaveats({\n enforcers,\n tokenAddress,\n periodAmount,\n periodDuration,\n startDate,\n}: BuildSubscriptionCaveatsParams): SignedDelegation['caveats'] {\n return [\n {\n enforcer: enforcers.valueLte,\n terms: createValueLteTerms({ maxValue: 0n }),\n args: '0x',\n },\n {\n enforcer: enforcers.erc20TokenPeriodTransfer,\n terms: createERC20TokenPeriodTransferTerms({\n tokenAddress,\n periodAmount,\n periodDuration,\n startDate,\n }),\n args: '0x',\n },\n // TODO: recheck with CHOMP team if we should set redeemer to subscription payment address\n // or use allowed call data\n // {\n // enforcer: enforcers.redeemer,\n // terms: createRedeemerTerms({ redeemers: [delegateAddress] }),\n // args: '0x',\n // },\n ];\n}\n\nexport type BuildUnsignedSubscriptionDelegationParams =\n BuildSubscriptionCaveatsParams & {\n delegatorAddress: Hex;\n /**\n * Optional salt for tests. When omitted, a random 32-byte salt is generated.\n */\n salt?: Hex;\n };\n\n/**\n * Builds an unsigned root cash-subscription delegation.\n *\n * @param params - Delegation parties, enforcers, and period terms.\n * @returns An unsigned delegation ready for signing.\n */\nexport function buildUnsignedSubscriptionDelegation(\n params: BuildUnsignedSubscriptionDelegationParams,\n): UnsignedSubscriptionDelegation {\n const salt =\n params.salt ??\n bytesToHex(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n\n return {\n delegate: params.delegateAddress,\n delegator: params.delegatorAddress,\n authority: ROOT_AUTHORITY,\n caveats: buildSubscriptionCaveats(params),\n salt,\n };\n}\n"]}