@metamask/delegation-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,342 @@
1
+ // src/returns.ts
2
+ import { bytesToHex, hexToBytes } from "@metamask/utils";
3
+ var defaultOptions = { out: "hex" };
4
+ function prepareResult(result, options) {
5
+ if (options.out === "hex") {
6
+ const hexValue = typeof result === "string" ? result : bytesToHex(result);
7
+ return hexValue.startsWith("0x") ? hexValue : `0x${hexValue}`;
8
+ }
9
+ const bytesValue = result instanceof Uint8Array ? result : hexToBytes(result);
10
+ return bytesValue;
11
+ }
12
+ var bytesLikeToHex = (bytesLike) => {
13
+ if (typeof bytesLike === "string") {
14
+ return bytesLike;
15
+ }
16
+ return bytesToHex(bytesLike);
17
+ };
18
+ var bytesLikeToBytes = (bytesLike) => {
19
+ if (typeof bytesLike === "string") {
20
+ return hexToBytes(bytesLike);
21
+ }
22
+ return bytesLike;
23
+ };
24
+
25
+ // src/utils.ts
26
+ var toHexString = ({
27
+ value,
28
+ size
29
+ }) => {
30
+ return value.toString(16).padStart(size * 2, "0");
31
+ };
32
+
33
+ // src/caveats/valueLte.ts
34
+ function createValueLteTerms(terms, options = defaultOptions) {
35
+ const { maxValue } = terms;
36
+ if (maxValue < 0n) {
37
+ throw new Error("Invalid maxValue: must be greater than or equal to zero");
38
+ }
39
+ const hexValue = toHexString({ value: maxValue, size: 32 });
40
+ return prepareResult(hexValue, options);
41
+ }
42
+
43
+ // src/caveats/timestamp.ts
44
+ var TIMESTAMP_UPPER_BOUND_SECONDS = 253402300799;
45
+ function createTimestampTerms(terms, encodingOptions = defaultOptions) {
46
+ const { timestampAfterThreshold, timestampBeforeThreshold } = terms;
47
+ if (timestampAfterThreshold < 0) {
48
+ throw new Error(
49
+ "Invalid timestampAfterThreshold: must be zero or positive"
50
+ );
51
+ }
52
+ if (timestampBeforeThreshold < 0) {
53
+ throw new Error(
54
+ "Invalid timestampBeforeThreshold: must be zero or positive"
55
+ );
56
+ }
57
+ if (timestampBeforeThreshold > TIMESTAMP_UPPER_BOUND_SECONDS) {
58
+ throw new Error(
59
+ `Invalid timestampBeforeThreshold: must be less than or equal to ${TIMESTAMP_UPPER_BOUND_SECONDS}`
60
+ );
61
+ }
62
+ if (timestampAfterThreshold > TIMESTAMP_UPPER_BOUND_SECONDS) {
63
+ throw new Error(
64
+ `Invalid timestampAfterThreshold: must be less than or equal to ${TIMESTAMP_UPPER_BOUND_SECONDS}`
65
+ );
66
+ }
67
+ if (timestampBeforeThreshold !== 0 && timestampAfterThreshold >= timestampBeforeThreshold) {
68
+ throw new Error(
69
+ "Invalid thresholds: timestampBeforeThreshold must be greater than timestampAfterThreshold when both are specified"
70
+ );
71
+ }
72
+ const afterThresholdHex = toHexString({
73
+ value: timestampAfterThreshold,
74
+ size: 16
75
+ });
76
+ const beforeThresholdHex = toHexString({
77
+ value: timestampBeforeThreshold,
78
+ size: 16
79
+ });
80
+ const hexValue = `0x${afterThresholdHex}${beforeThresholdHex}`;
81
+ return prepareResult(hexValue, encodingOptions);
82
+ }
83
+
84
+ // src/caveats/nativeTokenPeriodTransfer.ts
85
+ function createNativeTokenPeriodTransferTerms(terms, encodingOptions = defaultOptions) {
86
+ const { periodAmount, periodDuration, startDate } = terms;
87
+ if (periodAmount <= 0n) {
88
+ throw new Error("Invalid periodAmount: must be a positive number");
89
+ }
90
+ if (periodDuration <= 0) {
91
+ throw new Error("Invalid periodDuration: must be a positive number");
92
+ }
93
+ if (startDate <= 0) {
94
+ throw new Error("Invalid startDate: must be a positive number");
95
+ }
96
+ const periodAmountHex = toHexString({ value: periodAmount, size: 32 });
97
+ const periodDurationHex = toHexString({ value: periodDuration, size: 32 });
98
+ const startDateHex = toHexString({ value: startDate, size: 32 });
99
+ const hexValue = `0x${periodAmountHex}${periodDurationHex}${startDateHex}`;
100
+ return prepareResult(hexValue, encodingOptions);
101
+ }
102
+
103
+ // src/caveats/exactCalldata.ts
104
+ function createExactCalldataTerms(terms, encodingOptions = defaultOptions) {
105
+ const { callData } = terms;
106
+ if (typeof callData === "string" && !callData.startsWith("0x")) {
107
+ throw new Error("Invalid callData: must be a hex string starting with 0x");
108
+ }
109
+ return prepareResult(callData, encodingOptions);
110
+ }
111
+
112
+ // src/caveats/nativeTokenStreaming.ts
113
+ var TIMESTAMP_UPPER_BOUND_SECONDS2 = 253402300799;
114
+ function createNativeTokenStreamingTerms(terms, encodingOptions = defaultOptions) {
115
+ const { initialAmount, maxAmount, amountPerSecond, startTime } = terms;
116
+ if (initialAmount < 0n) {
117
+ throw new Error("Invalid initialAmount: must be greater than zero");
118
+ }
119
+ if (maxAmount <= 0n) {
120
+ throw new Error("Invalid maxAmount: must be a positive number");
121
+ }
122
+ if (maxAmount < initialAmount) {
123
+ throw new Error("Invalid maxAmount: must be greater than initialAmount");
124
+ }
125
+ if (amountPerSecond <= 0n) {
126
+ throw new Error("Invalid amountPerSecond: must be a positive number");
127
+ }
128
+ if (startTime <= 0) {
129
+ throw new Error("Invalid startTime: must be a positive number");
130
+ }
131
+ if (startTime > TIMESTAMP_UPPER_BOUND_SECONDS2) {
132
+ throw new Error(
133
+ "Invalid startTime: must be less than or equal to 253402300799"
134
+ );
135
+ }
136
+ const initialAmountHex = toHexString({ value: initialAmount, size: 32 });
137
+ const maxAmountHex = toHexString({ value: maxAmount, size: 32 });
138
+ const amountPerSecondHex = toHexString({ value: amountPerSecond, size: 32 });
139
+ const startTimeHex = toHexString({ value: startTime, size: 32 });
140
+ const hexValue = `0x${initialAmountHex}${maxAmountHex}${amountPerSecondHex}${startTimeHex}`;
141
+ return prepareResult(hexValue, encodingOptions);
142
+ }
143
+
144
+ // src/caveats/erc20Streaming.ts
145
+ import { bytesToHex as bytesToHex2, isHexString } from "@metamask/utils";
146
+ var TIMESTAMP_UPPER_BOUND_SECONDS3 = 253402300799;
147
+ function createERC20StreamingTerms(terms, encodingOptions = defaultOptions) {
148
+ const { tokenAddress, initialAmount, maxAmount, amountPerSecond, startTime } = terms;
149
+ if (!tokenAddress) {
150
+ throw new Error("Invalid tokenAddress: must be a valid address");
151
+ }
152
+ let prefixedTokenAddressHex;
153
+ if (typeof tokenAddress === "string") {
154
+ if (!isHexString(tokenAddress) || tokenAddress.length !== 42) {
155
+ throw new Error("Invalid tokenAddress: must be a valid address");
156
+ }
157
+ prefixedTokenAddressHex = tokenAddress;
158
+ } else {
159
+ if (tokenAddress.length !== 20) {
160
+ throw new Error("Invalid tokenAddress: must be a valid address");
161
+ }
162
+ prefixedTokenAddressHex = bytesToHex2(tokenAddress);
163
+ }
164
+ if (initialAmount < 0n) {
165
+ throw new Error("Invalid initialAmount: must be greater than zero");
166
+ }
167
+ if (maxAmount <= 0n) {
168
+ throw new Error("Invalid maxAmount: must be a positive number");
169
+ }
170
+ if (maxAmount < initialAmount) {
171
+ throw new Error("Invalid maxAmount: must be greater than initialAmount");
172
+ }
173
+ if (amountPerSecond <= 0n) {
174
+ throw new Error("Invalid amountPerSecond: must be a positive number");
175
+ }
176
+ if (startTime <= 0) {
177
+ throw new Error("Invalid startTime: must be a positive number");
178
+ }
179
+ if (startTime > TIMESTAMP_UPPER_BOUND_SECONDS3) {
180
+ throw new Error(
181
+ "Invalid startTime: must be less than or equal to 253402300799"
182
+ );
183
+ }
184
+ const initialAmountHex = toHexString({ value: initialAmount, size: 32 });
185
+ const maxAmountHex = toHexString({ value: maxAmount, size: 32 });
186
+ const amountPerSecondHex = toHexString({ value: amountPerSecond, size: 32 });
187
+ const startTimeHex = toHexString({ value: startTime, size: 32 });
188
+ const hexValue = `${prefixedTokenAddressHex}${initialAmountHex}${maxAmountHex}${amountPerSecondHex}${startTimeHex}`;
189
+ return prepareResult(hexValue, encodingOptions);
190
+ }
191
+
192
+ // src/caveats/erc20TokenPeriodTransfer.ts
193
+ import { isHexString as isHexString2, bytesToHex as bytesToHex3 } from "@metamask/utils";
194
+ function createERC20TokenPeriodTransferTerms(terms, encodingOptions = defaultOptions) {
195
+ const { tokenAddress, periodAmount, periodDuration, startDate } = terms;
196
+ if (!tokenAddress) {
197
+ throw new Error("Invalid tokenAddress: must be a valid address");
198
+ }
199
+ let prefixedTokenAddressHex;
200
+ if (typeof tokenAddress === "string") {
201
+ if (!isHexString2(tokenAddress) || tokenAddress.length !== 42) {
202
+ throw new Error("Invalid tokenAddress: must be a valid address");
203
+ }
204
+ prefixedTokenAddressHex = tokenAddress;
205
+ } else {
206
+ if (tokenAddress.length !== 20) {
207
+ throw new Error("Invalid tokenAddress: must be a valid address");
208
+ }
209
+ prefixedTokenAddressHex = bytesToHex3(tokenAddress);
210
+ }
211
+ if (periodAmount <= 0n) {
212
+ throw new Error("Invalid periodAmount: must be a positive number");
213
+ }
214
+ if (periodDuration <= 0) {
215
+ throw new Error("Invalid periodDuration: must be a positive number");
216
+ }
217
+ if (startDate <= 0) {
218
+ throw new Error("Invalid startDate: must be a positive number");
219
+ }
220
+ const periodAmountHex = toHexString({ value: periodAmount, size: 32 });
221
+ const periodDurationHex = toHexString({ value: periodDuration, size: 32 });
222
+ const startDateHex = toHexString({ value: startDate, size: 32 });
223
+ const hexValue = `${prefixedTokenAddressHex}${periodAmountHex}${periodDurationHex}${startDateHex}`;
224
+ return prepareResult(hexValue, encodingOptions);
225
+ }
226
+
227
+ // src/delegation.ts
228
+ import { encode, encodeSingle, decodeSingle } from "@metamask/abi-utils";
229
+ import { hexToBytes as hexToBytes2 } from "@metamask/utils";
230
+ import { keccak_256 as keccak256 } from "@noble/hashes/sha3";
231
+ var ANY_BENEFICIARY = "0x0000000000000000000000000000000000000a11";
232
+ var ROOT_AUTHORITY = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
233
+ var DELEGATION_TYPEHASH = "0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e";
234
+ var CAVEAT_TYPEHASH = "0x80ad7e1b04ee6d994a125f4714ca0720908bd80ed16063ec8aee4b88e9253e2d";
235
+ var DELEGATION_ARRAY_ABI_TYPES = "(address,address,bytes32,(address,bytes,bytes)[],uint256,bytes)[]";
236
+ function encodeDelegations(delegations, options = defaultOptions) {
237
+ let result;
238
+ if (delegations.length === 0) {
239
+ result = new Uint8Array(64);
240
+ result[31] = 32;
241
+ } else {
242
+ const encodableStructs = delegations.map((struct) => [
243
+ struct.delegate,
244
+ struct.delegator,
245
+ struct.authority,
246
+ struct.caveats.map((caveat) => [
247
+ caveat.enforcer,
248
+ caveat.terms,
249
+ caveat.args
250
+ ]),
251
+ struct.salt,
252
+ struct.signature
253
+ ]);
254
+ result = encodeSingle(DELEGATION_ARRAY_ABI_TYPES, encodableStructs);
255
+ }
256
+ return prepareResult(result, options);
257
+ }
258
+ var delegationFromDecodedDelegation = (decodedDelegation, convertFn) => {
259
+ const [delegate, delegator, authority, caveats, salt, signature] = decodedDelegation;
260
+ return {
261
+ delegate: convertFn(delegate),
262
+ delegator: convertFn(delegator),
263
+ authority: convertFn(authority),
264
+ caveats: caveats.map(([enforcer, terms, args]) => ({
265
+ enforcer: convertFn(enforcer),
266
+ terms: convertFn(terms),
267
+ args: convertFn(args)
268
+ })),
269
+ salt,
270
+ signature: convertFn(signature)
271
+ };
272
+ };
273
+ function decodeDelegations(encoded, options = defaultOptions) {
274
+ const decodedStructs = decodeSingle(
275
+ DELEGATION_ARRAY_ABI_TYPES,
276
+ encoded
277
+ // return types cannot be inferred from complex ABI types, so we must assert the type
278
+ );
279
+ if (options.out === "bytes") {
280
+ return decodedStructs.map(
281
+ (struct) => delegationFromDecodedDelegation(struct, bytesLikeToBytes)
282
+ );
283
+ }
284
+ return decodedStructs.map(
285
+ (struct) => delegationFromDecodedDelegation(struct, bytesLikeToHex)
286
+ );
287
+ }
288
+ function hashDelegation(delegation, options = defaultOptions) {
289
+ const encoded = encode(
290
+ ["bytes32", "address", "address", "bytes32", "bytes32", "uint256"],
291
+ [
292
+ DELEGATION_TYPEHASH,
293
+ delegation.delegate,
294
+ delegation.delegator,
295
+ delegation.authority,
296
+ getCaveatsArrayHash(delegation.caveats),
297
+ delegation.salt
298
+ ]
299
+ );
300
+ const hash = keccak256(encoded);
301
+ return prepareResult(hash, options);
302
+ }
303
+ function getCaveatsArrayHash(caveats) {
304
+ const byteLength = 32 * caveats.length;
305
+ const encoded = new Uint8Array(byteLength);
306
+ for (let i = 0; i < caveats.length; i++) {
307
+ const caveat = caveats[i];
308
+ if (!caveat) {
309
+ throw new Error(`Caveat was undefined at index ${i}`);
310
+ }
311
+ const caveatHash = getCaveatHash(caveat);
312
+ encoded.set(caveatHash, i * 32);
313
+ }
314
+ return keccak256(encoded);
315
+ }
316
+ function getCaveatHash(caveat) {
317
+ const termsBytes = typeof caveat.terms === "string" ? hexToBytes2(caveat.terms) : caveat.terms;
318
+ const termsHash = keccak256(termsBytes);
319
+ const encoded = encode(
320
+ ["bytes32", "address", "bytes32"],
321
+ [CAVEAT_TYPEHASH, caveat.enforcer, termsHash]
322
+ );
323
+ const hash = keccak256(encoded);
324
+ return hash;
325
+ }
326
+ export {
327
+ ANY_BENEFICIARY,
328
+ CAVEAT_TYPEHASH,
329
+ DELEGATION_TYPEHASH,
330
+ ROOT_AUTHORITY,
331
+ createERC20StreamingTerms,
332
+ createERC20TokenPeriodTransferTerms,
333
+ createExactCalldataTerms,
334
+ createNativeTokenPeriodTransferTerms,
335
+ createNativeTokenStreamingTerms,
336
+ createTimestampTerms,
337
+ createValueLteTerms,
338
+ decodeDelegations,
339
+ encodeDelegations,
340
+ hashDelegation
341
+ };
342
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/returns.ts","../src/utils.ts","../src/caveats/valueLte.ts","../src/caveats/timestamp.ts","../src/caveats/nativeTokenPeriodTransfer.ts","../src/caveats/exactCalldata.ts","../src/caveats/nativeTokenStreaming.ts","../src/caveats/erc20Streaming.ts","../src/caveats/erc20TokenPeriodTransfer.ts","../src/delegation.ts"],"sourcesContent":["import { type BytesLike, bytesToHex, hexToBytes } from '@metamask/utils';\n\nimport type { Hex } from './types';\n\n/**\n * The possible return value types for encoding/decoding operations.\n */\nexport type ResultValue = 'hex' | 'bytes';\n\n/**\n * Utility type for function return types based on ResultValue.\n */\nexport type ResultType<TResultValue extends ResultValue> =\n TResultValue extends 'hex' ? Hex : Uint8Array;\n\n/**\n * Base options interface for operations that can return hex or bytes.\n */\nexport type EncodingOptions<TResultValue extends ResultValue> = {\n out: TResultValue;\n};\n\n/**\n * Default options value with proper typing. Use this as your default parameter.\n */\nexport const defaultOptions = { out: 'hex' } as EncodingOptions<any>;\n\n/**\n * Prepares a result by converting between hex and bytes based on options.\n * @param result - The value to convert (either Uint8Array or Hex optionally prefixed with 0x).\n * @param options - The options specifying the desired output format.\n * @returns The converted value with proper type narrowing.\n */\nexport function prepareResult<TResultValue extends ResultValue>(\n result: Uint8Array | Hex | string,\n options: EncodingOptions<TResultValue>,\n): ResultType<TResultValue> {\n if (options.out === 'hex') {\n const hexValue = typeof result === 'string' ? result : bytesToHex(result);\n\n return hexValue.startsWith('0x')\n ? (hexValue as ResultType<TResultValue>)\n : (`0x${hexValue}` as ResultType<TResultValue>);\n }\n const bytesValue = result instanceof Uint8Array ? result : hexToBytes(result);\n return bytesValue as ResultType<TResultValue>;\n}\n\n/**\n * Converts a bytes-like value to a hex string.\n * @param bytesLike - The bytes-like value to convert.\n * @returns The hex string representation of the bytes-like value.\n */\nexport const bytesLikeToHex = (bytesLike: BytesLike) => {\n if (typeof bytesLike === 'string') {\n return bytesLike;\n }\n return bytesToHex(bytesLike);\n};\n\n/**\n * Converts a bytes-like value to a Uint8Array.\n * @param bytesLike - The bytes-like value to convert.\n * @returns The Uint8Array representation of the bytes-like value.\n */\nexport const bytesLikeToBytes = (bytesLike: BytesLike) => {\n if (typeof bytesLike === 'string') {\n return hexToBytes(bytesLike);\n }\n return bytesLike;\n};\n","/**\n * Converts a numeric value to a hexadecimal string with zero-padding, without 0x prefix.\n *\n * @param options - The options for the conversion.\n * @param options.value - The numeric value to convert to hex (bigint or number).\n * @param options.size - The size in bytes for the resulting hex string (each byte = 2 hex characters).\n * @returns A hexadecimal string prefixed with zeros to match the specified size.\n * @example\n * ```typescript\n * toHexString({ value: 255, size: 2 }) // Returns \"00ff\"\n * toHexString({ value: 16n, size: 1 }) // Returns \"10\"\n * ```\n */\nexport const toHexString = ({\n value,\n size,\n}: {\n value: bigint | number;\n size: number;\n}): string => {\n return value.toString(16).padStart(size * 2, '0');\n};\n","import {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\nimport { toHexString } from '../utils';\n\n/**\n * Terms for configuring a ValueLte caveat.\n */\nexport type ValueLteTerms = {\n /** The maximum value allowed for the transaction as a bigint. */\n maxValue: bigint;\n};\n\n/**\n * Creates terms for a ValueLte caveat that limits the maximum value of native tokens that can be spent.\n *\n * @param terms - The terms for the ValueLte caveat.\n * @param options - The encoding options for the result.\n * @returns The terms as a 32-byte hex string.\n * @throws Error if the maxValue is negative.\n */\nexport function createValueLteTerms(\n terms: ValueLteTerms,\n options?: EncodingOptions<'hex'>,\n): Hex;\nexport function createValueLteTerms(\n terms: ValueLteTerms,\n options: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for a ValueLte caveat that limits the maximum value of native tokens that can be spent.\n *\n * @param terms - The terms for the ValueLte caveat.\n * @param options - The encoding options for the result.\n * @returns The terms as a 32-byte hex string.\n * @throws Error if the maxValue is negative.\n */\nexport function createValueLteTerms(\n terms: ValueLteTerms,\n options: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { maxValue } = terms;\n\n if (maxValue < 0n) {\n throw new Error('Invalid maxValue: must be greater than or equal to zero');\n }\n const hexValue = toHexString({ value: maxValue, size: 32 });\n\n return prepareResult(hexValue, options);\n}\n","import {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\nimport { toHexString } from '../utils';\n\n// Upper bound for timestamps (equivalent to January 1, 10000 CE)\nconst TIMESTAMP_UPPER_BOUND_SECONDS = 253402300799;\n\n/**\n * Terms for configuring a timestamp threshold for delegation usage.\n */\nexport type TimestampTerms = {\n /** The timestamp (in seconds) after which the delegation can be used. */\n timestampAfterThreshold: number;\n /** The timestamp (in seconds) before which the delegation can be used. */\n timestampBeforeThreshold: number;\n};\n\n/**\n * Creates terms for a Timestamp caveat that enforces time-based constraints on delegation usage.\n *\n * @param terms - The terms for the Timestamp caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 32-byte hex string (16 bytes for each timestamp).\n * @throws Error if the timestamps are invalid.\n */\nexport function createTimestampTerms(\n terms: TimestampTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createTimestampTerms(\n terms: TimestampTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for a Timestamp caveat that enforces time-based constraints on delegation usage.\n *\n * @param terms - The terms for the Timestamp caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 32-byte hex string (16 bytes for each timestamp).\n * @throws Error if the timestamps are invalid.\n */\nexport function createTimestampTerms(\n terms: TimestampTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { timestampAfterThreshold, timestampBeforeThreshold } = terms;\n\n if (timestampAfterThreshold < 0) {\n throw new Error(\n 'Invalid timestampAfterThreshold: must be zero or positive',\n );\n }\n\n if (timestampBeforeThreshold < 0) {\n throw new Error(\n 'Invalid timestampBeforeThreshold: must be zero or positive',\n );\n }\n\n if (timestampBeforeThreshold > TIMESTAMP_UPPER_BOUND_SECONDS) {\n throw new Error(\n `Invalid timestampBeforeThreshold: must be less than or equal to ${TIMESTAMP_UPPER_BOUND_SECONDS}`,\n );\n }\n\n if (timestampAfterThreshold > TIMESTAMP_UPPER_BOUND_SECONDS) {\n throw new Error(\n `Invalid timestampAfterThreshold: must be less than or equal to ${TIMESTAMP_UPPER_BOUND_SECONDS}`,\n );\n }\n\n if (\n timestampBeforeThreshold !== 0 &&\n timestampAfterThreshold >= timestampBeforeThreshold\n ) {\n throw new Error(\n 'Invalid thresholds: timestampBeforeThreshold must be greater than timestampAfterThreshold when both are specified',\n );\n }\n\n const afterThresholdHex = toHexString({\n value: timestampAfterThreshold,\n size: 16,\n });\n const beforeThresholdHex = toHexString({\n value: timestampBeforeThreshold,\n size: 16,\n });\n\n const hexValue = `0x${afterThresholdHex}${beforeThresholdHex}`;\n\n return prepareResult(hexValue, encodingOptions);\n}\n","import {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\nimport { toHexString } from '../utils';\n\n/**\n * Terms for configuring a periodic transfer allowance of native tokens.\n */\nexport type NativeTokenPeriodTransferTerms = {\n /** The maximum amount that can be transferred within each period (in wei). */\n periodAmount: bigint;\n /** The duration of each period in seconds. */\n periodDuration: number;\n /** Unix timestamp when the first period begins. */\n startDate: number;\n};\n\n/**\n * Creates terms for a NativeTokenPeriodTransfer caveat that validates that native token (ETH) transfers\n * do not exceed a specified amount within a given time period. The transferable amount resets at the\n * beginning of each period, and any unused ETH is forfeited once the period ends.\n *\n * @param terms - The terms for the NativeTokenPeriodTransfer caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 96-byte hex string (32 bytes for each parameter).\n * @throws Error if any of the numeric parameters are invalid.\n */\nexport function createNativeTokenPeriodTransferTerms(\n terms: NativeTokenPeriodTransferTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createNativeTokenPeriodTransferTerms(\n terms: NativeTokenPeriodTransferTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for a NativeTokenPeriodTransfer caveat that validates that native token (ETH) transfers\n * do not exceed a specified amount within a given time period.\n *\n * @param terms - The terms for the NativeTokenPeriodTransfer caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 96-byte hex string (32 bytes for each parameter).\n * @throws Error if any of the numeric parameters are invalid.\n */\nexport function createNativeTokenPeriodTransferTerms(\n terms: NativeTokenPeriodTransferTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { periodAmount, periodDuration, startDate } = terms;\n\n if (periodAmount <= 0n) {\n throw new Error('Invalid periodAmount: must be a positive number');\n }\n\n if (periodDuration <= 0) {\n throw new Error('Invalid periodDuration: must be a positive number');\n }\n\n if (startDate <= 0) {\n throw new Error('Invalid startDate: must be a positive number');\n }\n\n const periodAmountHex = toHexString({ value: periodAmount, size: 32 });\n const periodDurationHex = toHexString({ value: periodDuration, size: 32 });\n const startDateHex = toHexString({ value: startDate, size: 32 });\n\n const hexValue = `0x${periodAmountHex}${periodDurationHex}${startDateHex}`;\n\n return prepareResult(hexValue, encodingOptions);\n}\n","import type { BytesLike } from '@metamask/utils';\n\nimport {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\n\n/**\n * Terms for configuring an ExactCalldata caveat.\n */\nexport type ExactCalldataTerms = {\n /** The expected calldata to match against. */\n callData: BytesLike;\n};\n\n/**\n * Creates terms for an ExactCalldata caveat that ensures the provided execution calldata\n * matches exactly the expected calldata.\n *\n * @param terms - The terms for the ExactCalldata caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as the calldata itself.\n * @throws Error if the `callData` is invalid.\n */\nexport function createExactCalldataTerms(\n terms: ExactCalldataTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createExactCalldataTerms(\n terms: ExactCalldataTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for an ExactCalldata caveat that ensures the provided execution calldata\n * matches exactly the expected calldata.\n * @param terms - The terms for the ExactCalldata caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as the calldata itself.\n * @throws Error if the `callData` is invalid.\n */\nexport function createExactCalldataTerms(\n terms: ExactCalldataTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { callData } = terms;\n\n if (typeof callData === 'string' && !callData.startsWith('0x')) {\n throw new Error('Invalid callData: must be a hex string starting with 0x');\n }\n\n // For exact calldata, the terms are simply the expected calldata\n return prepareResult(callData, encodingOptions);\n}\n","import {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\nimport { toHexString } from '../utils';\n\n// Upper bound for timestamps (January 1, 10000 CE)\nconst TIMESTAMP_UPPER_BOUND_SECONDS = 253402300799;\n\n/**\n * Terms for configuring a linear streaming allowance of native tokens.\n */\nexport type NativeTokenStreamingTerms = {\n /** The initial amount available immediately (in wei). */\n initialAmount: bigint;\n /** The maximum total amount that can be transferred (in wei). */\n maxAmount: bigint;\n /** The rate at which allowance increases per second (in wei). */\n amountPerSecond: bigint;\n /** Unix timestamp when streaming begins. */\n startTime: number;\n};\n\n/**\n * Creates terms for the NativeTokenStreaming caveat, configuring a linear\n * streaming allowance of native tokens.\n *\n * @param terms - The terms for the NativeTokenStreaming caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns Hex-encoded terms for the caveat (128 bytes).\n * @throws Error if initialAmount is negative.\n * @throws Error if maxAmount is not positive.\n * @throws Error if maxAmount is less than initialAmount.\n * @throws Error if amountPerSecond is not positive.\n * @throws Error if startTime is not positive.\n * @throws Error if startTime exceeds upper bound.\n */\nexport function createNativeTokenStreamingTerms(\n terms: NativeTokenStreamingTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createNativeTokenStreamingTerms(\n terms: NativeTokenStreamingTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for the NativeTokenStreaming caveat, configuring a linear\n * streaming allowance of native tokens.\n *\n * @param terms - The terms for the NativeTokenStreaming caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 128-byte hex string.\n * @throws Error if any of the numeric parameters are invalid.\n */\nexport function createNativeTokenStreamingTerms(\n terms: NativeTokenStreamingTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { initialAmount, maxAmount, amountPerSecond, startTime } = terms;\n\n if (initialAmount < 0n) {\n throw new Error('Invalid initialAmount: must be greater than zero');\n }\n\n if (maxAmount <= 0n) {\n throw new Error('Invalid maxAmount: must be a positive number');\n }\n\n if (maxAmount < initialAmount) {\n throw new Error('Invalid maxAmount: must be greater than initialAmount');\n }\n\n if (amountPerSecond <= 0n) {\n throw new Error('Invalid amountPerSecond: must be a positive number');\n }\n\n if (startTime <= 0) {\n throw new Error('Invalid startTime: must be a positive number');\n }\n\n if (startTime > TIMESTAMP_UPPER_BOUND_SECONDS) {\n throw new Error(\n 'Invalid startTime: must be less than or equal to 253402300799',\n );\n }\n\n const initialAmountHex = toHexString({ value: initialAmount, size: 32 });\n const maxAmountHex = toHexString({ value: maxAmount, size: 32 });\n const amountPerSecondHex = toHexString({ value: amountPerSecond, size: 32 });\n const startTimeHex = toHexString({ value: startTime, size: 32 });\n\n const hexValue = `0x${initialAmountHex}${maxAmountHex}${amountPerSecondHex}${startTimeHex}`;\n\n return prepareResult(hexValue, encodingOptions);\n}\n","import { type BytesLike, bytesToHex, isHexString } from '@metamask/utils';\n\nimport {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\nimport { toHexString } from '../utils';\n\n// Upper bound for timestamps (January 1, 10000 CE)\nconst TIMESTAMP_UPPER_BOUND_SECONDS = 253402300799;\n\n/**\n * Terms for configuring a linear streaming allowance of ERC20 tokens.\n */\nexport type ERC20StreamingTerms = {\n /** The address of the ERC20 token contract. */\n tokenAddress: BytesLike;\n /** The initial amount available immediately. */\n initialAmount: bigint;\n /** The maximum total amount that can be transferred. */\n maxAmount: bigint;\n /** The rate at which allowance increases per second. */\n amountPerSecond: bigint;\n /** Unix timestamp when streaming begins. */\n startTime: number;\n};\n\n/**\n * Creates terms for the ERC20Streaming caveat, configuring a linear\n * streaming allowance of ERC20 tokens.\n *\n * @param terms - The terms for the ERC20Streaming caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns Hex-encoded terms for the caveat (160 bytes).\n * @throws Error if tokenAddress is invalid.\n * @throws Error if initialAmount is negative.\n * @throws Error if maxAmount is not positive.\n * @throws Error if maxAmount is less than initialAmount.\n * @throws Error if amountPerSecond is not positive.\n * @throws Error if startTime is not positive.\n * @throws Error if startTime exceeds upper bound.\n */\nexport function createERC20StreamingTerms(\n terms: ERC20StreamingTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createERC20StreamingTerms(\n terms: ERC20StreamingTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for the ERC20Streaming caveat, configuring a linear\n * streaming allowance of ERC20 tokens.\n *\n * @param terms - The terms for the ERC20Streaming caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 160-byte hex string.\n * @throws Error if any of the parameters are invalid.\n */\nexport function createERC20StreamingTerms(\n terms: ERC20StreamingTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { tokenAddress, initialAmount, maxAmount, amountPerSecond, startTime } =\n terms;\n\n if (!tokenAddress) {\n throw new Error('Invalid tokenAddress: must be a valid address');\n }\n\n let prefixedTokenAddressHex: string;\n\n if (typeof tokenAddress === 'string') {\n if (!isHexString(tokenAddress) || tokenAddress.length !== 42) {\n throw new Error('Invalid tokenAddress: must be a valid address');\n }\n prefixedTokenAddressHex = tokenAddress;\n } else {\n if (tokenAddress.length !== 20) {\n throw new Error('Invalid tokenAddress: must be a valid address');\n }\n prefixedTokenAddressHex = bytesToHex(tokenAddress);\n }\n\n if (initialAmount < 0n) {\n throw new Error('Invalid initialAmount: must be greater than zero');\n }\n\n if (maxAmount <= 0n) {\n throw new Error('Invalid maxAmount: must be a positive number');\n }\n\n if (maxAmount < initialAmount) {\n throw new Error('Invalid maxAmount: must be greater than initialAmount');\n }\n\n if (amountPerSecond <= 0n) {\n throw new Error('Invalid amountPerSecond: must be a positive number');\n }\n\n if (startTime <= 0) {\n throw new Error('Invalid startTime: must be a positive number');\n }\n\n if (startTime > TIMESTAMP_UPPER_BOUND_SECONDS) {\n throw new Error(\n 'Invalid startTime: must be less than or equal to 253402300799',\n );\n }\n\n const initialAmountHex = toHexString({ value: initialAmount, size: 32 });\n const maxAmountHex = toHexString({ value: maxAmount, size: 32 });\n const amountPerSecondHex = toHexString({ value: amountPerSecond, size: 32 });\n const startTimeHex = toHexString({ value: startTime, size: 32 });\n\n const hexValue = `${prefixedTokenAddressHex}${initialAmountHex}${maxAmountHex}${amountPerSecondHex}${startTimeHex}`;\n\n return prepareResult(hexValue, encodingOptions);\n}\n","import { type BytesLike, isHexString, bytesToHex } from '@metamask/utils';\n\nimport {\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\nimport { toHexString } from '../utils';\n\n/**\n * Terms for configuring a periodic transfer allowance of ERC20 tokens.\n */\nexport type ERC20TokenPeriodTransferTerms = {\n /** The address of the ERC20 token. */\n tokenAddress: BytesLike;\n /** The maximum amount that can be transferred within each period. */\n periodAmount: bigint;\n /** The duration of each period in seconds. */\n periodDuration: number;\n /** Unix timestamp when the first period begins. */\n startDate: number;\n};\n\n/**\n * Creates terms for an ERC20TokenPeriodTransfer caveat that validates that ERC20 token transfers\n * do not exceed a specified amount within a given time period. The transferable amount resets at the\n * beginning of each period, and any unused tokens are forfeited once the period ends.\n *\n * @param terms - The terms for the ERC20TokenPeriodTransfer caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 128-byte hex string (32 bytes for each parameter).\n * @throws Error if any of the numeric parameters are invalid.\n */\nexport function createERC20TokenPeriodTransferTerms(\n terms: ERC20TokenPeriodTransferTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createERC20TokenPeriodTransferTerms(\n terms: ERC20TokenPeriodTransferTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for an ERC20TokenPeriodTransfer caveat that validates that ERC20 token transfers\n * do not exceed a specified amount within a given time period.\n *\n * @param terms - The terms for the ERC20TokenPeriodTransfer caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 128-byte hex string (32 bytes for each parameter).\n * @throws Error if any of the numeric parameters are invalid.\n */\nexport function createERC20TokenPeriodTransferTerms(\n terms: ERC20TokenPeriodTransferTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { tokenAddress, periodAmount, periodDuration, startDate } = terms;\n\n if (!tokenAddress) {\n throw new Error('Invalid tokenAddress: must be a valid address');\n }\n\n let prefixedTokenAddressHex: string;\n\n if (typeof tokenAddress === 'string') {\n if (!isHexString(tokenAddress) || tokenAddress.length !== 42) {\n throw new Error('Invalid tokenAddress: must be a valid address');\n }\n prefixedTokenAddressHex = tokenAddress;\n } else {\n if (tokenAddress.length !== 20) {\n throw new Error('Invalid tokenAddress: must be a valid address');\n }\n prefixedTokenAddressHex = bytesToHex(tokenAddress);\n }\n\n if (periodAmount <= 0n) {\n throw new Error('Invalid periodAmount: must be a positive number');\n }\n\n if (periodDuration <= 0) {\n throw new Error('Invalid periodDuration: must be a positive number');\n }\n\n if (startDate <= 0) {\n throw new Error('Invalid startDate: must be a positive number');\n }\n\n const periodAmountHex = toHexString({ value: periodAmount, size: 32 });\n const periodDurationHex = toHexString({ value: periodDuration, size: 32 });\n const startDateHex = toHexString({ value: startDate, size: 32 });\n\n const hexValue = `${prefixedTokenAddressHex}${periodAmountHex}${periodDurationHex}${startDateHex}`;\n\n return prepareResult(hexValue, encodingOptions);\n}\n","import { encode, encodeSingle, decodeSingle } from '@metamask/abi-utils';\nimport { hexToBytes, type BytesLike } from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nimport {\n bytesLikeToBytes,\n bytesLikeToHex,\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from './returns';\nimport type { CaveatStruct, DelegationStruct, Hex } from './types';\n\n/**\n * When designated as the delegate address in a delegation, this allows any beneficiary to redeem the delegation.\n */\nexport const ANY_BENEFICIARY = '0x0000000000000000000000000000000000000a11';\n\n/**\n * To be used on a delegation as the root authority.\n */\nexport const ROOT_AUTHORITY =\n '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';\n\n/**\n * The typehash for a delegation, used when generating a delegation hash.\n *\n * keccak('Delegation(address delegate,address delegator,bytes32 authority,Caveat[] caveats,uint256 salt)Caveat(address enforcer,bytes terms)')\n */\nexport const DELEGATION_TYPEHASH =\n '0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e';\n\n/**\n * The typehash for a caveat, used when generating a caveat hash.\n *\n * keccak('Caveat(address enforcer,bytes terms)')\n */\nexport const CAVEAT_TYPEHASH =\n '0x80ad7e1b04ee6d994a125f4714ca0720908bd80ed16063ec8aee4b88e9253e2d';\n\n/**\n * The ABI types for an array of delegations.\n */\nconst DELEGATION_ARRAY_ABI_TYPES =\n '(address,address,bytes32,(address,bytes,bytes)[],uint256,bytes)[]' as const;\n\n/**\n * Encodes an array of delegations into a permission context.\n * @param delegations - The delegations to encode.\n * @param options - Encoding options. Defaults to { out: 'hex' }.\n * @returns The encoded delegations as a hex string (default) or Uint8Array.\n */\nexport function encodeDelegations(\n delegations: DelegationStruct[],\n options?: EncodingOptions<'hex'>,\n): Hex;\nexport function encodeDelegations(\n delegations: DelegationStruct[],\n options: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Encodes an array of delegations into a permission context.\n * @param delegations - The delegations to encode.\n * @param options - Encoding options. Defaults to { out: 'hex' }.\n * @returns The encoded delegations as a hex string (default) or Uint8Array.\n */\nexport function encodeDelegations(\n delegations: DelegationStruct[],\n options: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n let result: Uint8Array;\n\n if (delegations.length === 0) {\n // short circuit for empty delegations, derived from\n // `encode(['(address,address,bytes32,(address,bytes,bytes)[],uint256,bytes)[]'],[[]],);`\n result = new Uint8Array(64);\n result[31] = 0x20;\n } else {\n const encodableStructs = delegations.map((struct) => [\n struct.delegate,\n struct.delegator,\n struct.authority,\n struct.caveats.map((caveat) => [\n caveat.enforcer,\n caveat.terms,\n caveat.args,\n ]),\n struct.salt,\n struct.signature,\n ]);\n\n result = encodeSingle(DELEGATION_ARRAY_ABI_TYPES, encodableStructs);\n }\n\n return prepareResult(result, options);\n}\n\n/**\n * Converts a decoded delegation struct to a delegation object using the provided conversion function.\n * @param decodedDelegation - The decoded delegation struct as a tuple.\n * @param convertFn - Function to convert BytesLike values to the desired output type.\n * @returns A delegation object with all bytes-like values converted using the provided function.\n */\nconst delegationFromDecodedDelegation = <TEncoding extends BytesLike>(\n decodedDelegation: DecodedDelegation,\n convertFn: (value: BytesLike) => TEncoding,\n): DelegationStruct<TEncoding> => {\n const [delegate, delegator, authority, caveats, salt, signature] =\n decodedDelegation;\n\n return {\n delegate: convertFn(delegate),\n delegator: convertFn(delegator),\n authority: convertFn(authority),\n caveats: caveats.map(([enforcer, terms, args]) => ({\n enforcer: convertFn(enforcer),\n terms: convertFn(terms),\n args: convertFn(args),\n })),\n salt,\n signature: convertFn(signature),\n };\n};\n\n/**\n * Represents a decoded delegation as a tuple structure.\n * This type defines the structure of a delegation after it has been decoded from\n * an encoded format.\n */\ntype DecodedDelegation = [\n BytesLike,\n BytesLike,\n BytesLike,\n [BytesLike, BytesLike, BytesLike][],\n bigint,\n BytesLike,\n];\n\n/**\n * Decodes an encoded permission context back into an array of delegations.\n * @param encoded - The encoded delegations as a hex string or Uint8Array.\n * @param options - Encoding options. Defaults to { out: 'hex' }.\n * @returns The decoded delegations array with types resolved based on options.\n */\nexport function decodeDelegations(\n encoded: BytesLike,\n options?: EncodingOptions<'hex'>,\n): DelegationStruct<Hex>[];\nexport function decodeDelegations(\n encoded: BytesLike,\n options: EncodingOptions<'bytes'>,\n): DelegationStruct<Uint8Array>[];\n/**\n * Decodes an encoded permission context back into an array of delegations.\n * @param encoded - The encoded delegations as a hex string or Uint8Array.\n * @param options - Encoding options. Defaults to { out: 'hex' }.\n * @returns The decoded delegations array with types resolved based on options.\n */\nexport function decodeDelegations(\n encoded: BytesLike,\n options: EncodingOptions<ResultValue> = defaultOptions,\n): DelegationStruct<Hex>[] | DelegationStruct<Uint8Array>[] {\n // it's possible to short circuit for empty delegations, but due to the\n // complexity of the input type, and the relative infrequency of empty delegations,\n // it's not worthwhile.\n\n const decodedStructs = decodeSingle(\n DELEGATION_ARRAY_ABI_TYPES,\n encoded,\n // return types cannot be inferred from complex ABI types, so we must assert the type\n ) as DecodedDelegation[];\n\n if (options.out === 'bytes') {\n return decodedStructs.map((struct) =>\n delegationFromDecodedDelegation(struct, bytesLikeToBytes),\n );\n }\n return decodedStructs.map((struct) =>\n delegationFromDecodedDelegation(struct, bytesLikeToHex),\n );\n}\n\n/**\n * Calculates the hash of a delegation for signing purposes.\n * The hash is computed by encoding the delegation parameters with the delegation typehash\n * and then applying keccak256 hashing.\n *\n * @param delegation - The delegation to hash.\n * @param options - Encoding options. Defaults to { out: 'hex' }.\n * @returns The keccak256 hash of the encoded delegation as a hex string (default) or Uint8Array.\n */\nexport function hashDelegation(\n delegation: DelegationStruct,\n options?: EncodingOptions<'hex'>,\n): Hex;\nexport function hashDelegation(\n delegation: DelegationStruct,\n options: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Calculates the hash of a delegation for signing purposes.\n * The hash is computed by encoding the delegation parameters with the delegation typehash\n * and then applying keccak256 hashing.\n *\n * @param delegation - The delegation to hash.\n * @param options - Encoding options. Defaults to { out: 'hex' }.\n * @returns The keccak256 hash of the encoded delegation as a hex string (default) or Uint8Array.\n */\nexport function hashDelegation(\n delegation: DelegationStruct,\n options: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const encoded = encode(\n ['bytes32', 'address', 'address', 'bytes32', 'bytes32', 'uint256'],\n [\n DELEGATION_TYPEHASH,\n delegation.delegate,\n delegation.delegator,\n delegation.authority,\n getCaveatsArrayHash(delegation.caveats),\n delegation.salt,\n ],\n );\n const hash = keccak256(encoded);\n return prepareResult(hash, options);\n}\n\n/**\n * Calculates the hash of an array of caveats. The caveats are individually abi\n * encoded and hashed, and concatenated. The resulting byte array is then\n * hashed to produce the CaveatsArrayHash.\n *\n * @param caveats - The array of caveats to hash.\n * @returns The keccak256 hash of the encoded caveat array.\n */\nfunction getCaveatsArrayHash(caveats: CaveatStruct[]): Uint8Array {\n const byteLength = 32 * caveats.length;\n const encoded = new Uint8Array(byteLength);\n\n for (let i = 0; i < caveats.length; i++) {\n const caveat = caveats[i];\n if (!caveat) {\n throw new Error(`Caveat was undefined at index ${i}`);\n }\n const caveatHash = getCaveatHash(caveat);\n encoded.set(caveatHash, i * 32);\n }\n\n return keccak256(encoded);\n}\n\n/**\n * Calculates the hash of a single caveat.\n * @param caveat - The caveat to hash.\n * @returns The keccak256 hash of the encoded caveat.\n */\nfunction getCaveatHash(caveat: CaveatStruct): Uint8Array {\n const termsBytes =\n typeof caveat.terms === 'string' ? hexToBytes(caveat.terms) : caveat.terms;\n\n const termsHash = keccak256(termsBytes);\n\n const encoded = encode(\n ['bytes32', 'address', 'bytes32'],\n [CAVEAT_TYPEHASH, caveat.enforcer, termsHash],\n );\n const hash = keccak256(encoded);\n return hash;\n}\n"],"mappings":";AAAA,SAAyB,YAAY,kBAAkB;AAyBhD,IAAM,iBAAiB,EAAE,KAAK,MAAM;AAQpC,SAAS,cACd,QACA,SAC0B;AAC1B,MAAI,QAAQ,QAAQ,OAAO;AACzB,UAAM,WAAW,OAAO,WAAW,WAAW,SAAS,WAAW,MAAM;AAExE,WAAO,SAAS,WAAW,IAAI,IAC1B,WACA,KAAK,QAAQ;AAAA,EACpB;AAC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M,SAAS,QAAQ,CAAC;AACxB,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,iCAAiC,CAAC,EAAE;AAAA,IACtD;AACA,UAAM,aAAa,cAAc,MAAM;AACvC,YAAQ,IAAI,YAAY,IAAI,EAAE;AAAA,EAChC;AAEA,SAAO,UAAU,OAAO;AAC1B;AAOA,SAAS,cAAc,QAAkC;AACvD,QAAM,aACJ,OAAO,OAAO,UAAU,WAAWC,YAAW,OAAO,KAAK,IAAI,OAAO;AAEvE,QAAM,YAAY,UAAU,UAAU;AAEtC,QAAM,UAAU;AAAA,IACd,CAAC,WAAW,WAAW,SAAS;AAAA,IAChC,CAAC,iBAAiB,OAAO,UAAU,SAAS;AAAA,EAC9C;AACA,QAAM,OAAO,UAAU,OAAO;AAC9B,SAAO;AACT;","names":["TIMESTAMP_UPPER_BOUND_SECONDS","bytesToHex","TIMESTAMP_UPPER_BOUND_SECONDS","bytesToHex","isHexString","bytesToHex","isHexString","bytesToHex","hexToBytes","hexToBytes"]}
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "@metamask/delegation-core",
3
+ "version": "0.1.0",
4
+ "description": "Low level core functionality for interacting with the Delegation Framework",
5
+ "license": "(MIT-0 OR Apache-2.0)",
6
+ "keywords": [
7
+ "MetaMask",
8
+ "Ethereum"
9
+ ],
10
+ "homepage": "https://github.com/metamask/delegation-toolkit/tree/main/packages/delegation-core#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/metamask/delegation-toolkit/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/metamask/delegation-toolkit.git"
17
+ },
18
+ "author": "MetaMask <hello@metamask.io>",
19
+ "sideEffects": false,
20
+ "contributors": [],
21
+ "main": "./dist/index.js",
22
+ "module": "./dist/index.mjs",
23
+ "types": "./dist/index.d.ts",
24
+ "files": [
25
+ "dist/**",
26
+ "dist/"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "require": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "import": {
35
+ "types": "./dist/index.d.mts",
36
+ "default": "./dist/index.mjs"
37
+ }
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "engines": {
42
+ "node": "^18.18 || >=20"
43
+ },
44
+ "scripts": {
45
+ "build": "yarn typecheck && tsup",
46
+ "typecheck": "tsc --noEmit",
47
+ "test": "vitest run",
48
+ "test:watch": "vitest",
49
+ "changelog:update": "../../scripts/update-changelog.sh @metamask/delegation-core",
50
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/delegation-core",
51
+ "clean": "rm -rf dist",
52
+ "lint": "yarn lint:eslint",
53
+ "lint:complete": "yarn lint:eslint && yarn lint:constraints && yarn lint:misc --check && yarn lint:dependencies --check && yarn lint:changelog",
54
+ "lint:changelog": "auto-changelog validate --prettier",
55
+ "lint:constraints": "yarn constraints",
56
+ "lint:dependencies": "depcheck && yarn dedupe",
57
+ "lint:eslint": "eslint . --cache --ext js,ts",
58
+ "lint:fix": "yarn lint:eslint --fix && yarn lint:constraints --fix && yarn lint:misc --write && yarn lint:dependencies && yarn lint:changelog",
59
+ "lint:misc": "prettier '**/*.json' '**/*.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public",
63
+ "registry": "https://registry.npmjs.org/"
64
+ },
65
+ "devDependencies": {
66
+ "@metamask/auto-changelog": "^3.4.4",
67
+ "@types/node": "^20.10.6",
68
+ "tsup": "^7.2.0",
69
+ "typescript": "5.0.4",
70
+ "vitest": "^2.1.9"
71
+ },
72
+ "dependencies": {
73
+ "@metamask/abi-utils": "^3.0.0",
74
+ "@metamask/utils": "^11.4.0",
75
+ "@noble/hashes": "^1.8.0"
76
+ }
77
+ }