Skip to content

Commit cfa6b3a

Browse files
committed
Add encodeIntAsFixedBytes util in @cashscript/utils
1 parent b18041e commit cfa6b3a

1 file changed

Lines changed: 7 additions & 0 deletions

File tree

packages/utils/src/data.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
binToUtf8,
55
vmNumberToBigInt,
66
isVmNumberError,
7+
padMinimallyEncodedVmNumber,
78
} from '@bitauth/libauth';
89

910
export function encodeBool(bool: boolean): Uint8Array {
@@ -26,6 +27,12 @@ export function encodeInt(int: bigint): Uint8Array {
2627
return bigIntToVmNumber(int);
2728
}
2829

30+
export function encodeIntAsFixedBytes(int: bigint, byteLength: number): Uint8Array {
31+
const minimal = encodeInt(int);
32+
if (minimal.length > byteLength) throw new Error('value exceeds the requested byteLength');
33+
return padMinimallyEncodedVmNumber(minimal, byteLength);
34+
}
35+
2936
export function decodeInt(encodedInt: Uint8Array, maxLength: number = Infinity): bigint {
3037
const options = { maximumVmNumberByteLength: maxLength };
3138
const result = vmNumberToBigInt(encodedInt, options);

0 commit comments

Comments
 (0)