ethers.js/lib.esm/abi/bytes32.js

40 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-11-30 23:44:23 +03:00
/**
* About bytes32 strings...
*
* @_docloc: api/utils:Bytes32 Strings
*/
2022-09-16 05:58:45 +03:00
import { getBytes, toUtf8Bytes, toUtf8String, zeroPadBytes } from "../utils/index.js";
2022-11-30 23:44:23 +03:00
/**
* Encodes %%text%% as a Bytes32 string.
*/
2022-10-01 08:34:06 +03:00
export function encodeBytes32String(text) {
2022-09-05 23:57:11 +03:00
// Get the bytes
const bytes = toUtf8Bytes(text);
// Check we have room for null-termination
if (bytes.length > 31) {
throw new Error("bytes32 string must be less than 32 bytes");
}
// Zero-pad (implicitly null-terminates)
return zeroPadBytes(bytes, 32);
}
2022-11-30 23:44:23 +03:00
/**
* Encodes the Bytes32-encoded %%bytes%% into a string.
*/
2022-10-01 08:34:06 +03:00
export function decodeBytes32String(_bytes) {
2022-09-16 05:58:45 +03:00
const data = getBytes(_bytes, "bytes");
2022-09-05 23:57:11 +03:00
// Must be 32 bytes with a null-termination
if (data.length !== 32) {
throw new Error("invalid bytes32 - not 32 bytes long");
}
if (data[31] !== 0) {
throw new Error("invalid bytes32 string - no null terminator");
}
// Find the null termination
let length = 31;
while (data[length - 1] === 0) {
length--;
}
// Determine the string value
return toUtf8String(data.slice(0, length));
}
//# sourceMappingURL=bytes32.js.map