@metamask/subscription-controller 9.0.1 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -1
- package/dist/SubscriptionController.d.ts.map +1 -1
- package/dist/SubscriptionController.js +9 -1
- package/dist/SubscriptionController.js.map +1 -1
- package/dist/SubscriptionService-structs.d.ts +150 -36
- package/dist/SubscriptionService-structs.d.ts.map +1 -1
- package/dist/SubscriptionService-structs.js +46 -12
- package/dist/SubscriptionService-structs.js.map +1 -1
- package/dist/SubscriptionService.d.ts.map +1 -1
- package/dist/SubscriptionService.js +7 -1
- package/dist/SubscriptionService.js.map +1 -1
- package/dist/constants.d.ts +27 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +34 -0
- package/dist/constants.js.map +1 -1
- package/dist/index.d.ts +11 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/selectors.d.ts +41 -1
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +65 -0
- package/dist/selectors.js.map +1 -1
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts +49 -0
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.d.ts.map +1 -0
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js +6 -0
- package/dist/subscription-delegation/SubscriptionDelegationService-method-action-types.js.map +1 -0
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts +97 -0
- package/dist/subscription-delegation/SubscriptionDelegationService.d.ts.map +1 -0
- package/dist/subscription-delegation/SubscriptionDelegationService.js +306 -0
- package/dist/subscription-delegation/SubscriptionDelegationService.js.map +1 -0
- package/dist/subscription-delegation/amount.d.ts +49 -0
- package/dist/subscription-delegation/amount.d.ts.map +1 -0
- package/dist/subscription-delegation/amount.js +84 -0
- package/dist/subscription-delegation/amount.js.map +1 -0
- package/dist/subscription-delegation/caveats.d.ts +40 -0
- package/dist/subscription-delegation/caveats.d.ts.map +1 -0
- package/dist/subscription-delegation/caveats.js +51 -0
- package/dist/subscription-delegation/caveats.js.map +1 -0
- package/dist/subscription-delegation/fingerprint.d.ts +53 -0
- package/dist/subscription-delegation/fingerprint.d.ts.map +1 -0
- package/dist/subscription-delegation/fingerprint.js +109 -0
- package/dist/subscription-delegation/fingerprint.js.map +1 -0
- package/dist/subscription-delegation/types.d.ts +72 -0
- package/dist/subscription-delegation/types.d.ts.map +1 -0
- package/dist/subscription-delegation/types.js +10 -0
- package/dist/subscription-delegation/types.js.map +1 -0
- package/dist/types.d.ts +113 -17
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +39 -0
- package/dist/types.js.map +1 -1
- package/package.json +18 -9
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { SubscriptionDelegationServiceErrorMessage } from '../constants.js';
|
|
2
|
+
import { RECURRING_INTERVALS } from '../types.js';
|
|
3
|
+
const SECONDS_PER_DAY = 86_400;
|
|
4
|
+
/**
|
|
5
|
+
* Rescales a plan fee from pricing `unitDecimals` into token base units.
|
|
6
|
+
*
|
|
7
|
+
* Uses a 1:1 numeric mapping (ADR 0057): the period amount is one billing
|
|
8
|
+
* interval's fee, not `fee × minimumFundingCycles`.
|
|
9
|
+
*
|
|
10
|
+
* @param params - Amount and decimal inputs.
|
|
11
|
+
* @param params.unitAmount - Fee in pricing minor units (non-negative integer).
|
|
12
|
+
* @param params.unitDecimals - Decimals of `unitAmount`.
|
|
13
|
+
* @param params.tokenDecimals - Decimals of the payment token.
|
|
14
|
+
* @returns The period amount in token base units.
|
|
15
|
+
* @throws If inputs are not non-negative integers, or downscaling would lose precision.
|
|
16
|
+
*/
|
|
17
|
+
export function calculatePeriodAmount({ unitAmount, unitDecimals, tokenDecimals, }) {
|
|
18
|
+
assertNonNegativeInteger(unitAmount, SubscriptionDelegationServiceErrorMessage.InvalidAmount);
|
|
19
|
+
assertNonNegativeInteger(unitDecimals, SubscriptionDelegationServiceErrorMessage.InvalidDecimals);
|
|
20
|
+
assertNonNegativeInteger(tokenDecimals, SubscriptionDelegationServiceErrorMessage.InvalidDecimals);
|
|
21
|
+
const amount = BigInt(unitAmount);
|
|
22
|
+
if (tokenDecimals === unitDecimals) {
|
|
23
|
+
return amount;
|
|
24
|
+
}
|
|
25
|
+
if (tokenDecimals > unitDecimals) {
|
|
26
|
+
return amount * 10n ** BigInt(tokenDecimals - unitDecimals);
|
|
27
|
+
}
|
|
28
|
+
const divisor = 10n ** BigInt(unitDecimals - tokenDecimals);
|
|
29
|
+
if (amount % divisor !== 0n) {
|
|
30
|
+
throw new Error(SubscriptionDelegationServiceErrorMessage.LossyAmountScale);
|
|
31
|
+
}
|
|
32
|
+
return amount / divisor;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Plan-scoped ERC-20 period duration in seconds (ADR 0057).
|
|
36
|
+
*
|
|
37
|
+
* - Monthly: 28 days (minimum Stripe monthly invoice gap).
|
|
38
|
+
* - Yearly: 365 days.
|
|
39
|
+
*
|
|
40
|
+
* @param recurringInterval - Subscription billing interval.
|
|
41
|
+
* @returns Period duration in seconds.
|
|
42
|
+
*/
|
|
43
|
+
export function getPeriodDuration(recurringInterval) {
|
|
44
|
+
if (recurringInterval === RECURRING_INTERVALS.month) {
|
|
45
|
+
return 28 * SECONDS_PER_DAY;
|
|
46
|
+
}
|
|
47
|
+
if (recurringInterval === RECURRING_INTERVALS.year) {
|
|
48
|
+
return 365 * SECONDS_PER_DAY;
|
|
49
|
+
}
|
|
50
|
+
throw new Error(SubscriptionDelegationServiceErrorMessage.UnsupportedRecurringInterval);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Computes the ERC20TokenPeriodTransfer `startDate` for a subscription
|
|
54
|
+
* delegation, optionally deferred by a pricing trial.
|
|
55
|
+
*
|
|
56
|
+
* @param params - Clock and optional trial length.
|
|
57
|
+
* @param params.nowSeconds - Current unix timestamp in seconds.
|
|
58
|
+
* @param params.trialPeriodDays - Optional non-negative trial length in days.
|
|
59
|
+
* Defaults to `0` (no offset) when omitted.
|
|
60
|
+
* @returns Unix timestamp when the first period transfer may begin.
|
|
61
|
+
*/
|
|
62
|
+
export function getDelegationStartDate({ nowSeconds, trialPeriodDays = 0, }) {
|
|
63
|
+
assertNonNegativeInteger(trialPeriodDays, SubscriptionDelegationServiceErrorMessage.InvalidTrialPeriodDays);
|
|
64
|
+
return nowSeconds + trialPeriodDays * SECONDS_PER_DAY;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* @param value - Candidate number.
|
|
68
|
+
* @param message - Error message when invalid.
|
|
69
|
+
*/
|
|
70
|
+
function assertNonNegativeInteger(value, message) {
|
|
71
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
72
|
+
throw new Error(message);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* @param value - Candidate number.
|
|
77
|
+
* @param message - Error message when invalid.
|
|
78
|
+
*/
|
|
79
|
+
export function assertPositiveInteger(value, message) {
|
|
80
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
81
|
+
throw new Error(message);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=amount.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"amount.js","sourceRoot":"","sources":["../../src/subscription-delegation/amount.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yCAAyC,EAAE,MAAM,iBAAiB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAGlD,MAAM,eAAe,GAAG,MAAM,CAAC;AAE/B;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CAAC,EACpC,UAAU,EACV,YAAY,EACZ,aAAa,GAKd;IACC,wBAAwB,CACtB,UAAU,EACV,yCAAyC,CAAC,aAAa,CACxD,CAAC;IACF,wBAAwB,CACtB,YAAY,EACZ,yCAAyC,CAAC,eAAe,CAC1D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,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAAa,EAAE,OAAe;IAClE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;AACH,CAAC","sourcesContent":["import { SubscriptionDelegationServiceErrorMessage } from '../constants.js';\nimport { RECURRING_INTERVALS } from '../types.js';\nimport type { RecurringInterval } from '../types.js';\n\nconst SECONDS_PER_DAY = 86_400;\n\n/**\n * Rescales a plan fee from pricing `unitDecimals` into token base units.\n *\n * Uses a 1:1 numeric mapping (ADR 0057): the period amount is one billing\n * interval's fee, not `fee × minimumFundingCycles`.\n *\n * @param params - Amount and decimal inputs.\n * @param params.unitAmount - Fee in pricing minor units (non-negative integer).\n * @param params.unitDecimals - Decimals of `unitAmount`.\n * @param params.tokenDecimals - Decimals of the payment token.\n * @returns The period amount in token base units.\n * @throws If inputs are not non-negative integers, or downscaling would lose precision.\n */\nexport function calculatePeriodAmount({\n unitAmount,\n unitDecimals,\n tokenDecimals,\n}: {\n unitAmount: number;\n unitDecimals: number;\n tokenDecimals: number;\n}): bigint {\n assertNonNegativeInteger(\n unitAmount,\n SubscriptionDelegationServiceErrorMessage.InvalidAmount,\n );\n assertNonNegativeInteger(\n unitDecimals,\n SubscriptionDelegationServiceErrorMessage.InvalidDecimals,\n );\n assertNonNegativeInteger(\n tokenDecimals,\n SubscriptionDelegationServiceErrorMessage.InvalidDecimals,\n );\n\n const amount = BigInt(unitAmount);\n\n if (tokenDecimals === unitDecimals) {\n return amount;\n }\n\n if (tokenDecimals > unitDecimals) {\n return amount * 10n ** BigInt(tokenDecimals - unitDecimals);\n }\n\n const divisor = 10n ** BigInt(unitDecimals - tokenDecimals);\n if (amount % divisor !== 0n) {\n throw new Error(SubscriptionDelegationServiceErrorMessage.LossyAmountScale);\n }\n return amount / divisor;\n}\n\n/**\n * Plan-scoped ERC-20 period duration in seconds (ADR 0057).\n *\n * - Monthly: 28 days (minimum Stripe monthly invoice gap).\n * - Yearly: 365 days.\n *\n * @param recurringInterval - Subscription billing interval.\n * @returns Period duration in seconds.\n */\nexport function getPeriodDuration(\n recurringInterval: RecurringInterval,\n): number {\n if (recurringInterval === RECURRING_INTERVALS.month) {\n return 28 * SECONDS_PER_DAY;\n }\n if (recurringInterval === RECURRING_INTERVALS.year) {\n return 365 * SECONDS_PER_DAY;\n }\n throw new Error(\n SubscriptionDelegationServiceErrorMessage.UnsupportedRecurringInterval,\n );\n}\n\n/**\n * Computes the ERC20TokenPeriodTransfer `startDate` for a subscription\n * delegation, optionally deferred by a pricing trial.\n *\n * @param params - Clock and optional trial length.\n * @param params.nowSeconds - Current unix timestamp in seconds.\n * @param params.trialPeriodDays - Optional non-negative trial length in days.\n * Defaults to `0` (no offset) when omitted.\n * @returns Unix timestamp when the first period transfer may begin.\n */\nexport function getDelegationStartDate({\n nowSeconds,\n trialPeriodDays = 0,\n}: {\n nowSeconds: number;\n trialPeriodDays?: number;\n}): number {\n assertNonNegativeInteger(\n trialPeriodDays,\n SubscriptionDelegationServiceErrorMessage.InvalidTrialPeriodDays,\n );\n return nowSeconds + trialPeriodDays * SECONDS_PER_DAY;\n}\n\n/**\n * @param value - Candidate number.\n * @param message - Error message when invalid.\n */\nfunction assertNonNegativeInteger(value: number, message: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(message);\n }\n}\n\n/**\n * @param value - Candidate number.\n * @param message - Error message when invalid.\n */\nexport function assertPositiveInteger(value: number, message: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(message);\n }\n}\n"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { SignedDelegation } from '@metamask/authenticated-user-storage';
|
|
2
|
+
import type { Hex } from '@metamask/utils';
|
|
3
|
+
import type { SubscriptionDelegationEnforcers } from './types.js';
|
|
4
|
+
export type UnsignedSubscriptionDelegation = Omit<SignedDelegation, 'signature'>;
|
|
5
|
+
export type BuildSubscriptionCaveatsParams = {
|
|
6
|
+
enforcers: SubscriptionDelegationEnforcers;
|
|
7
|
+
delegateAddress: Hex;
|
|
8
|
+
tokenAddress: Hex;
|
|
9
|
+
periodAmount: bigint;
|
|
10
|
+
periodDuration: number;
|
|
11
|
+
startDate: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Builds the caveat list for a cash-subscription delegation:
|
|
15
|
+
* `ValueLte(0)` then `ERC20TokenPeriodTransfer(...)`.
|
|
16
|
+
*
|
|
17
|
+
* @param params - Enforcer addresses, parties, and period terms.
|
|
18
|
+
* @param params.enforcers - Delegation Framework enforcer addresses.
|
|
19
|
+
* @param params.tokenAddress - Subscription settlement token.
|
|
20
|
+
* @param params.periodAmount - Maximum token amount per period.
|
|
21
|
+
* @param params.periodDuration - Period length in seconds.
|
|
22
|
+
* @param params.startDate - Unix timestamp when transfers may begin.
|
|
23
|
+
* @returns Caveats in enforcer order.
|
|
24
|
+
*/
|
|
25
|
+
export declare function buildSubscriptionCaveats({ enforcers, tokenAddress, periodAmount, periodDuration, startDate, }: BuildSubscriptionCaveatsParams): SignedDelegation['caveats'];
|
|
26
|
+
export type BuildUnsignedSubscriptionDelegationParams = BuildSubscriptionCaveatsParams & {
|
|
27
|
+
delegatorAddress: Hex;
|
|
28
|
+
/**
|
|
29
|
+
* Optional salt for tests. When omitted, a random 32-byte salt is generated.
|
|
30
|
+
*/
|
|
31
|
+
salt?: Hex;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Builds an unsigned root cash-subscription delegation.
|
|
35
|
+
*
|
|
36
|
+
* @param params - Delegation parties, enforcers, and period terms.
|
|
37
|
+
* @returns An unsigned delegation ready for signing.
|
|
38
|
+
*/
|
|
39
|
+
export declare function buildUnsignedSubscriptionDelegation(params: BuildUnsignedSubscriptionDelegationParams): UnsignedSubscriptionDelegation;
|
|
40
|
+
//# sourceMappingURL=caveats.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"caveats.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/caveats.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAO7E,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAElE,MAAM,MAAM,8BAA8B,GAAG,IAAI,CAC/C,gBAAgB,EAChB,WAAW,CACZ,CAAC;AAEF,MAAM,MAAM,8BAA8B,GAAG;IAC3C,SAAS,EAAE,+BAA+B,CAAC;IAC3C,eAAe,EAAE,GAAG,CAAC;IACrB,YAAY,EAAE,GAAG,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,EACvC,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,SAAS,GACV,EAAE,8BAA8B,GAAG,gBAAgB,CAAC,SAAS,CAAC,CAkB9D;AAED,MAAM,MAAM,yCAAyC,GACnD,8BAA8B,GAAG;IAC/B,gBAAgB,EAAE,GAAG,CAAC;IACtB;;OAEG;IACH,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ,CAAC;AAEJ;;;;;GAKG;AACH,wBAAgB,mCAAmC,CACjD,MAAM,EAAE,yCAAyC,GAChD,8BAA8B,CAYhC"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { ROOT_AUTHORITY, createERC20TokenPeriodTransferTerms, createValueLteTerms, } from '@metamask/delegation-core';
|
|
2
|
+
import { bytesToHex } from '@metamask/utils';
|
|
3
|
+
/**
|
|
4
|
+
* Builds the caveat list for a cash-subscription delegation:
|
|
5
|
+
* `ValueLte(0)` then `ERC20TokenPeriodTransfer(...)`.
|
|
6
|
+
*
|
|
7
|
+
* @param params - Enforcer addresses, parties, and period terms.
|
|
8
|
+
* @param params.enforcers - Delegation Framework enforcer addresses.
|
|
9
|
+
* @param params.tokenAddress - Subscription settlement token.
|
|
10
|
+
* @param params.periodAmount - Maximum token amount per period.
|
|
11
|
+
* @param params.periodDuration - Period length in seconds.
|
|
12
|
+
* @param params.startDate - Unix timestamp when transfers may begin.
|
|
13
|
+
* @returns Caveats in enforcer order.
|
|
14
|
+
*/
|
|
15
|
+
export function buildSubscriptionCaveats({ enforcers, tokenAddress, periodAmount, periodDuration, startDate, }) {
|
|
16
|
+
return [
|
|
17
|
+
{
|
|
18
|
+
enforcer: enforcers.valueLte,
|
|
19
|
+
terms: createValueLteTerms({ maxValue: 0n }),
|
|
20
|
+
args: '0x',
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
enforcer: enforcers.erc20TokenPeriodTransfer,
|
|
24
|
+
terms: createERC20TokenPeriodTransferTerms({
|
|
25
|
+
tokenAddress,
|
|
26
|
+
periodAmount,
|
|
27
|
+
periodDuration,
|
|
28
|
+
startDate,
|
|
29
|
+
}),
|
|
30
|
+
args: '0x',
|
|
31
|
+
},
|
|
32
|
+
];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Builds an unsigned root cash-subscription delegation.
|
|
36
|
+
*
|
|
37
|
+
* @param params - Delegation parties, enforcers, and period terms.
|
|
38
|
+
* @returns An unsigned delegation ready for signing.
|
|
39
|
+
*/
|
|
40
|
+
export function buildUnsignedSubscriptionDelegation(params) {
|
|
41
|
+
const salt = params.salt ??
|
|
42
|
+
bytesToHex(globalThis.crypto.getRandomValues(new Uint8Array(32)));
|
|
43
|
+
return {
|
|
44
|
+
delegate: params.delegateAddress,
|
|
45
|
+
delegator: params.delegatorAddress,
|
|
46
|
+
authority: ROOT_AUTHORITY,
|
|
47
|
+
caveats: buildSubscriptionCaveats(params),
|
|
48
|
+
salt,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=caveats.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"caveats.js","sourceRoot":"","sources":["../../src/subscription-delegation/caveats.ts"],"names":[],"mappings":"AACA,OAAO,EACL,cAAc,EACd,mCAAmC,EACnC,mBAAmB,GACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAmB7C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,wBAAwB,CAAC,EACvC,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,SAAS,GACsB;IAC/B,OAAO;QACL;YACE,QAAQ,EAAE,SAAS,CAAC,QAAQ;YAC5B,KAAK,EAAE,mBAAmB,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;YAC5C,IAAI,EAAE,IAAI;SACX;QACD;YACE,QAAQ,EAAE,SAAS,CAAC,wBAAwB;YAC5C,KAAK,EAAE,mCAAmC,CAAC;gBACzC,YAAY;gBACZ,YAAY;gBACZ,cAAc;gBACd,SAAS;aACV,CAAC;YACF,IAAI,EAAE,IAAI;SACX;KACF,CAAC;AACJ,CAAC;AAWD;;;;;GAKG;AACH,MAAM,UAAU,mCAAmC,CACjD,MAAiD;IAEjD,MAAM,IAAI,GACR,MAAM,CAAC,IAAI;QACX,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAEpE,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,eAAe;QAChC,SAAS,EAAE,MAAM,CAAC,gBAAgB;QAClC,SAAS,EAAE,cAAc;QACzB,OAAO,EAAE,wBAAwB,CAAC,MAAM,CAAC;QACzC,IAAI;KACL,CAAC;AACJ,CAAC","sourcesContent":["import type { SignedDelegation } from '@metamask/authenticated-user-storage';\nimport {\n ROOT_AUTHORITY,\n createERC20TokenPeriodTransferTerms,\n createValueLteTerms,\n} from '@metamask/delegation-core';\nimport { bytesToHex } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport type { SubscriptionDelegationEnforcers } from './types.js';\n\nexport type UnsignedSubscriptionDelegation = Omit<\n SignedDelegation,\n 'signature'\n>;\n\nexport type BuildSubscriptionCaveatsParams = {\n enforcers: SubscriptionDelegationEnforcers;\n delegateAddress: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n startDate: number;\n};\n\n/**\n * Builds the caveat list for a cash-subscription delegation:\n * `ValueLte(0)` then `ERC20TokenPeriodTransfer(...)`.\n *\n * @param params - Enforcer addresses, parties, and period terms.\n * @param params.enforcers - Delegation Framework enforcer addresses.\n * @param params.tokenAddress - Subscription settlement token.\n * @param params.periodAmount - Maximum token amount per period.\n * @param params.periodDuration - Period length in seconds.\n * @param params.startDate - Unix timestamp when transfers may begin.\n * @returns Caveats in enforcer order.\n */\nexport function buildSubscriptionCaveats({\n enforcers,\n tokenAddress,\n periodAmount,\n periodDuration,\n startDate,\n}: BuildSubscriptionCaveatsParams): SignedDelegation['caveats'] {\n return [\n {\n enforcer: enforcers.valueLte,\n terms: createValueLteTerms({ maxValue: 0n }),\n args: '0x',\n },\n {\n enforcer: enforcers.erc20TokenPeriodTransfer,\n terms: createERC20TokenPeriodTransferTerms({\n tokenAddress,\n periodAmount,\n periodDuration,\n startDate,\n }),\n args: '0x',\n },\n ];\n}\n\nexport type BuildUnsignedSubscriptionDelegationParams =\n BuildSubscriptionCaveatsParams & {\n delegatorAddress: Hex;\n /**\n * Optional salt for tests. When omitted, a random 32-byte salt is generated.\n */\n salt?: Hex;\n };\n\n/**\n * Builds an unsigned root cash-subscription delegation.\n *\n * @param params - Delegation parties, enforcers, and period terms.\n * @returns An unsigned delegation ready for signing.\n */\nexport function buildUnsignedSubscriptionDelegation(\n params: BuildUnsignedSubscriptionDelegationParams,\n): UnsignedSubscriptionDelegation {\n const salt =\n params.salt ??\n bytesToHex(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n\n return {\n delegate: params.delegateAddress,\n delegator: params.delegatorAddress,\n authority: ROOT_AUTHORITY,\n caveats: buildSubscriptionCaveats(params),\n salt,\n };\n}\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { DelegationResponse } from '@metamask/authenticated-user-storage';
|
|
2
|
+
import type { Hex } from '@metamask/utils';
|
|
3
|
+
import type { SubscriptionDelegationEnforcers } from './types.js';
|
|
4
|
+
export type SubscriptionDelegationFingerprint = {
|
|
5
|
+
delegatorAddress: Hex;
|
|
6
|
+
delegateAddress: Hex;
|
|
7
|
+
chainId: Hex;
|
|
8
|
+
tokenAddress: Hex;
|
|
9
|
+
periodAmount: bigint;
|
|
10
|
+
periodDuration: number;
|
|
11
|
+
/**
|
|
12
|
+
* Current unix timestamp in seconds. Used to classify a stored period
|
|
13
|
+
* `startDate` as immediately redeemable (`<= now`) vs trial-deferred (`> now`).
|
|
14
|
+
*/
|
|
15
|
+
nowSeconds: number;
|
|
16
|
+
/**
|
|
17
|
+
* When true, only a still-deferred period start (`> nowSeconds`) matches.
|
|
18
|
+
* When false, only an immediately redeemable start (`<= nowSeconds`) matches.
|
|
19
|
+
*/
|
|
20
|
+
isTrialDeferred: boolean;
|
|
21
|
+
enforcers: SubscriptionDelegationEnforcers;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Case-insensitive hex equality.
|
|
25
|
+
*
|
|
26
|
+
* @param left - First hex value.
|
|
27
|
+
* @param right - Second hex value.
|
|
28
|
+
* @returns Whether the values are equal ignoring case.
|
|
29
|
+
*/
|
|
30
|
+
export declare function equalsIgnoreCase(left: string, right: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Builds a predicate that matches a stored AUS delegation to the semantic
|
|
33
|
+
* cash-subscription fingerprint. Salt is ignored so a previously signed
|
|
34
|
+
* equivalent permission can be reused. Period `startDate` is compared only
|
|
35
|
+
* as trial-deferred (`> nowSeconds`) vs immediately redeemable (`<= nowSeconds`)
|
|
36
|
+
* so a positive-length trial cannot reuse a live permission and vice versa.
|
|
37
|
+
*
|
|
38
|
+
* @param expected - Semantic fields that must match.
|
|
39
|
+
* @returns Predicate over {@link DelegationResponse}.
|
|
40
|
+
*/
|
|
41
|
+
export declare function makeMatchesSubscriptionDelegation(expected: SubscriptionDelegationFingerprint): (entry: DelegationResponse) => boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Returns the fingerprint match with the latest period `startDate`.
|
|
44
|
+
*
|
|
45
|
+
* Equal `startDate`s keep list order. A delegation whose `startDate` cannot
|
|
46
|
+
* be read sorts last.
|
|
47
|
+
*
|
|
48
|
+
* @param matches - Fingerprint-matching AUS delegations, in list order.
|
|
49
|
+
* @param enforcers - Enforcer addresses used to read `startDate`.
|
|
50
|
+
* @returns The preferred match, or `undefined` when `matches` is empty.
|
|
51
|
+
*/
|
|
52
|
+
export declare function pickLatestMatchingSubscriptionDelegation(matches: readonly DelegationResponse[], enforcers: SubscriptionDelegationEnforcers): DelegationResponse | undefined;
|
|
53
|
+
//# sourceMappingURL=fingerprint.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fingerprint.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/fingerprint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAK/E,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,YAAY,CAAC;AAGlE,MAAM,MAAM,iCAAiC,GAAG;IAC9C,gBAAgB,EAAE,GAAG,CAAC;IACtB,eAAe,EAAE,GAAG,CAAC;IACrB,OAAO,EAAE,GAAG,CAAC;IACb,YAAY,EAAE,GAAG,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,eAAe,EAAE,OAAO,CAAC;IACzB,SAAS,EAAE,+BAA+B,CAAC;CAC5C,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAErE;AAED;;;;;;;;;GASG;AACH,wBAAgB,iCAAiC,CAC/C,QAAQ,EAAE,iCAAiC,GAC1C,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAsExC;AA8BD;;;;;;;;;GASG;AACH,wBAAgB,wCAAwC,CACtD,OAAO,EAAE,SAAS,kBAAkB,EAAE,EACtC,SAAS,EAAE,+BAA+B,GACzC,kBAAkB,GAAG,SAAS,CAYhC"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { decodeERC20TokenPeriodTransferTerms, decodeValueLteTerms, } from '@metamask/delegation-core';
|
|
2
|
+
import { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Case-insensitive hex equality.
|
|
5
|
+
*
|
|
6
|
+
* @param left - First hex value.
|
|
7
|
+
* @param right - Second hex value.
|
|
8
|
+
* @returns Whether the values are equal ignoring case.
|
|
9
|
+
*/
|
|
10
|
+
export function equalsIgnoreCase(left, right) {
|
|
11
|
+
return left.toLowerCase() === right.toLowerCase();
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Builds a predicate that matches a stored AUS delegation to the semantic
|
|
15
|
+
* cash-subscription fingerprint. Salt is ignored so a previously signed
|
|
16
|
+
* equivalent permission can be reused. Period `startDate` is compared only
|
|
17
|
+
* as trial-deferred (`> nowSeconds`) vs immediately redeemable (`<= nowSeconds`)
|
|
18
|
+
* so a positive-length trial cannot reuse a live permission and vice versa.
|
|
19
|
+
*
|
|
20
|
+
* @param expected - Semantic fields that must match.
|
|
21
|
+
* @returns Predicate over {@link DelegationResponse}.
|
|
22
|
+
*/
|
|
23
|
+
export function makeMatchesSubscriptionDelegation(expected) {
|
|
24
|
+
return (entry) => {
|
|
25
|
+
if (entry.metadata.type !== CASH_SUBSCRIPTION_DELEGATION_TYPE) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
if (!equalsIgnoreCase(entry.signedDelegation.delegator, expected.delegatorAddress)) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
if (!equalsIgnoreCase(entry.signedDelegation.delegate, expected.delegateAddress)) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
if (!equalsIgnoreCase(entry.metadata.chainIdHex, expected.chainId)) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (!equalsIgnoreCase(entry.metadata.tokenAddress, expected.tokenAddress)) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
const { caveats } = entry.signedDelegation;
|
|
41
|
+
if (caveats.length < 2) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
const valueLteCaveat = caveats.find((caveat) => equalsIgnoreCase(caveat.enforcer, expected.enforcers.valueLte));
|
|
45
|
+
const periodCaveat = caveats.find((caveat) => equalsIgnoreCase(caveat.enforcer, expected.enforcers.erc20TokenPeriodTransfer));
|
|
46
|
+
if (!valueLteCaveat || !periodCaveat) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const valueTerms = decodeValueLteTerms(valueLteCaveat.terms);
|
|
51
|
+
if (valueTerms.maxValue !== 0n) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
const periodTerms = decodeERC20TokenPeriodTransferTerms(periodCaveat.terms);
|
|
55
|
+
const storedStartDate = Number(periodTerms.startDate);
|
|
56
|
+
const isStoredDeferred = storedStartDate > expected.nowSeconds;
|
|
57
|
+
if (expected.isTrialDeferred !== isStoredDeferred) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
return (equalsIgnoreCase(periodTerms.tokenAddress, expected.tokenAddress) &&
|
|
61
|
+
periodTerms.periodAmount === expected.periodAmount &&
|
|
62
|
+
Number(periodTerms.periodDuration) === expected.periodDuration);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Reads the ERC-20 period-transfer `startDate` from a stored delegation.
|
|
71
|
+
*
|
|
72
|
+
* @param entry - Stored AUS delegation.
|
|
73
|
+
* @param enforcers - Enforcer addresses used to locate the period caveat.
|
|
74
|
+
* @returns Unix timestamp in seconds, or `undefined` when the caveat is
|
|
75
|
+
* missing or malformed.
|
|
76
|
+
*/
|
|
77
|
+
function getSubscriptionDelegationStartDate(entry, enforcers) {
|
|
78
|
+
const periodCaveat = entry.signedDelegation.caveats.find((caveat) => equalsIgnoreCase(caveat.enforcer, enforcers.erc20TokenPeriodTransfer));
|
|
79
|
+
if (!periodCaveat) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
return Number(decodeERC20TokenPeriodTransferTerms(periodCaveat.terms).startDate);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Returns the fingerprint match with the latest period `startDate`.
|
|
91
|
+
*
|
|
92
|
+
* Equal `startDate`s keep list order. A delegation whose `startDate` cannot
|
|
93
|
+
* be read sorts last.
|
|
94
|
+
*
|
|
95
|
+
* @param matches - Fingerprint-matching AUS delegations, in list order.
|
|
96
|
+
* @param enforcers - Enforcer addresses used to read `startDate`.
|
|
97
|
+
* @returns The preferred match, or `undefined` when `matches` is empty.
|
|
98
|
+
*/
|
|
99
|
+
export function pickLatestMatchingSubscriptionDelegation(matches, enforcers) {
|
|
100
|
+
const byStartDateDescending = [...matches].sort((left, right) => {
|
|
101
|
+
const leftStart = getSubscriptionDelegationStartDate(left, enforcers) ??
|
|
102
|
+
Number.NEGATIVE_INFINITY;
|
|
103
|
+
const rightStart = getSubscriptionDelegationStartDate(right, enforcers) ??
|
|
104
|
+
Number.NEGATIVE_INFINITY;
|
|
105
|
+
return rightStart - leftStart;
|
|
106
|
+
});
|
|
107
|
+
return byStartDateDescending[0];
|
|
108
|
+
}
|
|
109
|
+
//# sourceMappingURL=fingerprint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fingerprint.js","sourceRoot":"","sources":["../../src/subscription-delegation/fingerprint.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mCAAmC,EACnC,mBAAmB,GACpB,MAAM,2BAA2B,CAAC;AAInC,OAAO,EAAE,iCAAiC,EAAE,MAAM,YAAY,CAAC;AAsB/D;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAE,KAAa;IAC1D,OAAO,IAAI,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC,WAAW,EAAE,CAAC;AACpD,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,iCAAiC,CAC/C,QAA2C;IAE3C,OAAO,CAAC,KAAK,EAAE,EAAE;QACf,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,KAAK,iCAAiC,EAAE,CAAC;YAC9D,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IACE,CAAC,gBAAgB,CACf,KAAK,CAAC,gBAAgB,CAAC,SAAS,EAChC,QAAQ,CAAC,gBAAgB,CAC1B,EACD,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IACE,CAAC,gBAAgB,CACf,KAAK,CAAC,gBAAgB,CAAC,QAAQ,EAC/B,QAAQ,CAAC,eAAe,CACzB,EACD,CAAC;YACD,OAAO,KAA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EAAE,SAAS,CAAC;YACpD,MAAM,CAAC,iBAAiB,CAAC;QAC3B,OAAO,UAAU,GAAG,SAAS,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,OAAO,qBAAqB,CAAC,CAAC,CAAC,CAAC;AAClC,CAAC","sourcesContent":["import type { DelegationResponse } from '@metamask/authenticated-user-storage';\nimport {\n decodeERC20TokenPeriodTransferTerms,\n decodeValueLteTerms,\n} from '@metamask/delegation-core';\nimport type { Hex } from '@metamask/utils';\n\nimport type { SubscriptionDelegationEnforcers } from './types.js';\nimport { CASH_SUBSCRIPTION_DELEGATION_TYPE } from './types.js';\n\nexport type SubscriptionDelegationFingerprint = {\n delegatorAddress: Hex;\n delegateAddress: Hex;\n chainId: Hex;\n tokenAddress: Hex;\n periodAmount: bigint;\n periodDuration: number;\n /**\n * Current unix timestamp in seconds. Used to classify a stored period\n * `startDate` as immediately redeemable (`<= now`) vs trial-deferred (`> now`).\n */\n nowSeconds: number;\n /**\n * When true, only a still-deferred period start (`> nowSeconds`) matches.\n * When false, only an immediately redeemable start (`<= nowSeconds`) matches.\n */\n isTrialDeferred: boolean;\n enforcers: SubscriptionDelegationEnforcers;\n};\n\n/**\n * Case-insensitive hex equality.\n *\n * @param left - First hex value.\n * @param right - Second hex value.\n * @returns Whether the values are equal ignoring case.\n */\nexport function equalsIgnoreCase(left: string, right: string): boolean {\n return left.toLowerCase() === right.toLowerCase();\n}\n\n/**\n * Builds a predicate that matches a stored AUS delegation to the semantic\n * cash-subscription fingerprint. Salt is ignored so a previously signed\n * equivalent permission can be reused. Period `startDate` is compared only\n * as trial-deferred (`> nowSeconds`) vs immediately redeemable (`<= nowSeconds`)\n * so a positive-length trial cannot reuse a live permission and vice versa.\n *\n * @param expected - Semantic fields that must match.\n * @returns Predicate over {@link DelegationResponse}.\n */\nexport function makeMatchesSubscriptionDelegation(\n expected: SubscriptionDelegationFingerprint,\n): (entry: DelegationResponse) => boolean {\n return (entry) => {\n if (entry.metadata.type !== CASH_SUBSCRIPTION_DELEGATION_TYPE) {\n return false;\n }\n if (\n !equalsIgnoreCase(\n entry.signedDelegation.delegator,\n expected.delegatorAddress,\n )\n ) {\n return false;\n }\n if (\n !equalsIgnoreCase(\n entry.signedDelegation.delegate,\n expected.delegateAddress,\n )\n ) {\n return false;\n }\n if (!equalsIgnoreCase(entry.metadata.chainIdHex, expected.chainId)) {\n return false;\n }\n if (!equalsIgnoreCase(entry.metadata.tokenAddress, expected.tokenAddress)) {\n return false;\n }\n\n const { caveats } = entry.signedDelegation;\n if (caveats.length < 2) {\n return false;\n }\n\n const valueLteCaveat = caveats.find((caveat) =>\n equalsIgnoreCase(caveat.enforcer, expected.enforcers.valueLte),\n );\n const periodCaveat = caveats.find((caveat) =>\n equalsIgnoreCase(\n caveat.enforcer,\n expected.enforcers.erc20TokenPeriodTransfer,\n ),\n );\n if (!valueLteCaveat || !periodCaveat) {\n return false;\n }\n\n try {\n const valueTerms = decodeValueLteTerms(valueLteCaveat.terms);\n if (valueTerms.maxValue !== 0n) {\n return false;\n }\n\n const periodTerms = decodeERC20TokenPeriodTransferTerms(\n periodCaveat.terms,\n );\n const storedStartDate = Number(periodTerms.startDate);\n const isStoredDeferred = storedStartDate > expected.nowSeconds;\n if (expected.isTrialDeferred !== isStoredDeferred) {\n return false;\n }\n\n return (\n equalsIgnoreCase(periodTerms.tokenAddress, expected.tokenAddress) &&\n periodTerms.periodAmount === expected.periodAmount &&\n Number(periodTerms.periodDuration) === expected.periodDuration\n );\n } catch {\n return false;\n }\n };\n}\n\n/**\n * Reads the ERC-20 period-transfer `startDate` from a stored delegation.\n *\n * @param entry - Stored AUS delegation.\n * @param enforcers - Enforcer addresses used to locate the period caveat.\n * @returns Unix timestamp in seconds, or `undefined` when the caveat is\n * missing or malformed.\n */\nfunction getSubscriptionDelegationStartDate(\n entry: DelegationResponse,\n enforcers: SubscriptionDelegationEnforcers,\n): number | undefined {\n const periodCaveat = entry.signedDelegation.caveats.find((caveat) =>\n equalsIgnoreCase(caveat.enforcer, enforcers.erc20TokenPeriodTransfer),\n );\n if (!periodCaveat) {\n return undefined;\n }\n\n try {\n return Number(\n decodeERC20TokenPeriodTransferTerms(periodCaveat.terms).startDate,\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the fingerprint match with the latest period `startDate`.\n *\n * Equal `startDate`s keep list order. A delegation whose `startDate` cannot\n * be read sorts last.\n *\n * @param matches - Fingerprint-matching AUS delegations, in list order.\n * @param enforcers - Enforcer addresses used to read `startDate`.\n * @returns The preferred match, or `undefined` when `matches` is empty.\n */\nexport function pickLatestMatchingSubscriptionDelegation(\n matches: readonly DelegationResponse[],\n enforcers: SubscriptionDelegationEnforcers,\n): DelegationResponse | undefined {\n const byStartDateDescending = [...matches].sort((left, right) => {\n const leftStart =\n getSubscriptionDelegationStartDate(left, enforcers) ??\n Number.NEGATIVE_INFINITY;\n const rightStart =\n getSubscriptionDelegationStartDate(right, enforcers) ??\n Number.NEGATIVE_INFINITY;\n return rightStart - leftStart;\n });\n\n return byStartDateDescending[0];\n}\n"]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Hex } from '@metamask/utils';
|
|
2
|
+
import { PRODUCT_TYPES } from '../types.js';
|
|
3
|
+
import type { RecurringInterval } from '../types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Storage / CHOMP metadata type for cash-subscription delegations.
|
|
6
|
+
*
|
|
7
|
+
* Defined locally so this package does not depend on an unreleased
|
|
8
|
+
* `@metamask/chomp-api-service` intent type. Production CHOMP intent
|
|
9
|
+
* registration still requires a follow-up chomp-api-service release that
|
|
10
|
+
* accepts `'cash-subscription'`.
|
|
11
|
+
*/
|
|
12
|
+
export declare const CASH_SUBSCRIPTION_DELEGATION_TYPE: 'cash-subscription';
|
|
13
|
+
/**
|
|
14
|
+
* Request to prepare a cash-subscription delegation.
|
|
15
|
+
*
|
|
16
|
+
* The service resolves all amount, token, delegate, and trial-duration fields
|
|
17
|
+
* from authoritative pricing held by `SubscriptionController`.
|
|
18
|
+
*
|
|
19
|
+
* Only Money Account Plus is supported; Shield continues to use ERC-20
|
|
20
|
+
* approval rather than delegation.
|
|
21
|
+
*/
|
|
22
|
+
export type PrepareSubscriptionDelegationRequest = {
|
|
23
|
+
product: typeof PRODUCT_TYPES.MONEY_ACCOUNT_PLUS;
|
|
24
|
+
recurringInterval: RecurringInterval;
|
|
25
|
+
payerAddress: Hex;
|
|
26
|
+
/**
|
|
27
|
+
* Whether the user selected the pricing trial. Pricing `trialPeriodDays`
|
|
28
|
+
* only affects the delegation start date when this is true.
|
|
29
|
+
*/
|
|
30
|
+
isTrialRequested: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* When true, gates preparation on a sufficient Money Account balance
|
|
33
|
+
* (`unitAmount × minBillingCyclesForBalance` in mUSD) before side effects.
|
|
34
|
+
*/
|
|
35
|
+
checkBalance?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* When true, skips CHOMP verify/intent interactions. Required for alpha
|
|
38
|
+
* until `@metamask/chomp-api-service` accepts `'cash-subscription'` intent
|
|
39
|
+
* metadata. Defaults to false (production path; unsupported until that
|
|
40
|
+
* follow-up release).
|
|
41
|
+
*/
|
|
42
|
+
skipChompInteractions?: boolean;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Result of {@link SubscriptionDelegationService.prepareDelegation}.
|
|
46
|
+
*/
|
|
47
|
+
export type PreparedSubscriptionDelegation = {
|
|
48
|
+
delegationHash: Hex;
|
|
49
|
+
disposition: 'created' | 'reused';
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Request to check whether a Money Account holds enough convertible mUSD value
|
|
53
|
+
* to cover the subscription funding requirement.
|
|
54
|
+
*/
|
|
55
|
+
export type MoneyAccountBalanceCheckRequest = Pick<PrepareSubscriptionDelegationRequest, 'product' | 'recurringInterval' | 'payerAddress'>;
|
|
56
|
+
/**
|
|
57
|
+
* Result of {@link SubscriptionDelegationService.checkMoneyAccountBalance}.
|
|
58
|
+
* `balance` and `requiredBalance` are mUSD base units (6 decimals).
|
|
59
|
+
*/
|
|
60
|
+
export type MoneyAccountBalanceCheckResult = {
|
|
61
|
+
hasSufficientBalance: boolean;
|
|
62
|
+
balance: string;
|
|
63
|
+
requiredBalance: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Delegation Framework enforcers used by cash-subscription delegations.
|
|
67
|
+
*/
|
|
68
|
+
export type SubscriptionDelegationEnforcers = {
|
|
69
|
+
valueLte: Hex;
|
|
70
|
+
erc20TokenPeriodTransfer: Hex;
|
|
71
|
+
};
|
|
72
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/subscription-delegation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD;;;;;;;GAOG;AACH,eAAO,MAAM,iCAAiC,EAAG,mBAA4B,CAAC;AAE9E;;;;;;;;GAQG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,OAAO,EAAE,OAAO,aAAa,CAAC,kBAAkB,CAAC;IACjD,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,YAAY,EAAE,GAAG,CAAC;IAClB;;;OAGG;IACH,gBAAgB,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;OAKG;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,QAAQ,EAAE,GAAG,CAAC;IACd,wBAAwB,EAAE,GAAG,CAAC;CAC/B,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage / CHOMP metadata type for cash-subscription delegations.
|
|
3
|
+
*
|
|
4
|
+
* Defined locally so this package does not depend on an unreleased
|
|
5
|
+
* `@metamask/chomp-api-service` intent type. Production CHOMP intent
|
|
6
|
+
* registration still requires a follow-up chomp-api-service release that
|
|
7
|
+
* accepts `'cash-subscription'`.
|
|
8
|
+
*/
|
|
9
|
+
export const CASH_SUBSCRIPTION_DELEGATION_TYPE = 'cash-subscription';
|
|
10
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/subscription-delegation/types.ts"],"names":[],"mappings":"AAKA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,mBAA4B,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport { PRODUCT_TYPES } from '../types.js';\nimport type { RecurringInterval } from '../types.js';\n\n/**\n * Storage / CHOMP metadata type for cash-subscription delegations.\n *\n * Defined locally so this package does not depend on an unreleased\n * `@metamask/chomp-api-service` intent type. Production CHOMP intent\n * registration still requires a follow-up chomp-api-service release that\n * accepts `'cash-subscription'`.\n */\nexport const CASH_SUBSCRIPTION_DELEGATION_TYPE = 'cash-subscription' as const;\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/intent interactions. Required for alpha\n * until `@metamask/chomp-api-service` accepts `'cash-subscription'` intent\n * metadata. Defaults to false (production path; unsupported until that\n * follow-up release).\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 valueLte: Hex;\n erc20TokenPeriodTransfer: Hex;\n};\n"]}
|