@metamask/delegation-core 0.1.0 → 0.2.0-rc.1

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 CHANGED
@@ -7,11 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.0-rc.1]
11
+
12
+ ### Added
13
+
14
+ - Added a Nonce caveat enforcer terms builder `createNonceTerms` ([#44](https://github.com/metamask/delegation-toolkit/pull/44))
15
+
16
+ ### Changed
17
+
18
+ - The configuration parameter `callData` is now `calldata` in `createExactCalldataTerms` argument type. ([#24](https://github.com/metamask/delegation-toolkit/pull/24))
19
+ - The package is explictly marked as ESM via `type: module`; with CJS compatibility maintained with dual export. ([#27](https://github.com/metamask/delegation-toolkit/pull/27))
20
+
10
21
  ## [0.1.0]
11
22
 
12
23
  ### Changed
13
24
 
14
25
  - Add @metamask/delegation-core package, providing utility types, delegation hashing, and terms encoding for a limited set of caveat enforcers.
15
26
 
16
- [Unreleased]: https://github.com/metamask/delegation-toolkit/compare/@metamask/delegation-core@0.1.0...HEAD
27
+ [Unreleased]: https://github.com/metamask/delegation-toolkit/compare/@metamask/delegation-core@0.2.0-rc.1...HEAD
28
+ [0.2.0-rc.1]: https://github.com/metamask/delegation-toolkit/compare/@metamask/delegation-core@0.1.0...@metamask/delegation-core@0.2.0-rc.1
17
29
  [0.1.0]: https://github.com/metamask/delegation-toolkit/releases/tag/@metamask/delegation-core@0.1.0
package/README.md CHANGED
@@ -17,6 +17,7 @@ yarn add @metamask/delegation-core
17
17
  ## Overview
18
18
 
19
19
  This package provides utilities for:
20
+
20
21
  - Creating caveat terms for various delegation constraints
21
22
  - Encoding and decoding delegations
22
23
  - Type definitions for delegation structures
@@ -32,6 +33,7 @@ Caveat terms builders create encoded parameters for different types of delegatio
32
33
  Creates terms for a ValueLte caveat that limits the maximum value of native tokens that can be spent.
33
34
 
34
35
  **Parameters:**
36
+
35
37
  - `terms: ValueLteTerms`
36
38
  - `maxValue: bigint` - The maximum value allowed for the transaction
37
39
  - `options?: EncodingOptions` - Optional encoding options (`'hex'` | `'bytes'`)
@@ -39,19 +41,23 @@ Creates terms for a ValueLte caveat that limits the maximum value of native toke
39
41
  **Returns:** `Hex | Uint8Array` - 32-byte encoded terms
40
42
 
41
43
  **Example:**
44
+
42
45
  ```typescript
43
46
  import { createValueLteTerms } from '@metamask/delegation-core';
44
47
 
45
48
  // Limit to 1 ETH maximum
46
49
  const terms = createValueLteTerms({
47
- maxValue: 1000000000000000000n // 1 ETH in wei
50
+ maxValue: 1000000000000000000n, // 1 ETH in wei
48
51
  });
49
52
  // Returns: '0x0000000000000000000000000000000000000000000000000de0b6b3a7640000'
50
53
 
51
54
  // Get as Uint8Array
52
- const bytesTerms = createValueLteTerms({
53
- maxValue: 1000000000000000000n
54
- }, { out: 'bytes' });
55
+ const bytesTerms = createValueLteTerms(
56
+ {
57
+ maxValue: 1000000000000000000n,
58
+ },
59
+ { out: 'bytes' },
60
+ );
55
61
  ```
56
62
 
57
63
  #### `createTimestampTerms(terms, options?)`
@@ -59,6 +65,7 @@ const bytesTerms = createValueLteTerms({
59
65
  Creates terms for a Timestamp caveat that enforces time-based constraints on delegation usage.
60
66
 
61
67
  **Parameters:**
68
+
62
69
  - `terms: TimestampTerms`
63
70
  - `timestampAfterThreshold: number` - Timestamp (seconds) after which delegation can be used
64
71
  - `timestampBeforeThreshold: number` - Timestamp (seconds) before which delegation can be used
@@ -67,19 +74,20 @@ Creates terms for a Timestamp caveat that enforces time-based constraints on del
67
74
  **Returns:** `Hex | Uint8Array` - 32-byte encoded terms (16 bytes per timestamp)
68
75
 
69
76
  **Example:**
77
+
70
78
  ```typescript
71
79
  import { createTimestampTerms } from '@metamask/delegation-core';
72
80
 
73
81
  // Valid between Jan 1, 2022 and Jan 1, 2023
74
82
  const terms = createTimestampTerms({
75
- timestampAfterThreshold: 1640995200, // 2022-01-01 00:00:00 UTC
76
- timestampBeforeThreshold: 1672531200 // 2023-01-01 00:00:00 UTC
83
+ timestampAfterThreshold: 1640995200, // 2022-01-01 00:00:00 UTC
84
+ timestampBeforeThreshold: 1672531200, // 2023-01-01 00:00:00 UTC
77
85
  });
78
86
 
79
87
  // Only valid after a certain time (no end time)
80
88
  const openEndedTerms = createTimestampTerms({
81
89
  timestampAfterThreshold: 1640995200,
82
- timestampBeforeThreshold: 0
90
+ timestampBeforeThreshold: 0,
83
91
  });
84
92
  ```
85
93
 
@@ -88,24 +96,27 @@ const openEndedTerms = createTimestampTerms({
88
96
  Creates terms for an ExactCalldata caveat that ensures execution calldata matches exactly.
89
97
 
90
98
  **Parameters:**
99
+
91
100
  - `terms: ExactCalldataTerms`
92
- - `callData: BytesLike` - The expected calldata (hex string or Uint8Array)
101
+ - `calldata: BytesLike` - The expected calldata (hex string or Uint8Array)
93
102
  - `options?: EncodingOptions` - Optional encoding options
94
103
 
95
104
  **Returns:** `Hex | Uint8Array` - The calldata itself (variable length)
96
105
 
97
106
  **Example:**
107
+
98
108
  ```typescript
99
109
  import { createExactCalldataTerms } from '@metamask/delegation-core';
100
110
 
101
111
  // Exact calldata for a specific function call
102
112
  const terms = createExactCalldataTerms({
103
- callData: '0xa9059cbb000000000000000000000000742d35cc6634c0532925a3b8d40ec49b0e8baa5e0000000000000000000000000000000000000000000000000de0b6b3a7640000'
113
+ calldata:
114
+ '0xa9059cbb000000000000000000000000742d35cc6634c0532925a3b8d40ec49b0e8baa5e0000000000000000000000000000000000000000000000000de0b6b3a7640000',
104
115
  });
105
116
 
106
117
  // From Uint8Array
107
118
  const terms2 = createExactCalldataTerms({
108
- callData: new Uint8Array([0xa9, 0x05, 0x9c, 0xbb, /* ... */])
119
+ calldata: new Uint8Array([0xa9, 0x05, 0x9c, 0xbb /* ... */]),
109
120
  });
110
121
  ```
111
122
 
@@ -114,6 +125,7 @@ const terms2 = createExactCalldataTerms({
114
125
  Creates terms for periodic native token transfer limits with time-based resets.
115
126
 
116
127
  **Parameters:**
128
+
117
129
  - `terms: NativeTokenPeriodTransferTerms`
118
130
  - `periodAmount: bigint` - Maximum amount transferable per period (wei)
119
131
  - `periodDuration: number` - Duration of each period (seconds)
@@ -123,14 +135,15 @@ Creates terms for periodic native token transfer limits with time-based resets.
123
135
  **Returns:** `Hex | Uint8Array` - 96-byte encoded terms (32 bytes per parameter)
124
136
 
125
137
  **Example:**
138
+
126
139
  ```typescript
127
140
  import { createNativeTokenPeriodTransferTerms } from '@metamask/delegation-core';
128
141
 
129
142
  // Allow 1 ETH per day starting from a specific date
130
143
  const terms = createNativeTokenPeriodTransferTerms({
131
- periodAmount: 1000000000000000000n, // 1 ETH in wei
132
- periodDuration: 86400, // 24 hours in seconds
133
- startDate: 1640995200 // 2022-01-01 00:00:00 UTC
144
+ periodAmount: 1000000000000000000n, // 1 ETH in wei
145
+ periodDuration: 86400, // 24 hours in seconds
146
+ startDate: 1640995200, // 2022-01-01 00:00:00 UTC
134
147
  });
135
148
  ```
136
149
 
@@ -139,6 +152,7 @@ const terms = createNativeTokenPeriodTransferTerms({
139
152
  Creates terms for linear streaming allowance of native tokens.
140
153
 
141
154
  **Parameters:**
155
+
142
156
  - `terms: NativeTokenStreamingTerms`
143
157
  - `initialAmount: bigint` - Amount available immediately (wei)
144
158
  - `maxAmount: bigint` - Maximum total transferable amount (wei)
@@ -149,15 +163,16 @@ Creates terms for linear streaming allowance of native tokens.
149
163
  **Returns:** `Hex | Uint8Array` - 128-byte encoded terms (32 bytes per parameter)
150
164
 
151
165
  **Example:**
166
+
152
167
  ```typescript
153
168
  import { createNativeTokenStreamingTerms } from '@metamask/delegation-core';
154
169
 
155
170
  // Stream 0.5 ETH per second, starting with 1 ETH, max 10 ETH
156
171
  const terms = createNativeTokenStreamingTerms({
157
- initialAmount: 1000000000000000000n, // 1 ETH available immediately
158
- maxAmount: 10000000000000000000n, // 10 ETH maximum
159
- amountPerSecond: 500000000000000000n, // 0.5 ETH per second
160
- startTime: 1640995200 // Start streaming at this time
172
+ initialAmount: 1000000000000000000n, // 1 ETH available immediately
173
+ maxAmount: 10000000000000000000n, // 10 ETH maximum
174
+ amountPerSecond: 500000000000000000n, // 0.5 ETH per second
175
+ startTime: 1640995200, // Start streaming at this time
161
176
  });
162
177
  ```
163
178
 
@@ -166,6 +181,7 @@ const terms = createNativeTokenStreamingTerms({
166
181
  Creates terms for linear streaming allowance of ERC20 tokens.
167
182
 
168
183
  **Parameters:**
184
+
169
185
  - `terms: ERC20StreamingTerms`
170
186
  - `tokenAddress: string` - ERC20 token contract address
171
187
  - `initialAmount: bigint` - Amount available immediately
@@ -177,16 +193,17 @@ Creates terms for linear streaming allowance of ERC20 tokens.
177
193
  **Returns:** `Hex | Uint8Array` - 148-byte encoded terms (20 bytes + 32 bytes × 4 parameters)
178
194
 
179
195
  **Example:**
196
+
180
197
  ```typescript
181
198
  import { createERC20StreamingTerms } from '@metamask/delegation-core';
182
199
 
183
200
  // Stream USDC tokens
184
201
  const terms = createERC20StreamingTerms({
185
202
  tokenAddress: '0xA0b86a33E6441E74C65c6BF2A6d73B895B9b34A2',
186
- initialAmount: 1000000n, // 1 USDC (6 decimals)
187
- maxAmount: 10000000n, // 10 USDC maximum
188
- amountPerSecond: 100000n, // 0.1 USDC per second
189
- startTime: 1640995200
203
+ initialAmount: 1000000n, // 1 USDC (6 decimals)
204
+ maxAmount: 10000000n, // 10 USDC maximum
205
+ amountPerSecond: 100000n, // 0.1 USDC per second
206
+ startTime: 1640995200,
190
207
  });
191
208
  ```
192
209
 
@@ -195,6 +212,7 @@ const terms = createERC20StreamingTerms({
195
212
  Creates terms for an ERC20TokenPeriodTransfer caveat that validates that ERC20 token transfers do not exceed a specified amount within a given time period.
196
213
 
197
214
  **Parameters:**
215
+
198
216
  - `terms: ERC20TokenPeriodTransferTerms`
199
217
  - `tokenAddress: BytesLike` - The address of the ERC20 token.
200
218
  - `periodAmount: bigint` - The maximum amount that can be transferred within each period.
@@ -205,15 +223,16 @@ Creates terms for an ERC20TokenPeriodTransfer caveat that validates that ERC20 t
205
223
  **Returns:** `Hex | Uint8Array` - 116-byte encoded terms (20 bytes for address + 32 bytes per parameter)
206
224
 
207
225
  **Example:**
226
+
208
227
  ```typescript
209
228
  import { createERC20TokenPeriodTransferTerms } from '@metamask/delegation-core';
210
229
 
211
230
  // Allow 100 tokens per day starting from a specific date
212
231
  const terms = createERC20TokenPeriodTransferTerms({
213
232
  tokenAddress: '0xA0b86a33E6441E74C65c6BF2A6d73B895B9b34A2',
214
- periodAmount: 100n, // 100 tokens
215
- periodDuration: 86400, // 24 hours in seconds
216
- startDate: 1640995200 // 2022-01-01 00:00:00 UTC
233
+ periodAmount: 100n, // 100 tokens
234
+ periodDuration: 86400, // 24 hours in seconds
235
+ startDate: 1640995200, // 2022-01-01 00:00:00 UTC
217
236
  });
218
237
  ```
219
238
 
@@ -224,11 +243,13 @@ const terms = createERC20TokenPeriodTransferTerms({
224
243
  Encodes an array of delegations into a format suitable for on-chain submission.
225
244
 
226
245
  **Parameters:**
246
+
227
247
  - `delegations: Delegation[]` - Array of delegation objects
228
248
 
229
249
  **Returns:** Encoded delegation data
230
250
 
231
251
  **Example:**
252
+
232
253
  ```typescript
233
254
  import { encodeDelegations } from '@metamask/delegation-core';
234
255
 
@@ -239,8 +260,8 @@ const delegations = [
239
260
  authority: '0x...',
240
261
  caveats: [],
241
262
  salt: 0n,
242
- signature: '0x...'
243
- }
263
+ signature: '0x...',
264
+ },
244
265
  ];
245
266
 
246
267
  const encoded = encodeDelegations(delegations);
@@ -251,11 +272,13 @@ const encoded = encodeDelegations(delegations);
251
272
  Decodes encoded delegation data back into delegation objects.
252
273
 
253
274
  **Parameters:**
275
+
254
276
  - `data` - Encoded delegation data
255
277
 
256
278
  **Returns:** `Delegation[]` - Array of decoded delegation objects
257
279
 
258
280
  **Example:**
281
+
259
282
  ```typescript
260
283
  import { decodeDelegations } from '@metamask/delegation-core';
261
284
 
@@ -267,6 +290,7 @@ const delegations = decodeDelegations(encodedData);
267
290
  A constant representing the root authority in the delegation hierarchy.
268
291
 
269
292
  **Example:**
293
+
270
294
  ```typescript
271
295
  import { ROOT_AUTHORITY } from '@metamask/delegation-core';
272
296
 
@@ -278,11 +302,13 @@ console.log(ROOT_AUTHORITY); // Root authority identifier
278
302
  Computes a hash for a given delegation object.
279
303
 
280
304
  **Parameters:**
305
+
281
306
  - `delegation: DelegationStruct` - The delegation object to hash
282
307
 
283
308
  **Returns:** `Hex` - The hash of the delegation
284
309
 
285
310
  **Example:**
311
+
286
312
  ```typescript
287
313
  import { hashDelegation } from '@metamask/delegation-core';
288
314
 
@@ -292,7 +318,7 @@ const delegation = {
292
318
  authority: '0x...',
293
319
  caveats: [],
294
320
  salt: 0n,
295
- signature: '0x...'
321
+ signature: '0x...',
296
322
  };
297
323
 
298
324
  const hash = hashDelegation(delegation);
@@ -333,7 +359,7 @@ export type TimestampTerms = {
333
359
  };
334
360
 
335
361
  export type ExactCalldataTerms = {
336
- callData: BytesLike;
362
+ calldata: BytesLike;
337
363
  };
338
364
 
339
365
  export type NativeTokenPeriodTransferTerms = {
@@ -365,7 +391,7 @@ All caveat builders include validation and will throw descriptive errors:
365
391
  ```typescript
366
392
  try {
367
393
  const terms = createValueLteTerms({
368
- maxValue: -1n // Invalid: negative value
394
+ maxValue: -1n, // Invalid: negative value
369
395
  });
370
396
  } catch (error) {
371
397
  console.error(error.message); // "Invalid maxValue: must be greater than or equal to zero"
@@ -381,4 +407,4 @@ try {
381
407
  ## Links
382
408
 
383
409
  - [MetaMask Delegation Framework](https://github.com/MetaMask/delegation-framework)
384
- - [EIP-7715: Delegated Authorization](https://eips.ethereum.org/EIPS/eip-7715)
410
+ - [EIP-7715: Delegated Authorization](https://eips.ethereum.org/EIPS/eip-7715)
@@ -102,11 +102,11 @@ function createNativeTokenPeriodTransferTerms(terms, encodingOptions = defaultOp
102
102
 
103
103
  // src/caveats/exactCalldata.ts
104
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");
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
108
  }
109
- return prepareResult(callData, encodingOptions);
109
+ return prepareResult(calldata, encodingOptions);
110
110
  }
111
111
 
112
112
  // src/caveats/nativeTokenStreaming.ts
@@ -224,6 +224,33 @@ function createERC20TokenPeriodTransferTerms(terms, encodingOptions = defaultOpt
224
224
  return prepareResult(hexValue, encodingOptions);
225
225
  }
226
226
 
227
+ // src/caveats/nonce.ts
228
+
229
+ var MAX_NONCE_STRING_LENGTH = 66;
230
+ function createNonceTerms(terms, encodingOptions = defaultOptions) {
231
+ const { nonce } = terms;
232
+ if (nonce instanceof Uint8Array && nonce.length === 0) {
233
+ throw new Error("Invalid nonce: Uint8Array must not be empty");
234
+ }
235
+ if (typeof nonce === "string" && !nonce.startsWith("0x")) {
236
+ throw new Error("Invalid nonce: string must have 0x prefix");
237
+ }
238
+ const hexNonce = bytesLikeToHex(nonce);
239
+ if (hexNonce === "0x") {
240
+ throw new Error("Invalid nonce: must not be empty");
241
+ }
242
+ if (!_utils.isHexString.call(void 0, hexNonce)) {
243
+ throw new Error("Invalid nonce: must be a valid BytesLike value");
244
+ }
245
+ if (hexNonce.length > MAX_NONCE_STRING_LENGTH) {
246
+ throw new Error("Invalid nonce: must be 32 bytes or less in length");
247
+ }
248
+ const nonceWithoutPrefix = hexNonce.slice(2);
249
+ const paddedNonce = nonceWithoutPrefix.padStart(64, "0");
250
+ const hexValue = `0x${paddedNonce}`;
251
+ return prepareResult(hexValue, encodingOptions);
252
+ }
253
+
227
254
  // src/delegation.ts
228
255
  var _abiutils = require('@metamask/abi-utils');
229
256
 
@@ -338,5 +365,6 @@ function getCaveatHash(caveat) {
338
365
 
339
366
 
340
367
 
341
- exports.ANY_BENEFICIARY = ANY_BENEFICIARY; exports.CAVEAT_TYPEHASH = CAVEAT_TYPEHASH; exports.DELEGATION_TYPEHASH = DELEGATION_TYPEHASH; exports.ROOT_AUTHORITY = ROOT_AUTHORITY; exports.createERC20StreamingTerms = createERC20StreamingTerms; exports.createERC20TokenPeriodTransferTerms = createERC20TokenPeriodTransferTerms; exports.createExactCalldataTerms = createExactCalldataTerms; exports.createNativeTokenPeriodTransferTerms = createNativeTokenPeriodTransferTerms; exports.createNativeTokenStreamingTerms = createNativeTokenStreamingTerms; exports.createTimestampTerms = createTimestampTerms; exports.createValueLteTerms = createValueLteTerms; exports.decodeDelegations = decodeDelegations; exports.encodeDelegations = encodeDelegations; exports.hashDelegation = hashDelegation;
342
- //# sourceMappingURL=index.js.map
368
+
369
+ exports.ANY_BENEFICIARY = ANY_BENEFICIARY; exports.CAVEAT_TYPEHASH = CAVEAT_TYPEHASH; exports.DELEGATION_TYPEHASH = DELEGATION_TYPEHASH; exports.ROOT_AUTHORITY = ROOT_AUTHORITY; exports.createERC20StreamingTerms = createERC20StreamingTerms; exports.createERC20TokenPeriodTransferTerms = createERC20TokenPeriodTransferTerms; exports.createExactCalldataTerms = createExactCalldataTerms; exports.createNativeTokenPeriodTransferTerms = createNativeTokenPeriodTransferTerms; exports.createNativeTokenStreamingTerms = createNativeTokenStreamingTerms; exports.createNonceTerms = createNonceTerms; exports.createTimestampTerms = createTimestampTerms; exports.createValueLteTerms = createValueLteTerms; exports.decodeDelegations = decodeDelegations; exports.encodeDelegations = encodeDelegations; exports.hashDelegation = hashDelegation;
370
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/delegation-toolkit/delegation-toolkit/packages/delegation-core/dist/index.cjs","../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/caveats/nonce.ts","../src/delegation.ts"],"names":["bytesToHex","hexToBytes"],"mappings":"AAAA;ACAA,wCAAuD;AAyBhD,IAAM,eAAA,EAAiB,EAAE,GAAA,EAAK,MAAM,CAAA;AAQpC,SAAS,aAAA,CACd,MAAA,EACA,OAAA,EAC0B;AAC1B,EAAA,GAAA,CAAI,OAAA,CAAQ,IAAA,IAAQ,KAAA,EAAO;AACzB,IAAA,MAAM,SAAA,EAAW,OAAO,OAAA,IAAW,SAAA,EAAW,OAAA,EAAS,+BAAA,MAAiB,CAAA;AAExE,IAAA,OAAO,QAAA,CAAS,UAAA,CAAW,IAAI,EAAA,EAC1B,SAAA,EACA,CAAA,EAAA,EAAK,QAAQ,CAAA,CAAA;AACpB,EAAA;AAC2D,EAAA;AACpD,EAAA;AACT;AAOwD;AACnB,EAAA;AAC1B,IAAA;AACT,EAAA;AAC2B,EAAA;AAC7B;AAO0D;AACrB,EAAA;AACN,IAAA;AAC7B,EAAA;AACO,EAAA;AACT;AD/CgE;AACA;AEXpC;AAC1B,EAAA;AACA,EAAA;AAIY;AACoC,EAAA;AAClD;AFUgE;AACA;AGY5C;AACG,EAAA;AAEF,EAAA;AACD,IAAA;AAClB,EAAA;AAC0D,EAAA;AAEpB,EAAA;AACxC;AHZgE;AACA;AIhC1B;AAsCY;AAEc,EAAA;AAE7B,EAAA;AACrB,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAEkC,EAAA;AACtB,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAE8D,EAAA;AAClD,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAE6D,EAAA;AACjD,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAIE,EAAA;AAEU,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAEsC,EAAA;AAC7B,IAAA;AACD,IAAA;AACP,EAAA;AACsC,EAAA;AAC9B,IAAA;AACD,IAAA;AACP,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AAAA;AAEF,EAAA;AAE6B,EAAA;AACL,IAAA;AACoB,MAAA;AAC1C,IAAA;AACF,EAAA;AACsB,EAAA;AACoB,IAAA;AAC1C,EAAA;AACF;AA+BoB;AACF,EAAA;AAC0C,IAAA;AACxD,IAAA;AACE,MAAA;AACW,MAAA;AACA,MAAA;AACA,MAAA;AAC2B,MAAA;AAC3B,MAAA;AACb,IAAA;AACF,EAAA;AAC8B,EAAA;AACI,EAAA;AACpC;AAUkE;AAChC,EAAA;AACS,EAAA;AAEA,EAAA;AACf,IAAA;AACX,IAAA;AACyC,MAAA;AACtD,IAAA;AACuC,IAAA;AACT,IAAA;AAChC,EAAA;AAEwB,EAAA;AAC1B;AAOyD;AAElBC,EAAAA;AAEC,EAAA;AAEtB,EAAA;AACkB,IAAA;AACY,IAAA;AAC9C,EAAA;AAC8B,EAAA;AACvB,EAAA;AACT;AXmFgE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/delegation-toolkit/delegation-toolkit/packages/delegation-core/dist/index.cjs","sourcesContent":[null,"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 { isHexString } from '@metamask/utils';\nimport type { BytesLike } from '@metamask/utils';\n\nimport {\n bytesLikeToHex,\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\n\n// char length of 32 byte hex string (including 0x prefix)\nconst MAX_NONCE_STRING_LENGTH = 66;\n\n/**\n * Terms for configuring a Nonce caveat.\n */\nexport type NonceTerms = {\n /** The nonce as BytesLike (0x-prefixed hex string or Uint8Array) to allow bulk revocation of delegations. */\n nonce: BytesLike;\n};\n\n/**\n * Creates terms for a Nonce caveat that uses a nonce value for bulk revocation of delegations.\n *\n * @param terms - The terms for the Nonce caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 32-byte hex string.\n * @throws Error if the nonce is invalid.\n */\nexport function createNonceTerms(\n terms: NonceTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createNonceTerms(\n terms: NonceTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for a Nonce caveat that uses a nonce value for bulk revocation of delegations.\n *\n * @param terms - The terms for the Nonce caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 32-byte padded value in the specified encoding format.\n * @throws Error if the nonce is invalid or empty.\n */\nexport function createNonceTerms(\n terms: NonceTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { nonce } = terms;\n\n // Handle zero-length Uint8Array specifically\n if (nonce instanceof Uint8Array && nonce.length === 0) {\n throw new Error('Invalid nonce: Uint8Array must not be empty');\n }\n\n // Validate that strings have 0x prefix (as required by BytesLike)\n if (typeof nonce === 'string' && !nonce.startsWith('0x')) {\n throw new Error('Invalid nonce: string must have 0x prefix');\n }\n\n // Convert to hex string for consistent processing\n const hexNonce = bytesLikeToHex(nonce);\n\n // Check for empty hex string (0x) first - more specific error\n if (hexNonce === '0x') {\n throw new Error('Invalid nonce: must not be empty');\n }\n\n if (!isHexString(hexNonce)) {\n throw new Error('Invalid nonce: must be a valid BytesLike value');\n }\n\n if (hexNonce.length > MAX_NONCE_STRING_LENGTH) {\n throw new Error('Invalid nonce: must be 32 bytes or less in length');\n }\n\n // Remove '0x' prefix for padding, then add it back\n const nonceWithoutPrefix = hexNonce.slice(2);\n const paddedNonce = nonceWithoutPrefix.padStart(64, '0'); // 64 hex chars = 32 bytes\n const hexValue = `0x${paddedNonce}`;\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"]}
@@ -42,7 +42,7 @@ declare function createNativeTokenPeriodTransferTerms(terms: NativeTokenPeriodTr
42
42
  declare function createNativeTokenPeriodTransferTerms(terms: NativeTokenPeriodTransferTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
43
43
 
44
44
  type ExactCalldataTerms = {
45
- callData: BytesLike;
45
+ calldata: BytesLike;
46
46
  };
47
47
  declare function createExactCalldataTerms(terms: ExactCalldataTerms, encodingOptions?: EncodingOptions<'hex'>): Hex;
48
48
  declare function createExactCalldataTerms(terms: ExactCalldataTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
@@ -75,6 +75,12 @@ type ERC20TokenPeriodTransferTerms = {
75
75
  declare function createERC20TokenPeriodTransferTerms(terms: ERC20TokenPeriodTransferTerms, encodingOptions?: EncodingOptions<'hex'>): Hex;
76
76
  declare function createERC20TokenPeriodTransferTerms(terms: ERC20TokenPeriodTransferTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
77
77
 
78
+ type NonceTerms = {
79
+ nonce: BytesLike;
80
+ };
81
+ declare function createNonceTerms(terms: NonceTerms, encodingOptions?: EncodingOptions<'hex'>): Hex;
82
+ declare function createNonceTerms(terms: NonceTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
83
+
78
84
  declare const ANY_BENEFICIARY = "0x0000000000000000000000000000000000000a11";
79
85
  declare const ROOT_AUTHORITY = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
80
86
  declare const DELEGATION_TYPEHASH = "0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e";
@@ -86,4 +92,4 @@ declare function decodeDelegations(encoded: BytesLike, options: EncodingOptions<
86
92
  declare function hashDelegation(delegation: DelegationStruct, options?: EncodingOptions<'hex'>): Hex;
87
93
  declare function hashDelegation(delegation: DelegationStruct, options: EncodingOptions<'bytes'>): Uint8Array;
88
94
 
89
- export { ANY_BENEFICIARY, CAVEAT_TYPEHASH, CaveatStruct as Caveat, DELEGATION_TYPEHASH, DelegationStruct as Delegation, ROOT_AUTHORITY, createERC20StreamingTerms, createERC20TokenPeriodTransferTerms, createExactCalldataTerms, createNativeTokenPeriodTransferTerms, createNativeTokenStreamingTerms, createTimestampTerms, createValueLteTerms, decodeDelegations, encodeDelegations, hashDelegation };
95
+ export { ANY_BENEFICIARY, CAVEAT_TYPEHASH, type CaveatStruct as Caveat, DELEGATION_TYPEHASH, type DelegationStruct as Delegation, ROOT_AUTHORITY, createERC20StreamingTerms, createERC20TokenPeriodTransferTerms, createExactCalldataTerms, createNativeTokenPeriodTransferTerms, createNativeTokenStreamingTerms, createNonceTerms, createTimestampTerms, createValueLteTerms, decodeDelegations, encodeDelegations, hashDelegation };
package/dist/index.d.ts CHANGED
@@ -42,7 +42,7 @@ declare function createNativeTokenPeriodTransferTerms(terms: NativeTokenPeriodTr
42
42
  declare function createNativeTokenPeriodTransferTerms(terms: NativeTokenPeriodTransferTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
43
43
 
44
44
  type ExactCalldataTerms = {
45
- callData: BytesLike;
45
+ calldata: BytesLike;
46
46
  };
47
47
  declare function createExactCalldataTerms(terms: ExactCalldataTerms, encodingOptions?: EncodingOptions<'hex'>): Hex;
48
48
  declare function createExactCalldataTerms(terms: ExactCalldataTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
@@ -75,6 +75,12 @@ type ERC20TokenPeriodTransferTerms = {
75
75
  declare function createERC20TokenPeriodTransferTerms(terms: ERC20TokenPeriodTransferTerms, encodingOptions?: EncodingOptions<'hex'>): Hex;
76
76
  declare function createERC20TokenPeriodTransferTerms(terms: ERC20TokenPeriodTransferTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
77
77
 
78
+ type NonceTerms = {
79
+ nonce: BytesLike;
80
+ };
81
+ declare function createNonceTerms(terms: NonceTerms, encodingOptions?: EncodingOptions<'hex'>): Hex;
82
+ declare function createNonceTerms(terms: NonceTerms, encodingOptions: EncodingOptions<'bytes'>): Uint8Array;
83
+
78
84
  declare const ANY_BENEFICIARY = "0x0000000000000000000000000000000000000a11";
79
85
  declare const ROOT_AUTHORITY = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
80
86
  declare const DELEGATION_TYPEHASH = "0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e";
@@ -86,4 +92,4 @@ declare function decodeDelegations(encoded: BytesLike, options: EncodingOptions<
86
92
  declare function hashDelegation(delegation: DelegationStruct, options?: EncodingOptions<'hex'>): Hex;
87
93
  declare function hashDelegation(delegation: DelegationStruct, options: EncodingOptions<'bytes'>): Uint8Array;
88
94
 
89
- export { ANY_BENEFICIARY, CAVEAT_TYPEHASH, CaveatStruct as Caveat, DELEGATION_TYPEHASH, DelegationStruct as Delegation, ROOT_AUTHORITY, createERC20StreamingTerms, createERC20TokenPeriodTransferTerms, createExactCalldataTerms, createNativeTokenPeriodTransferTerms, createNativeTokenStreamingTerms, createTimestampTerms, createValueLteTerms, decodeDelegations, encodeDelegations, hashDelegation };
95
+ export { ANY_BENEFICIARY, CAVEAT_TYPEHASH, type CaveatStruct as Caveat, DELEGATION_TYPEHASH, type DelegationStruct as Delegation, ROOT_AUTHORITY, createERC20StreamingTerms, createERC20TokenPeriodTransferTerms, createExactCalldataTerms, createNativeTokenPeriodTransferTerms, createNativeTokenStreamingTerms, createNonceTerms, createTimestampTerms, createValueLteTerms, decodeDelegations, encodeDelegations, hashDelegation };
package/dist/index.mjs CHANGED
@@ -102,11 +102,11 @@ function createNativeTokenPeriodTransferTerms(terms, encodingOptions = defaultOp
102
102
 
103
103
  // src/caveats/exactCalldata.ts
104
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");
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
108
  }
109
- return prepareResult(callData, encodingOptions);
109
+ return prepareResult(calldata, encodingOptions);
110
110
  }
111
111
 
112
112
  // src/caveats/nativeTokenStreaming.ts
@@ -224,6 +224,33 @@ function createERC20TokenPeriodTransferTerms(terms, encodingOptions = defaultOpt
224
224
  return prepareResult(hexValue, encodingOptions);
225
225
  }
226
226
 
227
+ // src/caveats/nonce.ts
228
+ import { isHexString as isHexString3 } from "@metamask/utils";
229
+ var MAX_NONCE_STRING_LENGTH = 66;
230
+ function createNonceTerms(terms, encodingOptions = defaultOptions) {
231
+ const { nonce } = terms;
232
+ if (nonce instanceof Uint8Array && nonce.length === 0) {
233
+ throw new Error("Invalid nonce: Uint8Array must not be empty");
234
+ }
235
+ if (typeof nonce === "string" && !nonce.startsWith("0x")) {
236
+ throw new Error("Invalid nonce: string must have 0x prefix");
237
+ }
238
+ const hexNonce = bytesLikeToHex(nonce);
239
+ if (hexNonce === "0x") {
240
+ throw new Error("Invalid nonce: must not be empty");
241
+ }
242
+ if (!isHexString3(hexNonce)) {
243
+ throw new Error("Invalid nonce: must be a valid BytesLike value");
244
+ }
245
+ if (hexNonce.length > MAX_NONCE_STRING_LENGTH) {
246
+ throw new Error("Invalid nonce: must be 32 bytes or less in length");
247
+ }
248
+ const nonceWithoutPrefix = hexNonce.slice(2);
249
+ const paddedNonce = nonceWithoutPrefix.padStart(64, "0");
250
+ const hexValue = `0x${paddedNonce}`;
251
+ return prepareResult(hexValue, encodingOptions);
252
+ }
253
+
227
254
  // src/delegation.ts
228
255
  import { encode, encodeSingle, decodeSingle } from "@metamask/abi-utils";
229
256
  import { hexToBytes as hexToBytes2 } from "@metamask/utils";
@@ -333,6 +360,7 @@ export {
333
360
  createExactCalldataTerms,
334
361
  createNativeTokenPeriodTransferTerms,
335
362
  createNativeTokenStreamingTerms,
363
+ createNonceTerms,
336
364
  createTimestampTerms,
337
365
  createValueLteTerms,
338
366
  decodeDelegations,
@@ -1 +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;AACA,QAAM,aAAa,kBAAkB,aAAa,SAAS,WAAW,MAAM;AAC5E,SAAO;AACT;AAOO,IAAM,iBAAiB,CAAC,cAAyB;AACtD,MAAI,OAAO,cAAc,UAAU;AACjC,WAAO;AAAA,EACT;AACA,SAAO,WAAW,SAAS;AAC7B;AAOO,IAAM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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"]}
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/caveats/nonce.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 { isHexString } from '@metamask/utils';\nimport type { BytesLike } from '@metamask/utils';\n\nimport {\n bytesLikeToHex,\n defaultOptions,\n prepareResult,\n type EncodingOptions,\n type ResultValue,\n} from '../returns';\nimport type { Hex } from '../types';\n\n// char length of 32 byte hex string (including 0x prefix)\nconst MAX_NONCE_STRING_LENGTH = 66;\n\n/**\n * Terms for configuring a Nonce caveat.\n */\nexport type NonceTerms = {\n /** The nonce as BytesLike (0x-prefixed hex string or Uint8Array) to allow bulk revocation of delegations. */\n nonce: BytesLike;\n};\n\n/**\n * Creates terms for a Nonce caveat that uses a nonce value for bulk revocation of delegations.\n *\n * @param terms - The terms for the Nonce caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 32-byte hex string.\n * @throws Error if the nonce is invalid.\n */\nexport function createNonceTerms(\n terms: NonceTerms,\n encodingOptions?: EncodingOptions<'hex'>,\n): Hex;\nexport function createNonceTerms(\n terms: NonceTerms,\n encodingOptions: EncodingOptions<'bytes'>,\n): Uint8Array;\n/**\n * Creates terms for a Nonce caveat that uses a nonce value for bulk revocation of delegations.\n *\n * @param terms - The terms for the Nonce caveat.\n * @param encodingOptions - The encoding options for the result.\n * @returns The terms as a 32-byte padded value in the specified encoding format.\n * @throws Error if the nonce is invalid or empty.\n */\nexport function createNonceTerms(\n terms: NonceTerms,\n encodingOptions: EncodingOptions<ResultValue> = defaultOptions,\n): Hex | Uint8Array {\n const { nonce } = terms;\n\n // Handle zero-length Uint8Array specifically\n if (nonce instanceof Uint8Array && nonce.length === 0) {\n throw new Error('Invalid nonce: Uint8Array must not be empty');\n }\n\n // Validate that strings have 0x prefix (as required by BytesLike)\n if (typeof nonce === 'string' && !nonce.startsWith('0x')) {\n throw new Error('Invalid nonce: string must have 0x prefix');\n }\n\n // Convert to hex string for consistent processing\n const hexNonce = bytesLikeToHex(nonce);\n\n // Check for empty hex string (0x) first - more specific error\n if (hexNonce === '0x') {\n throw new Error('Invalid nonce: must not be empty');\n }\n\n if (!isHexString(hexNonce)) {\n throw new Error('Invalid nonce: must be a valid BytesLike value');\n }\n\n if (hexNonce.length > MAX_NONCE_STRING_LENGTH) {\n throw new Error('Invalid nonce: must be 32 bytes or less in length');\n }\n\n // Remove '0x' prefix for padding, then add it back\n const nonceWithoutPrefix = hexNonce.slice(2);\n const paddedNonce = nonceWithoutPrefix.padStart(64, '0'); // 64 hex chars = 32 bytes\n const hexValue = `0x${paddedNonce}`;\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;AACA,QAAM,aAAa,kBAAkB,aAAa,SAAS,WAAW,MAAM;AAC5E,SAAO;AACT;AAOO,IAAM,iBAAiB,CAAC,cAAyB;AACtD,MAAI,OAAO,cAAc,UAAU;AACjC,WAAO;AAAA,EACT;AACA,SAAO,WAAW,SAAS;AAC7B;AAOO,IAAM,mBAAmB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A,IAAI,CAAC,WACzB,gCAAgC,QAAQ,cAAc;AAAA,EACxD;AACF;AA4BO,SAAS,eACd,YACA,UAAwC,gBACtB;AAClB,QAAM,UAAU;AAAA,IACd,CAAC,WAAW,WAAW,WAAW,WAAW,WAAW,SAAS;AAAA,IACjE;AAAA,MACE;AAAA,MACA,WAAW;AAAA,MACX,WAAW;AAAA,MACX,WAAW;AAAA,MACX,oBAAoB,WAAW,OAAO;AAAA,MACtC,WAAW;AAAA,IACb;AAAA,EACF;AACA,QAAM,OAAO,UAAU,OAAO;AAC9B,SAAO,cAAc,MAAM,OAAO;AACpC;AAUA,SAAS,oBAAoB,SAAqC;AAChE,QAAM,aAAa,KAAK,QAAQ;AAChC,QAAM,UAAU,IAAI,WAAW,UAAU;AAEzC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,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","isHexString","isHexString","hexToBytes","hexToBytes"]}
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@metamask/delegation-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-rc.1",
4
4
  "description": "Low level core functionality for interacting with the Delegation Framework",
5
5
  "license": "(MIT-0 OR Apache-2.0)",
6
+ "type": "module",
6
7
  "keywords": [
7
8
  "MetaMask",
8
9
  "Ethereum"
@@ -18,7 +19,7 @@
18
19
  "author": "MetaMask <hello@metamask.io>",
19
20
  "sideEffects": false,
20
21
  "contributors": [],
21
- "main": "./dist/index.js",
22
+ "main": "./dist/index.cjs",
22
23
  "module": "./dist/index.mjs",
23
24
  "types": "./dist/index.d.ts",
24
25
  "files": [
@@ -28,11 +29,11 @@
28
29
  "exports": {
29
30
  ".": {
30
31
  "require": {
31
- "types": "./dist/index.d.ts",
32
- "default": "./dist/index.js"
32
+ "types": "./dist/index.d.cts",
33
+ "default": "./dist/index.cjs"
33
34
  },
34
35
  "import": {
35
- "types": "./dist/index.d.mts",
36
+ "types": "./dist/index.d.ts",
36
37
  "default": "./dist/index.mjs"
37
38
  }
38
39
  },
@@ -63,11 +64,11 @@
63
64
  "registry": "https://registry.npmjs.org/"
64
65
  },
65
66
  "devDependencies": {
66
- "@metamask/auto-changelog": "^3.4.4",
67
+ "@metamask/auto-changelog": "^5.0.2",
67
68
  "@types/node": "^20.10.6",
68
- "tsup": "^7.2.0",
69
+ "tsup": "^8.5.0",
69
70
  "typescript": "5.0.4",
70
- "vitest": "^2.1.9"
71
+ "vitest": "^3.2.4"
71
72
  },
72
73
  "dependencies": {
73
74
  "@metamask/abi-utils": "^3.0.0",
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
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"],"names":["TIMESTAMP_UPPER_BOUND_SECONDS","byt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X,oBAAoB,WAAW,OAAO;AAAA,MACtC,WAAW;AAAA,IACb;AAAA,EACF;AACA,QAAM,OAAO,UAAU,OAAO;AAC9B,SAAO,cAAc,MAAM,OAAO;AACpC;AAUA,SAAS,oBAAoB,SAAqC;AAChE,QAAM,aAAa,KAAK,QAAQ;AAChC,QAAM,UAAU,IAAI,WAAW,UAAU;AAEzC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,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,WAAWA,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","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"]}