-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathnonce.ts
More file actions
75 lines (65 loc) · 2.23 KB
/
Copy pathnonce.ts
File metadata and controls
75 lines (65 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { isHexString } from '@metamask/utils';
import type { BytesLike } from '@metamask/utils';
import {
defaultOptions,
prepareResult,
type EncodingOptions,
type ResultValue,
} from '../returns';
import type { Hex } from '../types';
// char length of 32 byte hex string (including 0x prefix)
const MAX_NONCE_STRING_LENGTH = 66;
/**
* Terms for configuring a Nonce caveat.
*/
export type NonceTerms = {
/** The nonce as a hex string to allow bulk revocation of delegations. */
nonce: BytesLike;
};
/**
* Creates terms for a Nonce caveat that uses a nonce value for bulk revocation of delegations.
*
* @param terms - The terms for the Nonce caveat.
* @param encodingOptions - The encoding options for the result.
* @returns The terms as a 32-byte hex string.
* @throws Error if the nonce is invalid.
*/
export function createNonceTerms(
terms: NonceTerms,
encodingOptions?: EncodingOptions<'hex'>,
): Hex;
export function createNonceTerms(
terms: NonceTerms,
encodingOptions: EncodingOptions<'bytes'>,
): Uint8Array;
/**
* Creates terms for a Nonce caveat that uses a nonce value for bulk revocation of delegations.
*
* @param terms - The terms for the Nonce caveat.
* @param encodingOptions - The encoding options for the result.
* @returns The terms as a 32-byte hex string.
* @throws Error if the nonce is invalid.
*/
export function createNonceTerms(
terms: NonceTerms,
encodingOptions: EncodingOptions<ResultValue> = defaultOptions,
): Hex | Uint8Array {
const { nonce } = terms;
if (!nonce || nonce === '0x') {
throw new Error('Invalid nonce: must be a non-empty hex string');
}
if (typeof nonce !== 'string' || !nonce.startsWith('0x')) {
throw new Error('Invalid nonce: must be a valid hex string');
}
if (!isHexString(nonce)) {
throw new Error('Invalid nonce: must be a valid hex string');
}
if (nonce.length > MAX_NONCE_STRING_LENGTH) {
throw new Error('Invalid nonce: must be 32 bytes or less in length');
}
// Remove '0x' prefix for padding, then add it back
const nonceWithoutPrefix = nonce.slice(2);
const paddedNonce = nonceWithoutPrefix.padStart(64, '0'); // 64 hex chars = 32 bytes
const hexValue = `0x${paddedNonce}`;
return prepareResult(hexValue, encodingOptions);
}