@metamask-previews/subscription-controller 12.0.1-preview-3b264bf6d → 12.0.1-preview-5e76941
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 +13 -0
- package/dist/constants.d.ts +0 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +0 -2
- package/dist/constants.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts +9 -14
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts +10 -16
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService.js +33 -104
- package/dist/subscription-delegation/SubscriptionDelegationService.js.map +1 -1
- package/dist/subscription-delegation/types.d.ts +0 -21
- package/dist/subscription-delegation/types.d.ts.map +1 -1
- package/dist/subscription-delegation/types.js +0 -1
- package/dist/subscription-delegation/types.js.map +1 -1
- package/package.json +1 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- **BREAKING:** `SubscriptionDelegationService:startSubscriptionWithDelegation` no longer requests an approval. Callers must obtain consent and initiate funding (for example, a `membershipSubscription` transaction) before calling. ([#10666](https://github.com/MetaMask/core/pull/10666))
|
|
13
|
+
- `skipApproval` is removed from `StartSubscriptionWithDelegationRequest`.
|
|
14
|
+
|
|
15
|
+
### Removed
|
|
16
|
+
|
|
17
|
+
- **BREAKING:** Remove the subscription delegation approval contracts. ([#10666](https://github.com/MetaMask/core/pull/10666))
|
|
18
|
+
- Remove `SUBSCRIPTION_DELEGATION_APPROVAL_TYPE`, `SubscriptionFundingRequest`, and `SubscriptionDelegationApprovalResult`.
|
|
19
|
+
- Remove `ApprovalResultMissing` and `InvalidFundingTransactionHash` from `SubscriptionDelegationServiceErrorMessage`.
|
|
20
|
+
- `SubscriptionDelegationServiceMessenger` no longer allows `ApprovalController:addRequest`. Clients that construct this messenger must stop delegating that action.
|
|
21
|
+
- Remove the `@metamask/approval-controller` dependency. ([#10666](https://github.com/MetaMask/core/pull/10666))
|
|
22
|
+
|
|
10
23
|
## [12.0.1]
|
|
11
24
|
|
|
12
25
|
### Changed
|
package/dist/constants.d.ts
CHANGED
|
@@ -72,8 +72,6 @@ export declare enum SubscriptionDelegationServiceErrorMessage {
|
|
|
72
72
|
ChompMissingDelegationHash = "CHOMP verify response did not include a delegation hash",
|
|
73
73
|
ChompDelegationHashMismatch = "CHOMP verify response delegation hash does not match the locally computed hash",
|
|
74
74
|
ChainMismatch = "Subscription delegation chain does not match the Money Account chain",
|
|
75
|
-
ApprovalResultMissing = "Subscription delegation approval result is missing",
|
|
76
|
-
InvalidFundingTransactionHash = "Subscription funding transaction hash is invalid",
|
|
77
75
|
ReusableDelegationInvalid = "Reusable subscription delegation is missing or invalid",
|
|
78
76
|
TrialEligibilityChanged = "Subscription trial eligibility changed after authorization",
|
|
79
77
|
ChompIntentNotActive = "CHOMP subscription intent is not active"
|
package/dist/constants.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD;;GAEG;AACH,eAAO,MAAM,oBAAoB;aAE/B,aAAa,EAAE,eAAe;aAE9B,kBAAkB,EAAE,oBAAoB;aAExC,wBAAwB,EAAE,0BAA0B;aAEpD,sBAAsB,EAAE,wBAAwB;aA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A2B;IAC9C,kBAAkB,0BAA0B;IAC5C,2BAA2B,qCAAqC;CACjE;AAED,oBAAY,yCAAyC;IACnD,aAAa,kEAAkE;IAC/E,eAAe,oEAAoE;IACnF,sBAAsB,6EAA6E;IACnG,2BAA2B,8EAA8E;IACzG,gBAAgB,wFAAwF;IACxG,4BAA4B,gDAAgD;IAC5E,kBAAkB,gEAAgE;IAClF,8BAA8B,4DAA4D;IAC1F,2BAA2B,8EAA8E;IACzG,4BAA4B,gEAAgE;IAC5F,uBAAuB,sEAAsE;IAC7F,mBAAmB,mFAAmF;IACtG,uBAAuB,+CAA+C;IACtE,0BAA0B,4DAA4D;IACtF,2BAA2B,mFAAmF;IAC9G,aAAa,yEAAyE;IACtF,yBAAyB,2DAA2D;IACpF,uBAAuB,+DAA+D;IACtF,oBAAoB,4CAA4C;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,EAIpC,MAAM,EAAE,CAAC"}
|
package/dist/constants.js
CHANGED
|
@@ -96,8 +96,6 @@ export var SubscriptionDelegationServiceErrorMessage;
|
|
|
96
96
|
SubscriptionDelegationServiceErrorMessage["ChompMissingDelegationHash"] = "CHOMP verify response did not include a delegation hash";
|
|
97
97
|
SubscriptionDelegationServiceErrorMessage["ChompDelegationHashMismatch"] = "CHOMP verify response delegation hash does not match the locally computed hash";
|
|
98
98
|
SubscriptionDelegationServiceErrorMessage["ChainMismatch"] = "Subscription delegation chain does not match the Money Account chain";
|
|
99
|
-
SubscriptionDelegationServiceErrorMessage["ApprovalResultMissing"] = "Subscription delegation approval result is missing";
|
|
100
|
-
SubscriptionDelegationServiceErrorMessage["InvalidFundingTransactionHash"] = "Subscription funding transaction hash is invalid";
|
|
101
99
|
SubscriptionDelegationServiceErrorMessage["ReusableDelegationInvalid"] = "Reusable subscription delegation is missing or invalid";
|
|
102
100
|
SubscriptionDelegationServiceErrorMessage["TrialEligibilityChanged"] = "Subscription trial eligibility changed after authorization";
|
|
103
101
|
SubscriptionDelegationServiceErrorMessage["ChompIntentNotActive"] = "CHOMP subscription intent is not active";
|
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEnD,MAAM,CAAC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,6BAA6B;IAC7B,aAAa,EAAE,eAAe;IAC9B,8BAA8B;IAC9B,kBAAkB,EAAE,oBAAoB;IACxC,uCAAuC;IACvC,wBAAwB,EAAE,0BAA0B;IACpD,wBAAwB;IACxB,sBAAsB,EAAE,wBAAwB;IAChD,uBAAuB;IACvB,oBAAoB,EAAE,sBAAsB;IAC5C,QAAQ;IACR,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,MAAM,CAAN,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,KAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,yCAAyC;KAC9D;CACF,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,GAAQ;IACjC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC;AAED,MAAM,CAAN,IAAY,kCAUX;AAVD,WAAY,kCAAkC;IAC5C,mHAAwE,CAAA;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MAAM,CAAN,IAAY,yCAoBX;AApBD,WAAY,yCAAyC;IACnD,4HAA+E,CAAA;IAC/E,gIAAmF,CAAA;IACnF,gJAAmG,CAAA;IACnG,sJAAyG,CAAA;IACzG,qJAAwG,CAAA;IACxG,yHAA4E,CAAA;IAC5E,+HAAkF,CAAA;IAClF,uIAA0F,CAAA;IAC1F,sJAAyG,CAAA;IACzG,yIAA4F,CAAA;IAC5F,0IAA6F,CAAA;IAC7F,mJAAsG,CAAA;IACtG,mHAAsE,CAAA;IACtE,mIAAsF,CAAA;IACtF,2JAA8G,CAAA;IAC9G,mIAAsF,CAAA;IACtF,iIAAoF,CAAA;IACpF,mIAAsF,CAAA;IACtF,6GAAgE,CAAA;AAClE,CAAC,EApBW,yCAAyC,KAAzC,yCAAyC,QAoBpD;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC,YAAY;AAEpE,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC1C,qBAAqB,CAAC,MAAM;IAC5B,qBAAqB,CAAC,QAAQ;IAC9B,qBAAqB,CAAC,WAAW;CACtB,CAAC","sourcesContent":["import { SUBSCRIPTION_STATUSES } from './types.js';\n\nexport const controllerName = 'SubscriptionController';\n\n/**\n * API cancellation reason values and their client-facing text.\n */\nexport const CANCELLATION_REASONS = {\n // Costs more than it's worth\n TOO_EXPENSIVE: 'too_expensive',\n // I wasn't using the benefits\n NOT_USING_BENEFITS: 'not_using_benefits',\n // The benefits weren't what I expected\n BENEFITS_NOT_AS_EXPECTED: 'benefits_not_as_expected',\n // Something didn't work\n SOMETHING_DID_NOT_WORK: 'something_did_not_work',\n // Unhappy with support\n UNHAPPY_WITH_SUPPORT: 'unhappy_with_support',\n // Other\n OTHER: 'other',\n} as const;\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n CryptoApprovalRequiresShieldApprove = `${controllerName} - Crypto approval is only supported for Shield ERC-20 approve transactions`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport enum SubscriptionServiceErrorMessage {\n FailedToGetSubscriptions = 'Failed to get subscriptions',\n FailedToGetBenefits = 'Failed to get benefits',\n FailedToCancelSubscription = 'Failed to cancel subscription',\n FailedToUncancelSubscription = 'Failed to uncancel subscription',\n FailedToStartSubscriptionWithCard = 'Failed to start subscription with card',\n FailedToStartSubscriptionWithCrypto = 'Failed to start subscription with crypto',\n InvalidCryptoAuthCombo = 'Crypto subscription requires exactly one of rawTransaction (erc20_approval) or delegationHash (delegation)',\n FailedToUpdatePaymentMethodCard = 'Failed to update payment method card',\n FailedToUpdatePaymentMethodCrypto = 'Failed to update payment method crypto',\n FailedToGetSubscriptionsEligibilities = 'Failed to get subscriptions eligibilities',\n FailedToSubmitUserEvent = 'Failed to submit user event',\n FailedToAssignUserToCohort = 'Failed to assign user to cohort',\n FailedToSubmitSponsorshipIntents = 'Failed to submit sponsorship intents',\n FailedToLinkRewards = 'Failed to link rewards',\n FailedToGetPricing = 'Failed to get pricing',\n FailedToGetBillingPortalUrl = 'Failed to get billing portal url',\n}\n\nexport enum SubscriptionDelegationServiceErrorMessage {\n InvalidAmount = 'Subscription delegation amount must be a non-negative integer',\n InvalidDecimals = 'Subscription delegation decimals must be a non-negative integer',\n InvalidTrialPeriodDays = 'Subscription delegation trial period days must be a non-negative integer',\n InvalidMinimumFundingCycles = 'Subscription delegation minimum funding cycles must be a positive integer',\n LossyAmountScale = 'Subscription delegation amount cannot be scaled to token decimals without remainder',\n UnsupportedRecurringInterval = 'Unsupported subscription recurring interval',\n UnsupportedProduct = 'Subscription delegation is only supported for Money Account',\n MissingMoneyAccountVaultConfig = 'Money Account vault configuration is missing or invalid',\n DelegationContractsNotFound = 'Subscription delegation contracts were not found for the configured chain',\n PricingConfigurationNotFound = 'Subscription delegation pricing configuration was not found',\n InvalidRecipientAddress = 'Subscription delegation recipient must be a valid 20-byte address',\n InsufficientBalance = 'Money Account balance is insufficient for the subscription funding requirement',\n ChompRejectedDelegation = 'CHOMP rejected the subscription delegation',\n ChompMissingDelegationHash = 'CHOMP verify response did not include a delegation hash',\n ChompDelegationHashMismatch = 'CHOMP verify response delegation hash does not match the locally computed hash',\n ChainMismatch = 'Subscription delegation chain does not match the Money Account chain',\n ReusableDelegationInvalid = 'Reusable subscription delegation is missing or invalid',\n TrialEligibilityChanged = 'Subscription trial eligibility changed after authorization',\n ChompIntentNotActive = 'CHOMP subscription intent is not active',\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,6 @@ export { SubscriptionDelegationService, serviceName as subscriptionDelegationSer
|
|
|
15
15
|
export type { SubscriptionDelegationServicePrepareDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';
|
|
16
16
|
export type { SubscriptionDelegationServiceCheckMoneyAccountBalanceAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';
|
|
17
17
|
export type { SubscriptionDelegationServiceStartSubscriptionWithDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';
|
|
18
|
-
export type { ChompIntentType, CommitAuthorizationBundleRequest, CommitAuthorizationBundleResult, DecodedPermission, MoneyAccountAuthorizationReason, MoneyAccountBalanceCheckRequest, MoneyAccountBalanceCheckResult, PrepareSubscriptionDelegationRequest, PrepareAuthorizationBundleResult, PreparedSubscriptionDelegation, PreparedSubscriptionDelegationBundle, PreparedSubscriptionPermission, SignedSubscriptionDelegation, StartSubscriptionWithDelegationRequest, StartSubscriptionWithDelegationResult,
|
|
19
|
-
export { CASH_SUBSCRIPTION_DELEGATION_TYPE,
|
|
18
|
+
export type { ChompIntentType, CommitAuthorizationBundleRequest, CommitAuthorizationBundleResult, DecodedPermission, MoneyAccountAuthorizationReason, MoneyAccountBalanceCheckRequest, MoneyAccountBalanceCheckResult, PrepareSubscriptionDelegationRequest, PrepareAuthorizationBundleResult, PreparedSubscriptionDelegation, PreparedSubscriptionDelegationBundle, PreparedSubscriptionPermission, SignedSubscriptionDelegation, StartSubscriptionWithDelegationRequest, StartSubscriptionWithDelegationResult, SubscriptionDelegationTypedData, SubscriptionPermissionId, UnsignedSubscriptionDelegation, } from './subscription-delegation/types.js';
|
|
19
|
+
export { CASH_SUBSCRIPTION_DELEGATION_TYPE, SUBSCRIPTION_DELEGATION_POLICY_VERSION, } from './subscription-delegation/types.js';
|
|
20
20
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,MAAM,6BAA6B,CAAC;AACrC,YAAY,EACV,sCAAsC,EACtC,4CAA4C,EAC5C,uCAAuC,EACvC,oDAAoD,EACpD,kDAAkD,EAClD,yDAAyD,EACzD,8CAA8C,EAC9C,gDAAgD,EAChD,qDAAqD,EACrD,uDAAuD,EACvD,4DAA4D,EAC5D,6DAA6D,EAC7D,+CAA+C,EAC/C,+CAA+C,EAC/C,0DAA0D,EAC1D,0DAA0D,EAC1D,oDAAoD,EACpD,2CAA2C,EAC3C,8CAA8C,EAC9C,uCAAuC,EACvC,iDAAiD,EACjD,wDAAwD,EACxD,sCAAsC,EACtC,qDAAqD,EACrD,0CAA0C,GAC3C,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,MAAM,6BAA6B,CAAC;AACrC,YAAY,EACV,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,EACnB,4BAA4B,EAC5B,yBAAyB,EACzB,iBAAiB,EACjB,SAAS,EACT,yBAAyB,EACzB,UAAU,EACV,sBAAsB,EACtB,oBAAoB,EACpB,8BAA8B,EAC9B,wCAAwC,EACxC,mCAAmC,EACnC,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,uCAAuC,EACvC,6BAA6B,EAC7B,+BAA+B,EAC/B,yBAAyB,EACzB,mBAAmB,EACnB,oBAAoB,EACpB,sBAAsB,EACtB,+BAA+B,EAC/B,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAA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AAmC,EACnC,4CAA4C,GAC7C,MAAM,8CAA8C,CAAC;AAEtD,YAAY,EACV,oCAAoC,EACpC,mCAAmC,EACnC,sCAAsC,EACtC,oCAAoC,GACrC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EACL,6BAA6B,EAC7B,WAAW,IAAI,iCAAiC,GACjD,MAAM,4DAA4D,CAAC;AACpE,YAAY,EAAE,oDAAoD,EAAE,MAAM,gFAAgF,CAAC;AAC3J,YAAY,EAAE,2DAA2D,EAAE,MAAM,gFAAgF,CAAC;AAClK,YAAY,EAAE,kEAAkE,EAAE,MAAM,gFAAgF,CAAC;AACzK,YAAY,EACV,eAAe,EACf,gCAAgC,EAChC,+BAA+B,EAC/B,iBAAiB,EACjB,+BAA+B,EAC/B,+BAA+B,EAC/B,8BAA8B,EAC9B,oCAAoC,EACpC,gCAAgC,EAChC,8BAA8B,EAC9B,oCAAoC,EACpC,8BAA8B,EAC9B,4BAA4B,EAC5B,sCAAsC,EACtC,qCAAqC,EACrC,+BAA+B,EAC/B,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,iCAAiC,EACjC,sCAAsC,GACvC,MAAM,oCAAoC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -6,5 +6,5 @@ export { SubscriptionServiceError } from './errors.js';
|
|
|
6
6
|
export { Env, SubscriptionControllerErrorMessage, SubscriptionServiceErrorMessage, SubscriptionDelegationServiceErrorMessage, } from './constants.js';
|
|
7
7
|
export { SubscriptionService, serviceName as subscriptionServiceName, SUBSCRIPTION_URL, } from './SubscriptionService.js';
|
|
8
8
|
export { SubscriptionDelegationService, serviceName as subscriptionDelegationServiceName, } from './subscription-delegation/SubscriptionDelegationService.js';
|
|
9
|
-
export { CASH_SUBSCRIPTION_DELEGATION_TYPE,
|
|
9
|
+
export { CASH_SUBSCRIPTION_DELEGATION_TYPE, SUBSCRIPTION_DELEGATION_POLICY_VERSION, } from './subscription-delegation/types.js';
|
|
10
10
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoCA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,MAAM,6BAA6B,CAAC;AA0ErC,OAAO,EACL,YAAY,EACZ,4BAA4B,EAC5B,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,qBAAqB,EACrB,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,mBAAmB,EACnB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EACL,GAAG,EACH,kCAAkC,EAClC,+BAA+B,EAC/B,yCAAyC,GAC1C,MAAM,gBAAgB,CAAC;AAUxB,OAAO,EACL,mBAAmB,EACnB,WAAW,IAAI,uBAAuB,EACtC,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAyBlC,OAAO,EACL,6BAA6B,EAC7B,WAAW,IAAI,iCAAiC,GACjD,MAAM,4DAA4D,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoCA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,MAAM,6BAA6B,CAAC;AA0ErC,OAAO,EACL,YAAY,EACZ,4BAA4B,EAC5B,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,aAAa,EACb,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,qBAAqB,EACrB,YAAY,EACZ,kBAAkB,EAClB,UAAU,EACV,mBAAmB,EACnB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EACL,GAAG,EACH,kCAAkC,EAClC,+BAA+B,EAC/B,yCAAyC,GAC1C,MAAM,gBAAgB,CAAC;AAUxB,OAAO,EACL,mBAAmB,EACnB,WAAW,IAAI,uBAAuB,EACtC,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAyBlC,OAAO,EACL,6BAA6B,EAC7B,WAAW,IAAI,iCAAiC,GACjD,MAAM,4DAA4D,CAAC;AAwBpE,OAAO,EACL,iCAAiC,EACjC,sCAAsC,GACvC,MAAM,oCAAoC,CAAC","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController.js';\nexport type {\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerGetBenefitsAction,\n SubscriptionControllerGetSubscriptionByProductAction,\n SubscriptionControllerIsUserEligibleForTrialAction,\n SubscriptionControllerGetSubscriptionsEligibilitiesAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerUnCancelSubscriptionAction,\n SubscriptionControllerStartSubscriptionWithCardAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerSubmitSubscriptionCryptoApprovalAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerUpdatePaymentMethodAction,\n SubscriptionControllerGetBillingPortalUrlAction,\n SubscriptionControllerCacheLastSelectedPaymentMethodAction,\n SubscriptionControllerClearLastSelectedPaymentMethodAction,\n SubscriptionControllerSubmitSponsorshipIntentsAction,\n SubscriptionControllerSubmitUserEventAction,\n SubscriptionControllerAssignUserToCohortAction,\n SubscriptionControllerLinkRewardsAction,\n SubscriptionControllerGetTokenApproveAmountAction,\n SubscriptionControllerGetTokenMinimumBalanceAmountAction,\n SubscriptionControllerClearStateAction,\n SubscriptionControllerTriggerAccessTokenRefreshAction,\n SubscriptionControllerStopAllPollingAction,\n} from './SubscriptionController-method-action-types.js';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController.js';\nexport type {\n SubscriptionApiError,\n Subscription,\n PerpsBenefitUsage,\n PredictBenefitUsage,\n SubscriptionBenefitsResponse,\n SubscriptionBenefitsState,\n SwapsBenefitUsage,\n AuthUtils,\n CancelSubscriptionRequest,\n CancelType,\n CancellationReasonCode,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartDelegationCryptoSubscriptionRequest,\n StartErc20CryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n SubmitSubscriptionCryptoApprovalRequest,\n SubscriptionCardPaymentMethod,\n SubscriptionCryptoPaymentMethod,\n SubscriptionPaymentMethod,\n SubscriptionInvoice,\n InvoicePaymentStatus,\n SubmitUserEventRequest,\n SubmitSponsorshipIntentsRequest,\n SubscriptionEligibility,\n SubscriptionUserEventType,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n SpotTokenPaymentInfo,\n VaultTokenPaymentInfo,\n VaultName,\n ChainPaymentInfo,\n Currency,\n CryptoAuthMethod,\n PricingPaymentMethod,\n PricingCardPaymentMethod,\n PricingCryptoPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n BillingPortalResponse,\n CryptoPaymentMethodError,\n CryptoPaymentError,\n UpdateErc20PaymentMethodCryptoRequest,\n UpdateDelegationPaymentMethodCryptoRequest,\n UpdatePaymentMethodCryptoRequest,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCardResponse,\n CachedLastSelectedPaymentMethod,\n CacheLastSelectedPaymentMethodRequest,\n SubmitSponsorshipIntentsMethodParams,\n Cohort,\n CohortName,\n BalanceCategory,\n AssignCohortRequest,\n GetSubscriptionsEligibilitiesRequest,\n ModalType,\n MoneyAccountEntitlements,\n MoneyAccountPlusClaim,\n ProductEntitlementFeatureMap,\n ProductEntitlements,\n ShieldEntitlements,\n} from './types.js';\nexport {\n CANCEL_TYPES,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n CRYPTO_PAYMENT_ERRORS,\n INVOICE_PAYMENT_STATUSES,\n SUBSCRIPTION_STATUSES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n PAYMENT_TYPES,\n CRYPTO_AUTH_METHODS,\n VAULT_NAMES,\n isVaultShareToken,\n SubscriptionUserEvent,\n COHORT_NAMES,\n BALANCE_CATEGORIES,\n MODAL_TYPE,\n MoneyAccountFeature,\n ShieldFeature,\n} from './types.js';\nexport { CANCELLATION_REASONS } from './constants.js';\nexport {\n selectHasEntitlement,\n selectIsActiveSubscriber,\n selectIsUsageAvailable,\n selectIsPaymentFailed,\n selectPaymentFailureReason,\n selectIsRenewalNeeded,\n selectIsDelegationExhausted,\n} from './selectors.js';\nexport { SubscriptionServiceError } from './errors.js';\nexport {\n Env,\n SubscriptionControllerErrorMessage,\n SubscriptionServiceErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from './constants.js';\nexport type {\n SubscriptionServiceOptions,\n SubscriptionServiceMessenger,\n SubscriptionServiceActions,\n SubscriptionServiceEvents,\n SubscriptionServiceCacheUpdatedEvent,\n SubscriptionServiceGranularCacheUpdatedEvent,\n SubscriptionServiceInvalidateQueriesAction,\n} from './SubscriptionService.js';\nexport {\n SubscriptionService,\n serviceName as subscriptionServiceName,\n SUBSCRIPTION_URL,\n} from './SubscriptionService.js';\nexport type {\n SubscriptionServiceGetSubscriptionsAction,\n SubscriptionServiceGetBenefitsAction,\n SubscriptionServiceCancelSubscriptionAction,\n SubscriptionServiceUnCancelSubscriptionAction,\n SubscriptionServiceStartSubscriptionWithCardAction,\n SubscriptionServiceStartSubscriptionWithCryptoAction,\n SubscriptionServiceUpdatePaymentMethodCardAction,\n SubscriptionServiceUpdatePaymentMethodCryptoAction,\n SubscriptionServiceGetSubscriptionsEligibilitiesAction,\n SubscriptionServiceSubmitUserEventAction,\n SubscriptionServiceAssignUserToCohortAction,\n SubscriptionServiceSubmitSponsorshipIntentsAction,\n SubscriptionServiceLinkRewardsAction,\n SubscriptionServiceGetPricingAction,\n SubscriptionServiceGetBillingPortalUrlAction,\n} from './SubscriptionService-method-action-types.js';\n\nexport type {\n SubscriptionDelegationServiceActions,\n SubscriptionDelegationServiceEvents,\n SubscriptionDelegationServiceMessenger,\n SubscriptionDelegationServiceOptions,\n} from './subscription-delegation/SubscriptionDelegationService.js';\nexport {\n SubscriptionDelegationService,\n serviceName as subscriptionDelegationServiceName,\n} from './subscription-delegation/SubscriptionDelegationService.js';\nexport type { SubscriptionDelegationServicePrepareDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';\nexport type { SubscriptionDelegationServiceCheckMoneyAccountBalanceAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';\nexport type { SubscriptionDelegationServiceStartSubscriptionWithDelegationAction } from './subscription-delegation/SubscriptionDelegationService-method-action-types.js';\nexport type {\n ChompIntentType,\n CommitAuthorizationBundleRequest,\n CommitAuthorizationBundleResult,\n DecodedPermission,\n MoneyAccountAuthorizationReason,\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PrepareAuthorizationBundleResult,\n PreparedSubscriptionDelegation,\n PreparedSubscriptionDelegationBundle,\n PreparedSubscriptionPermission,\n SignedSubscriptionDelegation,\n StartSubscriptionWithDelegationRequest,\n StartSubscriptionWithDelegationResult,\n SubscriptionDelegationTypedData,\n SubscriptionPermissionId,\n UnsignedSubscriptionDelegation,\n} from './subscription-delegation/types.js';\nexport {\n CASH_SUBSCRIPTION_DELEGATION_TYPE,\n SUBSCRIPTION_DELEGATION_POLICY_VERSION,\n} from './subscription-delegation/types.js';\n"]}
|
|
@@ -18,22 +18,17 @@ export type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {
|
|
|
18
18
|
* Runs the complete Money Account subscription checkout authorization flow.
|
|
19
19
|
*
|
|
20
20
|
* Subscriptions are refreshed first. An active subscription for the product
|
|
21
|
-
* is rejected before Money Account upgrade,
|
|
22
|
-
*
|
|
21
|
+
* is rejected before Money Account upgrade, delegation signing, persistence,
|
|
22
|
+
* or CHOMP registration.
|
|
23
23
|
*
|
|
24
|
-
*
|
|
25
|
-
* the Money Account vault
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* delegation signing, persistence, or intent mutation occurs before
|
|
29
|
-
*
|
|
24
|
+
* The caller must obtain user consent and initiate funding before calling.
|
|
25
|
+
* `MoneyAccountUpgradeController` ensures the Money Account vault
|
|
26
|
+
* delegations and CHOMP intents exist. The Subscription API validates those
|
|
27
|
+
* delegations and the Money Account balance server-side. No payment
|
|
28
|
+
* delegation signing, persistence, or intent mutation occurs before the
|
|
29
|
+
* account is upgraded.
|
|
30
30
|
*
|
|
31
|
-
*
|
|
32
|
-
* result validation are skipped and the flow proceeds directly to signing.
|
|
33
|
-
* The caller is then responsible for consent and funding.
|
|
34
|
-
*
|
|
35
|
-
* @param request - Product selection, Money Account identity, and optional
|
|
36
|
-
* `skipApproval` flag.
|
|
31
|
+
* @param request - Product selection and Money Account identity.
|
|
37
32
|
* @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.
|
|
38
33
|
*/
|
|
39
34
|
export type SubscriptionDelegationServiceStartSubscriptionWithDelegationAction = {
|
package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService-method-action-types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AAExF;;;;;;GAMG;AACH,MAAM,MAAM,2DAA2D,GAAG;IACxE,IAAI,EAAE,wDAAwD,CAAC;IAC/D,OAAO,EAAE,6BAA6B,CAAC,0BAA0B,CAAC,CAAC;CACpE,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService-method-action-types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AAExF;;;;;;GAMG;AACH,MAAM,MAAM,2DAA2D,GAAG;IACxE,IAAI,EAAE,wDAAwD,CAAC;IAC/D,OAAO,EAAE,6BAA6B,CAAC,0BAA0B,CAAC,CAAC;CACpE,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,kEAAkE,GAC5E;IACE,IAAI,EAAE,+DAA+D,CAAC;IACtE,OAAO,EAAE,6BAA6B,CAAC,iCAAiC,CAAC,CAAC;CAC3E,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,MAAM,oDAAoD,GAAG;IACjE,IAAI,EAAE,iDAAiD,CAAC;IACxD,OAAO,EAAE,6BAA6B,CAAC,mBAAmB,CAAC,CAAC;CAC7D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0CAA0C,GAClD,2DAA2D,GAC3D,kEAAkE,GAClE,oDAAoD,CAAC"}
|
package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService-method-action-types.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionDelegationService } from './SubscriptionDelegationService.js';\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 */\nexport type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {\n type: `SubscriptionDelegationService:checkMoneyAccountBalance`;\n handler: SubscriptionDelegationService['checkMoneyAccountBalance'];\n};\n\n/**\n * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade,
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService-method-action-types.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { SubscriptionDelegationService } from './SubscriptionDelegationService.js';\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 */\nexport type SubscriptionDelegationServiceCheckMoneyAccountBalanceAction = {\n type: `SubscriptionDelegationService:checkMoneyAccountBalance`;\n handler: SubscriptionDelegationService['checkMoneyAccountBalance'];\n};\n\n/**\n * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade, delegation signing, persistence,\n * or CHOMP registration.\n *\n * The caller must obtain user consent and initiate funding before calling.\n * `MoneyAccountUpgradeController` ensures the Money Account vault\n * delegations and CHOMP intents exist. The Subscription API validates those\n * delegations and the Money Account balance server-side. No payment\n * delegation signing, persistence, or intent mutation occurs before the\n * account is upgraded.\n *\n * @param request - Product selection and Money Account identity.\n * @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.\n */\nexport type SubscriptionDelegationServiceStartSubscriptionWithDelegationAction =\n {\n type: `SubscriptionDelegationService:startSubscriptionWithDelegation`;\n handler: SubscriptionDelegationService['startSubscriptionWithDelegation'];\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 * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\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, CHOMP verify and intent calls are\n * skipped; the returned hash is computed locally.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @param forceNew - Whether to create a replacement instead of reusing a\n * matching stored delegation.\n * @returns The delegation hash (CHOMP-verified unless skipped) and whether it\n * was created or reused.\n */\nexport type SubscriptionDelegationServicePrepareDelegationAction = {\n type: `SubscriptionDelegationService:prepareDelegation`;\n handler: SubscriptionDelegationService['prepareDelegation'];\n};\n\n/**\n * Union of all SubscriptionDelegationService action types.\n */\nexport type SubscriptionDelegationServiceMethodActions =\n | SubscriptionDelegationServiceCheckMoneyAccountBalanceAction\n | SubscriptionDelegationServiceStartSubscriptionWithDelegationAction\n | SubscriptionDelegationServicePrepareDelegationAction;\n"]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { ApprovalControllerAddRequestAction } from '@metamask/approval-controller';
|
|
2
1
|
import type { AuthenticatedUserStorageServiceCreateDelegationAction, AuthenticatedUserStorageServiceListDelegationsAction } from '@metamask/authenticated-user-storage';
|
|
3
2
|
import type { ChompApiServiceCreateIntentsAction, ChompApiServiceGetIntentsByAddressAction, ChompApiServiceVerifyDelegationAction } from '@metamask/chomp-api-service';
|
|
4
3
|
import type { DelegationControllerSignDelegationAction } from '@metamask/delegation-controller';
|
|
@@ -22,7 +21,7 @@ export type SubscriptionDelegationServiceActions = SubscriptionDelegationService
|
|
|
22
21
|
/**
|
|
23
22
|
* Actions from other messengers that {@link SubscriptionDelegationServiceMessenger} calls.
|
|
24
23
|
*/
|
|
25
|
-
type AllowedActions = AuthenticatedUserStorageServiceListDelegationsAction | AuthenticatedUserStorageServiceCreateDelegationAction | ChompApiServiceVerifyDelegationAction | ChompApiServiceCreateIntentsAction | ChompApiServiceGetIntentsByAddressAction | DelegationControllerSignDelegationAction |
|
|
24
|
+
type AllowedActions = AuthenticatedUserStorageServiceListDelegationsAction | AuthenticatedUserStorageServiceCreateDelegationAction | ChompApiServiceVerifyDelegationAction | ChompApiServiceCreateIntentsAction | ChompApiServiceGetIntentsByAddressAction | DelegationControllerSignDelegationAction | MoneyAccountUpgradeControllerForceUpgradeAccountAction | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction | RemoteFeatureFlagControllerGetStateAction | SubscriptionControllerGetStateAction | SubscriptionControllerGetPricingAction | SubscriptionControllerGetSubscriptionsAction | SubscriptionControllerStartSubscriptionWithCryptoAction;
|
|
26
25
|
/**
|
|
27
26
|
* Events that {@link SubscriptionDelegationService} exposes to other consumers.
|
|
28
27
|
*/
|
|
@@ -72,22 +71,17 @@ export declare class SubscriptionDelegationService {
|
|
|
72
71
|
* Runs the complete Money Account subscription checkout authorization flow.
|
|
73
72
|
*
|
|
74
73
|
* Subscriptions are refreshed first. An active subscription for the product
|
|
75
|
-
* is rejected before Money Account upgrade,
|
|
76
|
-
*
|
|
74
|
+
* is rejected before Money Account upgrade, delegation signing, persistence,
|
|
75
|
+
* or CHOMP registration.
|
|
77
76
|
*
|
|
78
|
-
*
|
|
79
|
-
* the Money Account vault
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
* delegation signing, persistence, or intent mutation occurs before
|
|
83
|
-
*
|
|
77
|
+
* The caller must obtain user consent and initiate funding before calling.
|
|
78
|
+
* `MoneyAccountUpgradeController` ensures the Money Account vault
|
|
79
|
+
* delegations and CHOMP intents exist. The Subscription API validates those
|
|
80
|
+
* delegations and the Money Account balance server-side. No payment
|
|
81
|
+
* delegation signing, persistence, or intent mutation occurs before the
|
|
82
|
+
* account is upgraded.
|
|
84
83
|
*
|
|
85
|
-
*
|
|
86
|
-
* result validation are skipped and the flow proceeds directly to signing.
|
|
87
|
-
* The caller is then responsible for consent and funding.
|
|
88
|
-
*
|
|
89
|
-
* @param request - Product selection, Money Account identity, and optional
|
|
90
|
-
* `skipApproval` flag.
|
|
84
|
+
* @param request - Product selection and Money Account identity.
|
|
91
85
|
* @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.
|
|
92
86
|
*/
|
|
93
87
|
startSubscriptionWithDelegation(request: StartSubscriptionWithDelegationRequest): Promise<StartSubscriptionWithDelegationResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,qDAAqD,EACrD,oDAAoD,EACrD,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EACV,kCAAkC,EAClC,wCAAwC,EACxC,qCAAqC,EACtC,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,wC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jD,SAAS,EAAE,sCAAsC,CAAC;CACnD,CAAC;AAqBF;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,6BAA6B;;IACxC,QAAQ,CAAC,IAAI,EAAE,OAAO,WAAW,CAAe;IAIhD,YAAY,OAAO,EAAE,oCAAoC,EAOxD;IAED;;;;;;OAMG;IACG,wBAAwB,CAC5B,OAAO,EAAE,+BAA+B,GACvC,OAAO,CAAC,8BAA8B,CAAC,CAMzC;IA+BD;;;;;;;;;;;;;;;;OAgBG;IACG,+BAA+B,CACnC,OAAO,EAAE,sCAAsC,GAC9C,OAAO,CAAC,qCAAqC,CAAC,CA+DhD;IA2PD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,iBAAiB,CACrB,OAAO,EAAE,oCAAoC,EAC7C,QAAQ,UAAQ,GACf,OAAO,CAAC,8BAA8B,CAAC,CAoKzC;CAiJF"}
|
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import { ORIGIN_METAMASK } from '@metamask/controller-utils';
|
|
2
1
|
import { hashDelegation } from '@metamask/delegation-core';
|
|
3
2
|
import { DELEGATOR_CONTRACTS } from '@metamask/delegation-deployments';
|
|
4
|
-
import {
|
|
5
|
-
import { add0x, hexToNumber
|
|
3
|
+
import { getMoneyAccountVaultConfig, MUSD_DECIMALS, } from '@metamask/money-account-utils';
|
|
4
|
+
import { add0x, hexToNumber } from '@metamask/utils';
|
|
6
5
|
import { ACTIVE_SUBSCRIPTION_STATUSES, SubscriptionControllerErrorMessage, SubscriptionDelegationServiceErrorMessage, } from '../constants.js';
|
|
7
6
|
import { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';
|
|
8
7
|
import { assertPositiveInteger, calculatePeriodAmount, getDelegationStartDate, getPeriodDuration, } from './amount.js';
|
|
9
8
|
import { buildUnsignedSubscriptionDelegation } from './caveats.js';
|
|
10
9
|
import { equalsIgnoreCase, makeMatchesSubscriptionDelegation, pickLatestMatchingSubscriptionDelegation, } from './fingerprint.js';
|
|
11
10
|
import { buildDelegationTypedData, decodeSubscriptionAuthority, } from './typed-data.js';
|
|
12
|
-
import { CASH_SUBSCRIPTION_DELEGATION_TYPE
|
|
11
|
+
import { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';
|
|
13
12
|
/**
|
|
14
13
|
* The name of the {@link SubscriptionDelegationService}, used to namespace the
|
|
15
14
|
* service's actions and events.
|
|
@@ -90,22 +89,17 @@ export class SubscriptionDelegationService {
|
|
|
90
89
|
* Runs the complete Money Account subscription checkout authorization flow.
|
|
91
90
|
*
|
|
92
91
|
* Subscriptions are refreshed first. An active subscription for the product
|
|
93
|
-
* is rejected before Money Account upgrade,
|
|
94
|
-
*
|
|
92
|
+
* is rejected before Money Account upgrade, delegation signing, persistence,
|
|
93
|
+
* or CHOMP registration.
|
|
95
94
|
*
|
|
96
|
-
*
|
|
97
|
-
* the Money Account vault
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
* delegation signing, persistence, or intent mutation occurs before
|
|
101
|
-
*
|
|
95
|
+
* The caller must obtain user consent and initiate funding before calling.
|
|
96
|
+
* `MoneyAccountUpgradeController` ensures the Money Account vault
|
|
97
|
+
* delegations and CHOMP intents exist. The Subscription API validates those
|
|
98
|
+
* delegations and the Money Account balance server-side. No payment
|
|
99
|
+
* delegation signing, persistence, or intent mutation occurs before the
|
|
100
|
+
* account is upgraded.
|
|
102
101
|
*
|
|
103
|
-
*
|
|
104
|
-
* result validation are skipped and the flow proceeds directly to signing.
|
|
105
|
-
* The caller is then responsible for consent and funding.
|
|
106
|
-
*
|
|
107
|
-
* @param request - Product selection, Money Account identity, and optional
|
|
108
|
-
* `skipApproval` flag.
|
|
102
|
+
* @param request - Product selection and Money Account identity.
|
|
109
103
|
* @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.
|
|
110
104
|
*/
|
|
111
105
|
async startSubscriptionWithDelegation(request) {
|
|
@@ -123,53 +117,28 @@ export class SubscriptionDelegationService {
|
|
|
123
117
|
!trialedProducts.includes(request.product);
|
|
124
118
|
await this.#messenger.call('MoneyAccountUpgradeController:forceUpgradeAccount', request.payerAddress);
|
|
125
119
|
const paymentPermission = await this.#preparePaymentPermission(request, config, isTrialRequested);
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
120
|
+
const paymentDelegation = await this.#signPaymentPermissionIfRequired(paymentPermission, config);
|
|
121
|
+
const paymentDelegationHash = await this.#commitPaymentPermission({
|
|
122
|
+
request,
|
|
123
|
+
paymentPermission,
|
|
124
|
+
paymentDelegation,
|
|
125
|
+
config,
|
|
126
|
+
});
|
|
127
|
+
return await this.#messenger.call('SubscriptionController:startSubscriptionWithCrypto', {
|
|
128
|
+
products: [request.product],
|
|
129
|
+
isTrialRequested,
|
|
130
|
+
recurringInterval: request.recurringInterval,
|
|
131
|
+
billingCycles: config.price.minBillingCycles,
|
|
129
132
|
chainId: request.chainId,
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
});
|
|
140
|
-
try {
|
|
141
|
-
if (approval) {
|
|
142
|
-
this.#validateApprovalResult(approval);
|
|
143
|
-
}
|
|
144
|
-
const paymentDelegation = await this.#signPaymentPermissionIfRequired(paymentPermission, config);
|
|
145
|
-
const paymentDelegationHash = await this.#commitPaymentPermission({
|
|
146
|
-
request,
|
|
147
|
-
paymentPermission,
|
|
148
|
-
paymentDelegation,
|
|
149
|
-
config,
|
|
150
|
-
});
|
|
151
|
-
const result = await this.#messenger.call('SubscriptionController:startSubscriptionWithCrypto', {
|
|
152
|
-
products: [request.product],
|
|
153
|
-
isTrialRequested,
|
|
154
|
-
recurringInterval: request.recurringInterval,
|
|
155
|
-
billingCycles: config.price.minBillingCycles,
|
|
156
|
-
chainId: request.chainId,
|
|
157
|
-
payerAddress: request.payerAddress,
|
|
158
|
-
tokenSymbol: config.token.symbol,
|
|
159
|
-
cryptoAuthMethod: CRYPTO_AUTH_METHODS.DELEGATION,
|
|
160
|
-
delegationHash: paymentDelegationHash,
|
|
161
|
-
// Reject if eligibility changed during approval, because the signed
|
|
162
|
-
// delegation start date was derived from the original trial state.
|
|
163
|
-
// This local guard is removed before the backend request.
|
|
164
|
-
assertTrialEligibility: true,
|
|
165
|
-
});
|
|
166
|
-
approval?.resultCallbacks?.success();
|
|
167
|
-
return result;
|
|
168
|
-
}
|
|
169
|
-
catch (error) {
|
|
170
|
-
approval?.resultCallbacks?.error(error);
|
|
171
|
-
throw error;
|
|
172
|
-
}
|
|
133
|
+
payerAddress: request.payerAddress,
|
|
134
|
+
tokenSymbol: config.token.symbol,
|
|
135
|
+
cryptoAuthMethod: CRYPTO_AUTH_METHODS.DELEGATION,
|
|
136
|
+
delegationHash: paymentDelegationHash,
|
|
137
|
+
// Reject if eligibility changed during checkout, because the signed
|
|
138
|
+
// delegation start date was derived from the original trial state.
|
|
139
|
+
// This local guard is removed before the backend request.
|
|
140
|
+
assertTrialEligibility: true,
|
|
141
|
+
});
|
|
173
142
|
}
|
|
174
143
|
/**
|
|
175
144
|
* Rejects when the refreshed list already contains an active subscription
|
|
@@ -185,31 +154,6 @@ export class SubscriptionDelegationService {
|
|
|
185
154
|
throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);
|
|
186
155
|
}
|
|
187
156
|
}
|
|
188
|
-
async #requestApproval({ request, price, musdAddress, bundle, }) {
|
|
189
|
-
const targetAmount = calculatePeriodAmount({
|
|
190
|
-
unitAmount: price.unitAmount,
|
|
191
|
-
unitDecimals: price.unitDecimals,
|
|
192
|
-
tokenDecimals: MUSD_DECIMALS,
|
|
193
|
-
}) * BigInt(price.minBillingCyclesForBalance);
|
|
194
|
-
return (await this.#messenger.call('ApprovalController:addRequest', {
|
|
195
|
-
origin: ORIGIN_METAMASK,
|
|
196
|
-
type: SUBSCRIPTION_DELEGATION_APPROVAL_TYPE,
|
|
197
|
-
expectsResult: true,
|
|
198
|
-
requestData: {
|
|
199
|
-
bundle,
|
|
200
|
-
funding: {
|
|
201
|
-
useCase: 'subscription',
|
|
202
|
-
destinationAccount: request.payerAddress,
|
|
203
|
-
chainId: request.chainId,
|
|
204
|
-
targetToken: {
|
|
205
|
-
symbol: 'mUSD',
|
|
206
|
-
address: musdAddress,
|
|
207
|
-
},
|
|
208
|
-
targetAmount: targetAmount.toString(),
|
|
209
|
-
},
|
|
210
|
-
},
|
|
211
|
-
}, true));
|
|
212
|
-
}
|
|
213
157
|
async #preparePaymentPermission(request, config, isTrialRequested) {
|
|
214
158
|
const periodAmount = calculatePeriodAmount({
|
|
215
159
|
unitAmount: config.price.unitAmount,
|
|
@@ -266,20 +210,6 @@ export class SubscriptionDelegationService {
|
|
|
266
210
|
: {}),
|
|
267
211
|
};
|
|
268
212
|
}
|
|
269
|
-
#validateApprovalResult(approval) {
|
|
270
|
-
if (!approval?.value || typeof approval.value !== 'object') {
|
|
271
|
-
throw new Error(SubscriptionDelegationServiceErrorMessage.ApprovalResultMissing);
|
|
272
|
-
}
|
|
273
|
-
const value = approval.value;
|
|
274
|
-
if (typeof value.fundingTransactionHash !== 'string' ||
|
|
275
|
-
!isStrictHexString(value.fundingTransactionHash) ||
|
|
276
|
-
value.fundingTransactionHash.length !== 66) {
|
|
277
|
-
throw new Error(SubscriptionDelegationServiceErrorMessage.InvalidFundingTransactionHash);
|
|
278
|
-
}
|
|
279
|
-
return {
|
|
280
|
-
fundingTransactionHash: value.fundingTransactionHash,
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
213
|
async #signPaymentPermissionIfRequired(permission, config) {
|
|
284
214
|
if (permission.disposition === 'reused') {
|
|
285
215
|
return undefined;
|
|
@@ -544,7 +474,6 @@ export class SubscriptionDelegationService {
|
|
|
544
474
|
.DelegationManager,
|
|
545
475
|
paymentAddress: chain.paymentAddress,
|
|
546
476
|
enforcers,
|
|
547
|
-
musdAddress: getMoneyAccountDepositAssetAddress(chainId),
|
|
548
477
|
price,
|
|
549
478
|
token,
|
|
550
479
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionDelegationService.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAE7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAIvE,OAAO,EACL,kCAAkC,EAClC,0BAA0B,EAC1B,aAAa,GACd,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGxE,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,yCAAyC,GAC1C,MAAM,iBAAiB,CAAC;AAOzB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAShF,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,EACjC,wCAAwC,GACzC,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AAezB,OAAO,EACL,iCAAiC,EACjC,qCAAqC,EACrC,sCAAsC,GACvC,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,+BAA+B,CAAC;AAE3D,MAAM,yBAAyB,GAAG;IAChC,mBAAmB;IACnB,0BAA0B;IAC1B,iCAAiC;CACzB,CAAC;AAEX,MAAM,4BAA4B,GAAG,OAAO,CAAC;AAE7C,SAAS,gBAAgB,CAAC,OAAY;IACpC,MAAM,SAAS,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AAM,eAAe,GAAG,eAAe,CAAC,IAAI,CAC1C,CAAC,MAAM,EAAE,EAAE,CACT,gBAAgB,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,cAAc,CAAC;YAC9D,MAAM,CAAC,MAAM,KAAK,QAAQ,CAC7B,CAAC;QAEF,IAAI,eAAe,EAAE,CAAC;YACpB,OAAO;QACT,CAAC;QAED,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAgC;QAClD,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,iCAAiC;iBACxC;aACF;SACF,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AddResult,\n ApprovalControllerAddRequestAction,\n} from '@metamask/approval-controller';\nimport type {\n DelegationResponse,\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 { ORIGIN_METAMASK } from '@metamask/controller-utils';\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 type { MoneyAccountUpgradeControllerForceUpgradeAccountAction } from '@metamask/money-account-upgrade-controller';\nimport {\n getMoneyAccountDepositAssetAddress,\n getMoneyAccountVaultConfig,\n MUSD_DECIMALS,\n} from '@metamask/money-account-utils';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport { add0x, hexToNumber, isStrictHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n ACTIVE_SUBSCRIPTION_STATUSES,\n SubscriptionControllerErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from '../constants.js';\nimport type {\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n} from '../SubscriptionController-method-action-types.js';\nimport type { SubscriptionControllerGetStateAction } from '../SubscriptionController.js';\nimport { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';\nimport type {\n ProductPrice,\n ProductType,\n PricingCryptoPaymentMethod,\n RecurringInterval,\n Subscription,\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 pickLatestMatchingSubscriptionDelegation,\n} from './fingerprint.js';\nimport type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';\nimport {\n buildDelegationTypedData,\n decodeSubscriptionAuthority,\n} from './typed-data.js';\nimport type {\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PreparedSubscriptionDelegationBundle,\n PreparedSubscriptionPermission,\n PreparedSubscriptionDelegation,\n SignedSubscriptionDelegation,\n StartSubscriptionWithDelegationRequest,\n StartSubscriptionWithDelegationResult,\n SubscriptionDelegationApprovalResult,\n SubscriptionDelegationEnforcers,\n UnsignedSubscriptionDelegation,\n} from './types.js';\nimport {\n CASH_SUBSCRIPTION_DELEGATION_TYPE,\n SUBSCRIPTION_DELEGATION_APPROVAL_TYPE,\n SUBSCRIPTION_DELEGATION_POLICY_VERSION,\n} 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 'startSubscriptionWithDelegation',\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?.ERC20PeriodTransferEnforcer ||\n !contracts.AllowedCalldataEnforcer\n ) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.DelegationContractsNotFound}: ${chainId}`,\n );\n }\n\n return {\n erc20TokenPeriodTransfer: contracts.ERC20PeriodTransferEnforcer,\n allowedCalldata: contracts.AllowedCalldataEnforcer,\n };\n}\n\nfunction removeDelegationSignature(\n delegation: SignedSubscriptionDelegation,\n): UnsignedSubscriptionDelegation {\n const { signature: _signature, ...unsignedDelegation } = delegation;\n return unsignedDelegation;\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 | ApprovalControllerAddRequestAction\n | MoneyAccountUpgradeControllerForceUpgradeAccountAction\n | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction\n | RemoteFeatureFlagControllerGetStateAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction;\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 delegationManager: Hex;\n paymentAddress: Hex;\n enforcers: SubscriptionDelegationEnforcers;\n musdAddress: Hex;\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 * Pass `skipChompInteractions: true` to skip CHOMP verify and intent\n * registration and return a locally computed delegation hash.\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 the delegation `delegate`.\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 * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade, approval, delegation signing,\n * persistence, or CHOMP registration.\n *\n * Before the approval, `MoneyAccountUpgradeController` is asked to ensure\n * the Money Account vault delegations and CHOMP intents exist; the\n * Subscription API validates them server-side. The custom approval is the\n * sole consent and funding boundary for the payment permission. No payment\n * delegation signing, persistence, or intent mutation occurs before it\n * returns a funding transaction hash.\n *\n * When `request.skipApproval` is `true`, the approval request and its\n * result validation are skipped and the flow proceeds directly to signing.\n * The caller is then responsible for consent and funding.\n *\n * @param request - Product selection, Money Account identity, and optional\n * `skipApproval` flag.\n * @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.\n */\n async startSubscriptionWithDelegation(\n request: StartSubscriptionWithDelegationRequest,\n ): Promise<StartSubscriptionWithDelegationResult> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const config = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n if (!equalsIgnoreCase(request.chainId, config.chainId)) {\n throw new Error(SubscriptionDelegationServiceErrorMessage.ChainMismatch);\n }\n const subscriptions = await this.#messenger.call(\n 'SubscriptionController:getSubscriptions',\n );\n this.#assertUserNotSubscribed(subscriptions, request.product);\n const { trialedProducts } = this.#messenger.call(\n 'SubscriptionController:getState',\n );\n const isTrialRequested =\n config.price.trialPeriodDays > 0 &&\n !trialedProducts.includes(request.product);\n\n await this.#messenger.call(\n 'MoneyAccountUpgradeController:forceUpgradeAccount',\n request.payerAddress,\n );\n\n const paymentPermission = await this.#preparePaymentPermission(\n request,\n config,\n isTrialRequested,\n );\n const bundle: PreparedSubscriptionDelegationBundle = {\n policyVersion: SUBSCRIPTION_DELEGATION_POLICY_VERSION,\n account: request.payerAddress,\n chainId: request.chainId,\n permissions: [paymentPermission],\n };\n const approval = request.skipApproval\n ? undefined\n : await this.#requestApproval({\n request,\n price: config.price,\n musdAddress: config.musdAddress,\n bundle,\n });\n\n try {\n if (approval) {\n this.#validateApprovalResult(approval);\n }\n\n const paymentDelegation = await this.#signPaymentPermissionIfRequired(\n paymentPermission,\n config,\n );\n const paymentDelegationHash = await this.#commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n });\n const result = await this.#messenger.call(\n 'SubscriptionController:startSubscriptionWithCrypto',\n {\n products: [request.product],\n isTrialRequested,\n recurringInterval: request.recurringInterval,\n billingCycles: config.price.minBillingCycles,\n chainId: request.chainId,\n payerAddress: request.payerAddress,\n tokenSymbol: config.token.symbol,\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.DELEGATION,\n delegationHash: paymentDelegationHash,\n // Reject if eligibility changed during approval, because the signed\n // delegation start date was derived from the original trial state.\n // This local guard is removed before the backend request.\n assertTrialEligibility: true,\n },\n );\n approval?.resultCallbacks?.success();\n return result;\n } catch (error) {\n approval?.resultCallbacks?.error(error as Error);\n throw error;\n }\n }\n\n /**\n * Rejects when the refreshed list already contains an active subscription\n * for the product. Active includes `active`, `trialing`, and `provisional`.\n *\n * @param subscriptions - Subscriptions returned by the latest refresh.\n * @param product - Product the caller is trying to start.\n */\n #assertUserNotSubscribed(\n subscriptions: Subscription[],\n product: ProductType,\n ): void {\n const alreadySubscribed = subscriptions.some(\n (subscription) =>\n ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status) &&\n subscription.products.some((entry) => entry.name === product),\n );\n if (alreadySubscribed) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n async #requestApproval({\n request,\n price,\n musdAddress,\n bundle,\n }: {\n request: StartSubscriptionWithDelegationRequest;\n price: ProductPrice;\n musdAddress: Hex;\n bundle: PreparedSubscriptionDelegationBundle;\n }): Promise<AddResult> {\n const targetAmount =\n calculatePeriodAmount({\n unitAmount: price.unitAmount,\n unitDecimals: price.unitDecimals,\n tokenDecimals: MUSD_DECIMALS,\n }) * BigInt(price.minBillingCyclesForBalance);\n\n return (await this.#messenger.call(\n 'ApprovalController:addRequest',\n {\n origin: ORIGIN_METAMASK,\n type: SUBSCRIPTION_DELEGATION_APPROVAL_TYPE,\n expectsResult: true,\n requestData: {\n bundle,\n funding: {\n useCase: 'subscription',\n destinationAccount: request.payerAddress,\n chainId: request.chainId,\n targetToken: {\n symbol: 'mUSD',\n address: musdAddress,\n },\n targetAmount: targetAmount.toString(),\n },\n },\n },\n true,\n )) as AddResult;\n }\n\n async #preparePaymentPermission(\n request: StartSubscriptionWithDelegationRequest,\n config: ResolvedSubscriptionDelegationConfig,\n isTrialRequested: boolean,\n ): Promise<PreparedSubscriptionPermission> {\n const periodAmount = calculatePeriodAmount({\n unitAmount: config.price.unitAmount,\n unitDecimals: config.price.unitDecimals,\n tokenDecimals: config.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: isTrialRequested\n ? config.price.trialPeriodDays\n : undefined,\n });\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress: config.delegateAddress,\n chainId: request.chainId,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred: startDate > nowSeconds,\n enforcers: config.enforcers,\n });\n const reusable = pickLatestMatchingSubscriptionDelegation(\n (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).filter(matches),\n config.enforcers,\n );\n const delegation = reusable\n ? removeDelegationSignature(reusable.signedDelegation)\n : buildUnsignedSubscriptionDelegation({\n delegateAddress: config.delegateAddress,\n delegatorAddress: request.payerAddress,\n enforcers: config.enforcers,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n const typedData = buildDelegationTypedData({\n delegation,\n chainId: request.chainId,\n delegationManager: config.delegationManager,\n });\n\n return {\n id: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n owner: 'subscription',\n disposition: reusable ? 'reused' : 'new',\n delegation,\n typedData,\n decodedAuthority: decodeSubscriptionAuthority(\n delegation,\n config.enforcers,\n ),\n ...(reusable\n ? { existingDelegationHash: reusable.metadata.delegationHash }\n : {}),\n };\n }\n\n #validateApprovalResult(\n approval: AddResult,\n ): SubscriptionDelegationApprovalResult {\n if (!approval?.value || typeof approval.value !== 'object') {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ApprovalResultMissing,\n );\n }\n const value = approval.value as Record<string, unknown>;\n if (\n typeof value.fundingTransactionHash !== 'string' ||\n !isStrictHexString(value.fundingTransactionHash) ||\n value.fundingTransactionHash.length !== 66\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.InvalidFundingTransactionHash,\n );\n }\n return {\n fundingTransactionHash: value.fundingTransactionHash,\n };\n }\n\n async #signPaymentPermissionIfRequired(\n permission: PreparedSubscriptionPermission,\n config: ResolvedSubscriptionDelegationConfig,\n ): Promise<SignedSubscriptionDelegation | undefined> {\n if (permission.disposition === 'reused') {\n return undefined;\n }\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n {\n delegation: permission.delegation,\n chainId: config.chainId,\n },\n )) as Hex;\n return { ...permission.delegation, signature };\n }\n\n async #commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n }: {\n request: StartSubscriptionWithDelegationRequest;\n paymentPermission: PreparedSubscriptionPermission;\n paymentDelegation?: SignedSubscriptionDelegation;\n config: ResolvedSubscriptionDelegationConfig;\n }): Promise<Hex> {\n if (paymentPermission.disposition === 'reused') {\n const delegationHash = paymentPermission.existingDelegationHash as Hex;\n const storedDelegation = (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).find(({ metadata }) =>\n equalsIgnoreCase(metadata.delegationHash, delegationHash),\n );\n if (!storedDelegation) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n await this.#verifySignedPaymentDelegation(\n storedDelegation.signedDelegation,\n delegationHash,\n request.chainId,\n );\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance: add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n ),\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n const signedDelegation = paymentDelegation as SignedSubscriptionDelegation;\n const delegationHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n await this.#verifySignedPaymentDelegation(\n signedDelegation,\n delegationHash,\n request.chainId,\n );\n\n const allowance = add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n );\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: request.chainId,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n await this.#createIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n async #assertIntentActive(account: Hex, delegationHash: Hex): Promise<void> {\n const intents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n account,\n );\n const intent = intents.find((candidate) =>\n equalsIgnoreCase(candidate.delegationHash, delegationHash),\n );\n if (intent?.status !== 'active') {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompIntentNotActive,\n );\n }\n }\n\n async #verifySignedPaymentDelegation(\n signedDelegation: SignedSubscriptionDelegation,\n expectedDelegationHash: Hex,\n chainId: Hex,\n ): Promise<void> {\n const localHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n if (!equalsIgnoreCase(localHash, expectedDelegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n { signedDelegation, chainId },\n );\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (\n !equalsIgnoreCase(verifyResult.delegationHash, expectedDelegationHash)\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\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 * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\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, CHOMP verify and intent calls are\n * skipped; the returned hash is computed locally.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @param forceNew - Whether to create a replacement instead of reusing a\n * matching stored 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 forceNew = false,\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 {\n chainId,\n delegateAddress,\n paymentAddress,\n enforcers,\n price,\n 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 reusable = forceNew\n ? undefined\n : await this.#findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\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 recipientAddress: paymentAddress,\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 #findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n }: {\n request: PrepareSubscriptionDelegationRequest;\n chainId: Hex;\n delegateAddress: Hex;\n paymentAddress: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n nowSeconds: number;\n isTrialDeferred: boolean;\n enforcers: SubscriptionDelegationEnforcers;\n }): Promise<DelegationResponse | undefined> {\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress,\n recipientAddress: paymentAddress,\n chainId,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n\n const existingDelegations = await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n );\n\n return pickLatestMatchingSubscriptionDelegation(\n existingDelegations.filter(matches),\n enforcers,\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 delegationManager:\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION][hexToNumber(chainId)]\n .DelegationManager,\n paymentAddress: chain.paymentAddress,\n enforcers,\n musdAddress: getMoneyAccountDepositAssetAddress(chainId),\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 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,\n },\n },\n ]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionDelegationService.js","sourceRoot":"","sources":["../../src/subscription-delegation/SubscriptionDelegationService.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAIvE,OAAO,EACL,0BAA0B,EAC1B,aAAa,GACd,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGrD,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,yCAAyC,GAC1C,MAAM,iBAAiB,CAAC;AAOzB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAShF,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,EACjC,wCAAwC,GACzC,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AAazB,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;IA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\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 type { MoneyAccountUpgradeControllerForceUpgradeAccountAction } from '@metamask/money-account-upgrade-controller';\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 {\n ACTIVE_SUBSCRIPTION_STATUSES,\n SubscriptionControllerErrorMessage,\n SubscriptionDelegationServiceErrorMessage,\n} from '../constants.js';\nimport type {\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n} from '../SubscriptionController-method-action-types.js';\nimport type { SubscriptionControllerGetStateAction } from '../SubscriptionController.js';\nimport { CRYPTO_AUTH_METHODS, PAYMENT_TYPES, PRODUCT_TYPES } from '../types.js';\nimport type {\n ProductPrice,\n ProductType,\n PricingCryptoPaymentMethod,\n RecurringInterval,\n Subscription,\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 pickLatestMatchingSubscriptionDelegation,\n} from './fingerprint.js';\nimport type { SubscriptionDelegationServiceMethodActions } from './SubscriptionDelegationService-method-action-types.js';\nimport {\n buildDelegationTypedData,\n decodeSubscriptionAuthority,\n} from './typed-data.js';\nimport type {\n MoneyAccountBalanceCheckRequest,\n MoneyAccountBalanceCheckResult,\n PrepareSubscriptionDelegationRequest,\n PreparedSubscriptionPermission,\n PreparedSubscriptionDelegation,\n SignedSubscriptionDelegation,\n StartSubscriptionWithDelegationRequest,\n StartSubscriptionWithDelegationResult,\n SubscriptionDelegationEnforcers,\n UnsignedSubscriptionDelegation,\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 'startSubscriptionWithDelegation',\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?.ERC20PeriodTransferEnforcer ||\n !contracts.AllowedCalldataEnforcer\n ) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.DelegationContractsNotFound}: ${chainId}`,\n );\n }\n\n return {\n erc20TokenPeriodTransfer: contracts.ERC20PeriodTransferEnforcer,\n allowedCalldata: contracts.AllowedCalldataEnforcer,\n };\n}\n\nfunction removeDelegationSignature(\n delegation: SignedSubscriptionDelegation,\n): UnsignedSubscriptionDelegation {\n const { signature: _signature, ...unsignedDelegation } = delegation;\n return unsignedDelegation;\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 | MoneyAccountUpgradeControllerForceUpgradeAccountAction\n | MoneyAccountBalanceServiceFetchBalanceWithFallbackAction\n | RemoteFeatureFlagControllerGetStateAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction;\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 delegationManager: Hex;\n paymentAddress: 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 * Pass `skipChompInteractions: true` to skip CHOMP verify and intent\n * registration and return a locally computed delegation hash.\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 the delegation `delegate`.\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 * Runs the complete Money Account subscription checkout authorization flow.\n *\n * Subscriptions are refreshed first. An active subscription for the product\n * is rejected before Money Account upgrade, delegation signing, persistence,\n * or CHOMP registration.\n *\n * The caller must obtain user consent and initiate funding before calling.\n * `MoneyAccountUpgradeController` ensures the Money Account vault\n * delegations and CHOMP intents exist. The Subscription API validates those\n * delegations and the Money Account balance server-side. No payment\n * delegation signing, persistence, or intent mutation occurs before the\n * account is upgraded.\n *\n * @param request - Product selection and Money Account identity.\n * @returns The result from `SubscriptionController:startSubscriptionWithCrypto`.\n */\n async startSubscriptionWithDelegation(\n request: StartSubscriptionWithDelegationRequest,\n ): Promise<StartSubscriptionWithDelegationResult> {\n if (request.product !== PRODUCT_TYPES.MONEY_ACCOUNT_PLUS) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedProduct,\n );\n }\n\n const config = await this.#resolveConfiguration(\n request.product,\n request.recurringInterval,\n );\n if (!equalsIgnoreCase(request.chainId, config.chainId)) {\n throw new Error(SubscriptionDelegationServiceErrorMessage.ChainMismatch);\n }\n const subscriptions = await this.#messenger.call(\n 'SubscriptionController:getSubscriptions',\n );\n this.#assertUserNotSubscribed(subscriptions, request.product);\n const { trialedProducts } = this.#messenger.call(\n 'SubscriptionController:getState',\n );\n const isTrialRequested =\n config.price.trialPeriodDays > 0 &&\n !trialedProducts.includes(request.product);\n\n await this.#messenger.call(\n 'MoneyAccountUpgradeController:forceUpgradeAccount',\n request.payerAddress,\n );\n\n const paymentPermission = await this.#preparePaymentPermission(\n request,\n config,\n isTrialRequested,\n );\n const paymentDelegation = await this.#signPaymentPermissionIfRequired(\n paymentPermission,\n config,\n );\n const paymentDelegationHash = await this.#commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n });\n return await this.#messenger.call(\n 'SubscriptionController:startSubscriptionWithCrypto',\n {\n products: [request.product],\n isTrialRequested,\n recurringInterval: request.recurringInterval,\n billingCycles: config.price.minBillingCycles,\n chainId: request.chainId,\n payerAddress: request.payerAddress,\n tokenSymbol: config.token.symbol,\n cryptoAuthMethod: CRYPTO_AUTH_METHODS.DELEGATION,\n delegationHash: paymentDelegationHash,\n // Reject if eligibility changed during checkout, because the signed\n // delegation start date was derived from the original trial state.\n // This local guard is removed before the backend request.\n assertTrialEligibility: true,\n },\n );\n }\n\n /**\n * Rejects when the refreshed list already contains an active subscription\n * for the product. Active includes `active`, `trialing`, and `provisional`.\n *\n * @param subscriptions - Subscriptions returned by the latest refresh.\n * @param product - Product the caller is trying to start.\n */\n #assertUserNotSubscribed(\n subscriptions: Subscription[],\n product: ProductType,\n ): void {\n const alreadySubscribed = subscriptions.some(\n (subscription) =>\n ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status) &&\n subscription.products.some((entry) => entry.name === product),\n );\n if (alreadySubscribed) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n async #preparePaymentPermission(\n request: StartSubscriptionWithDelegationRequest,\n config: ResolvedSubscriptionDelegationConfig,\n isTrialRequested: boolean,\n ): Promise<PreparedSubscriptionPermission> {\n const periodAmount = calculatePeriodAmount({\n unitAmount: config.price.unitAmount,\n unitDecimals: config.price.unitDecimals,\n tokenDecimals: config.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: isTrialRequested\n ? config.price.trialPeriodDays\n : undefined,\n });\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress: config.delegateAddress,\n chainId: request.chainId,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred: startDate > nowSeconds,\n enforcers: config.enforcers,\n });\n const reusable = pickLatestMatchingSubscriptionDelegation(\n (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).filter(matches),\n config.enforcers,\n );\n const delegation = reusable\n ? removeDelegationSignature(reusable.signedDelegation)\n : buildUnsignedSubscriptionDelegation({\n delegateAddress: config.delegateAddress,\n delegatorAddress: request.payerAddress,\n enforcers: config.enforcers,\n recipientAddress: config.paymentAddress,\n tokenAddress: config.token.address,\n periodAmount,\n periodDuration,\n startDate,\n });\n const typedData = buildDelegationTypedData({\n delegation,\n chainId: request.chainId,\n delegationManager: config.delegationManager,\n });\n\n return {\n id: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n owner: 'subscription',\n disposition: reusable ? 'reused' : 'new',\n delegation,\n typedData,\n decodedAuthority: decodeSubscriptionAuthority(\n delegation,\n config.enforcers,\n ),\n ...(reusable\n ? { existingDelegationHash: reusable.metadata.delegationHash }\n : {}),\n };\n }\n\n async #signPaymentPermissionIfRequired(\n permission: PreparedSubscriptionPermission,\n config: ResolvedSubscriptionDelegationConfig,\n ): Promise<SignedSubscriptionDelegation | undefined> {\n if (permission.disposition === 'reused') {\n return undefined;\n }\n const signature = (await this.#messenger.call(\n 'DelegationController:signDelegation',\n {\n delegation: permission.delegation,\n chainId: config.chainId,\n },\n )) as Hex;\n return { ...permission.delegation, signature };\n }\n\n async #commitPaymentPermission({\n request,\n paymentPermission,\n paymentDelegation,\n config,\n }: {\n request: StartSubscriptionWithDelegationRequest;\n paymentPermission: PreparedSubscriptionPermission;\n paymentDelegation?: SignedSubscriptionDelegation;\n config: ResolvedSubscriptionDelegationConfig;\n }): Promise<Hex> {\n if (paymentPermission.disposition === 'reused') {\n const delegationHash = paymentPermission.existingDelegationHash as Hex;\n const storedDelegation = (\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n )\n ).find(({ metadata }) =>\n equalsIgnoreCase(metadata.delegationHash, delegationHash),\n );\n if (!storedDelegation) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n await this.#verifySignedPaymentDelegation(\n storedDelegation.signedDelegation,\n delegationHash,\n request.chainId,\n );\n await this.#ensureIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance: add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n ),\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n const signedDelegation = paymentDelegation as SignedSubscriptionDelegation;\n const delegationHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n await this.#verifySignedPaymentDelegation(\n signedDelegation,\n delegationHash,\n request.chainId,\n );\n\n const allowance = add0x(\n BigInt(paymentPermission.decodedAuthority.periodAmount).toString(16),\n );\n await this.#messenger.call(\n 'AuthenticatedUserStorageService:createDelegation',\n {\n signedDelegation,\n metadata: {\n delegationHash,\n chainIdHex: request.chainId,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n type: CASH_SUBSCRIPTION_DELEGATION_TYPE,\n },\n },\n );\n await this.#createIntent({\n account: request.payerAddress,\n chainId: request.chainId,\n delegationHash,\n allowance,\n tokenSymbol: config.token.symbol,\n tokenAddress: config.token.address,\n });\n await this.#assertIntentActive(request.payerAddress, delegationHash);\n return delegationHash;\n }\n\n async #assertIntentActive(account: Hex, delegationHash: Hex): Promise<void> {\n const intents = await this.#messenger.call(\n 'ChompApiService:getIntentsByAddress',\n account,\n );\n const intent = intents.find((candidate) =>\n equalsIgnoreCase(candidate.delegationHash, delegationHash),\n );\n if (intent?.status !== 'active') {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompIntentNotActive,\n );\n }\n }\n\n async #verifySignedPaymentDelegation(\n signedDelegation: SignedSubscriptionDelegation,\n expectedDelegationHash: Hex,\n chainId: Hex,\n ): Promise<void> {\n const localHash = hashDelegation({\n ...signedDelegation,\n salt: BigInt(signedDelegation.salt),\n });\n if (!equalsIgnoreCase(localHash, expectedDelegationHash)) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ReusableDelegationInvalid,\n );\n }\n\n const verifyResult = await this.#messenger.call(\n 'ChompApiService:verifyDelegation',\n { signedDelegation, chainId },\n );\n if (!verifyResult.valid) {\n throw new Error(\n `${SubscriptionDelegationServiceErrorMessage.ChompRejectedDelegation}: ${\n verifyResult.errors?.join(', ') ?? 'unknown error'\n }`,\n );\n }\n if (!verifyResult.delegationHash) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompMissingDelegationHash,\n );\n }\n if (\n !equalsIgnoreCase(verifyResult.delegationHash, expectedDelegationHash)\n ) {\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.ChompDelegationHashMismatch,\n );\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 * When several records match, the latest period `startDate` is reused\n * so a `forceNew` replacement is preferred over an older equivalent\n * permission.\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, CHOMP verify and intent calls are\n * skipped; the returned hash is computed locally.\n *\n * @param request - Authoritative pricing and payer details for the delegation.\n * @param forceNew - Whether to create a replacement instead of reusing a\n * matching stored 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 forceNew = false,\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 {\n chainId,\n delegateAddress,\n paymentAddress,\n enforcers,\n price,\n 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 reusable = forceNew\n ? undefined\n : await this.#findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress: token.address,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\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 recipientAddress: paymentAddress,\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 #findReusableDelegation({\n request,\n chainId,\n delegateAddress,\n paymentAddress,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n }: {\n request: PrepareSubscriptionDelegationRequest;\n chainId: Hex;\n delegateAddress: Hex;\n paymentAddress: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n nowSeconds: number;\n isTrialDeferred: boolean;\n enforcers: SubscriptionDelegationEnforcers;\n }): Promise<DelegationResponse | undefined> {\n const matches = makeMatchesSubscriptionDelegation({\n delegatorAddress: request.payerAddress,\n delegateAddress,\n recipientAddress: paymentAddress,\n chainId,\n tokenAddress,\n periodAmount,\n periodDuration,\n nowSeconds,\n isTrialDeferred,\n enforcers,\n });\n\n const existingDelegations = await this.#messenger.call(\n 'AuthenticatedUserStorageService:listDelegations',\n );\n\n return pickLatestMatchingSubscriptionDelegation(\n existingDelegations.filter(matches),\n enforcers,\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 delegationManager:\n DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION][hexToNumber(chainId)]\n .DelegationManager,\n paymentAddress: chain.paymentAddress,\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 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,\n },\n },\n ]);\n }\n}\n"]}
|
|
@@ -9,7 +9,6 @@ export type { ChompIntentType };
|
|
|
9
9
|
* The `'cash-subscription'` member of {@link ChompIntentType}.
|
|
10
10
|
*/
|
|
11
11
|
export declare const CASH_SUBSCRIPTION_DELEGATION_TYPE: "cash-subscription";
|
|
12
|
-
export declare const SUBSCRIPTION_DELEGATION_APPROVAL_TYPE: 'subscription_delegation';
|
|
13
12
|
export declare const SUBSCRIPTION_DELEGATION_POLICY_VERSION: '1';
|
|
14
13
|
export type SubscriptionPermissionId = ChompIntentType;
|
|
15
14
|
export type MoneyAccountAuthorizationReason = 'controller-not-ready' | 'address-not-associated' | 'eip7702-not-active' | 'monitoring-list-missing' | 'configuration-changed';
|
|
@@ -64,31 +63,11 @@ export type PreparedSubscriptionDelegationBundle = {
|
|
|
64
63
|
chainId: Hex;
|
|
65
64
|
permissions: PreparedSubscriptionPermission[];
|
|
66
65
|
};
|
|
67
|
-
export type SubscriptionFundingRequest = {
|
|
68
|
-
useCase: 'subscription';
|
|
69
|
-
destinationAccount: Hex;
|
|
70
|
-
chainId: Hex;
|
|
71
|
-
targetToken: {
|
|
72
|
-
symbol: 'mUSD';
|
|
73
|
-
address: Hex;
|
|
74
|
-
};
|
|
75
|
-
targetAmount: string;
|
|
76
|
-
};
|
|
77
|
-
export type SubscriptionDelegationApprovalResult = {
|
|
78
|
-
fundingTransactionHash: Hex;
|
|
79
|
-
};
|
|
80
66
|
export type StartSubscriptionWithDelegationRequest = {
|
|
81
67
|
product: ProductType;
|
|
82
68
|
recurringInterval: RecurringInterval;
|
|
83
69
|
chainId: Hex;
|
|
84
70
|
payerAddress: Hex;
|
|
85
|
-
/**
|
|
86
|
-
* When `true`, skips the `ApprovalController:addRequest` consent and
|
|
87
|
-
* funding step and proceeds directly to signing, committing, and starting
|
|
88
|
-
* the subscription. Callers must have already obtained user consent and
|
|
89
|
-
* ensured the Money Account is funded.
|
|
90
|
-
*/
|
|
91
|
-
skipApproval?: boolean;
|
|
92
71
|
};
|
|
93
72
|
export type PrepareAuthorizationBundleResult = {
|
|
94
73
|
status: 'prepared';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAEjD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EACV,WAAW,EACX,iBAAiB,EACjB,+BAA+B,EAChC,MAAM,aAAa,CAAC;AAErB,YAAY,EAAE,eAAe,EAAE,CAAC;AAEhC;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,qBACU,CAAC;AAEzD,eAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAEjD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EACV,WAAW,EACX,iBAAiB,EACjB,+BAA+B,EAChC,MAAM,aAAa,CAAC;AAErB,YAAY,EAAE,eAAe,EAAE,CAAC;AAEhC;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,qBACU,CAAC;AAEzD,eAAO,MAAM,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OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,cAAc,EAAE,GAAG,CAAC;IACpB,WAAW,EAAE,SAAS,GAAG,QAAQ,CAAC;CACnC,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,+BAA+B,GAAG,IAAI,CAChD,oCAAoC,EACpC,SAAS,GAAG,mBAAmB,GAAG,cAAc,CACjD,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,oBAAoB,EAAE,OAAO,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG;IAC5C,wBAAwB,EAAE,GAAG,CAAC;IAC9B,eAAe,EAAE,GAAG,CAAC;CACtB,CAAC"}
|
|
@@ -4,6 +4,5 @@
|
|
|
4
4
|
* The `'cash-subscription'` member of {@link ChompIntentType}.
|
|
5
5
|
*/
|
|
6
6
|
export const CASH_SUBSCRIPTION_DELEGATION_TYPE = 'cash-subscription';
|
|
7
|
-
export const SUBSCRIPTION_DELEGATION_APPROVAL_TYPE = 'subscription_delegation';
|
|
8
7
|
export const SUBSCRIPTION_DELEGATION_POLICY_VERSION = '1';
|
|
9
8
|
//# sourceMappingURL=types.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/subscription-delegation/types.ts"],"names":[],"mappings":"AAYA;;;;GAIG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAC5C,mBAAsD,CAAC;AAEzD,MAAM,CAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/subscription-delegation/types.ts"],"names":[],"mappings":"AAYA;;;;GAIG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAC5C,mBAAsD,CAAC;AAEzD,MAAM,CAAC,MAAM,sCAAsC,GAAG,GAAY,CAAC","sourcesContent":["import type { ChompIntentType } from '@metamask/chomp-api-service';\nimport type { Hex, Json } from '@metamask/utils';\n\nimport { PRODUCT_TYPES } from '../types.js';\nimport type {\n ProductType,\n RecurringInterval,\n StartCryptoSubscriptionResponse,\n} from '../types.js';\n\nexport type { ChompIntentType };\n\n/**\n * Storage / CHOMP metadata type for cash-subscription delegations.\n *\n * The `'cash-subscription'` member of {@link ChompIntentType}.\n */\nexport const CASH_SUBSCRIPTION_DELEGATION_TYPE =\n 'cash-subscription' as const satisfies ChompIntentType;\n\nexport const SUBSCRIPTION_DELEGATION_POLICY_VERSION = '1' as const;\n\nexport type SubscriptionPermissionId = ChompIntentType;\n\nexport type MoneyAccountAuthorizationReason =\n | 'controller-not-ready'\n | 'address-not-associated'\n | 'eip7702-not-active'\n | 'monitoring-list-missing'\n | 'configuration-changed';\n\nexport type UnsignedSubscriptionDelegation = {\n delegate: Hex;\n delegator: Hex;\n authority: Hex;\n caveats: {\n enforcer: Hex;\n terms: Hex;\n args: Hex;\n }[];\n salt: Hex;\n};\n\nexport type SignedSubscriptionDelegation = UnsignedSubscriptionDelegation & {\n signature: Hex;\n};\n\nexport type SubscriptionDelegationTypedData = {\n types: Record<string, { name: string; type: string }[]>;\n primaryType: string;\n domain: {\n chainId: number;\n name: string;\n version: string;\n verifyingContract: Hex;\n };\n message: Json;\n};\n\nexport type DecodedPermission = {\n tokenAddress: Hex;\n delegateAddress: Hex;\n periodAmount: string;\n periodDuration: number;\n startDate: number;\n maxNativeValue: '0';\n};\n\nexport type PreparedSubscriptionPermission = {\n id: SubscriptionPermissionId;\n owner: 'money-account' | 'subscription';\n disposition: 'new' | 'reused';\n delegation: UnsignedSubscriptionDelegation;\n typedData: SubscriptionDelegationTypedData;\n decodedAuthority: DecodedPermission;\n existingDelegationHash?: Hex;\n};\n\nexport type PreparedSubscriptionDelegationBundle = {\n policyVersion: string;\n account: Hex;\n chainId: Hex;\n permissions: PreparedSubscriptionPermission[];\n};\n\nexport type StartSubscriptionWithDelegationRequest = {\n product: ProductType;\n recurringInterval: RecurringInterval;\n chainId: Hex;\n payerAddress: Hex;\n};\n\nexport type PrepareAuthorizationBundleResult =\n | {\n status: 'prepared';\n bundle: PreparedSubscriptionDelegationBundle;\n }\n | {\n status: 'money-account-authorization-required';\n reasons: MoneyAccountAuthorizationReason[];\n };\n\nexport type CommitAuthorizationBundleRequest = {\n bundle: PreparedSubscriptionDelegationBundle;\n signedPaymentDelegation: SignedSubscriptionDelegation;\n};\n\nexport type CommitAuthorizationBundleResult = {\n paymentDelegationHash: Hex;\n};\n\nexport type StartSubscriptionWithDelegationResult =\n StartCryptoSubscriptionResponse;\n\n/**\n * Request to prepare a cash-subscription delegation.\n *\n * The service resolves all amount, token, delegate, and trial-duration fields\n * from authoritative pricing held by `SubscriptionController`.\n *\n * Only Money Account Plus is supported; Shield continues to use ERC-20\n * approval rather than delegation.\n */\nexport type PrepareSubscriptionDelegationRequest = {\n product: typeof PRODUCT_TYPES.MONEY_ACCOUNT_PLUS;\n recurringInterval: RecurringInterval;\n payerAddress: Hex;\n /**\n * Whether the user selected the pricing trial. Pricing `trialPeriodDays`\n * only affects the delegation start date when this is true.\n */\n isTrialRequested: boolean;\n /**\n * When true, gates preparation on a sufficient Money Account balance\n * (`unitAmount × minBillingCyclesForBalance` in mUSD) before side effects.\n */\n checkBalance?: boolean;\n /**\n * When true, skips CHOMP verify and intent registration. The returned\n * delegation hash is computed locally. Defaults to false.\n */\n skipChompInteractions?: boolean;\n};\n\n/**\n * Result of {@link SubscriptionDelegationService.prepareDelegation}.\n */\nexport type PreparedSubscriptionDelegation = {\n delegationHash: Hex;\n disposition: 'created' | 'reused';\n};\n\n/**\n * Request to check whether a Money Account holds enough convertible mUSD value\n * to cover the subscription funding requirement.\n */\nexport type MoneyAccountBalanceCheckRequest = Pick<\n PrepareSubscriptionDelegationRequest,\n 'product' | 'recurringInterval' | 'payerAddress'\n>;\n\n/**\n * Result of {@link SubscriptionDelegationService.checkMoneyAccountBalance}.\n * `balance` and `requiredBalance` are mUSD base units (6 decimals).\n */\nexport type MoneyAccountBalanceCheckResult = {\n hasSufficientBalance: boolean;\n balance: string;\n requiredBalance: string;\n};\n\n/**\n * Delegation Framework enforcers used by cash-subscription delegations.\n */\nexport type SubscriptionDelegationEnforcers = {\n erc20TokenPeriodTransfer: Hex;\n allowedCalldata: Hex;\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/subscription-controller",
|
|
3
|
-
"version": "12.0.1-preview-
|
|
3
|
+
"version": "12.0.1-preview-5e76941",
|
|
4
4
|
"description": "Handle user subscription",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -51,7 +51,6 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@ethersproject/abi": "^5.7.0",
|
|
54
|
-
"@metamask/approval-controller": "^10.0.0",
|
|
55
54
|
"@metamask/authenticated-user-storage": "^4.1.0",
|
|
56
55
|
"@metamask/base-controller": "^10.0.0",
|
|
57
56
|
"@metamask/base-data-service": "^2.1.0",
|