Skip to main content
Cross-platform encoding and decoding utilities that work in both browsers and Node.js without relying on the Node.js Buffer class.
npm install @cosmjs/encoding

Hex

FunctionParametersReturns
toHexdata: Uint8Arraystring
fromHexhexstring: stringUint8Array
import { toHex, fromHex } from "@cosmjs/encoding";

const hex = toHex(new Uint8Array([255, 0, 128])); // "ff0080"
const bytes = fromHex("ff0080"); // Uint8Array [255, 0, 128]

Base64

FunctionParametersReturns
toBase64data: Uint8Arraystring
fromBase64base64String: stringUint8Array
import { toBase64, fromBase64 } from "@cosmjs/encoding";

const b64 = toBase64(new Uint8Array([1, 2, 3])); // "AQID"
const bytes = fromBase64("AQID"); // Uint8Array [1, 2, 3]

Bech32

FunctionParametersReturns
toBech32prefix: string, data: Uint8Array, limit?: numberstring
fromBech32address: string, limit?: number (default Infinity){ readonly prefix: string; readonly data: Uint8Array }
normalizeBech32address: stringstring
import { toBech32, fromBech32 } from "@cosmjs/encoding";

const address = toBech32("cosmos", addressBytes);
const { prefix, data } = fromBech32("cosmos1abc...");

UTF-8

FunctionParametersReturns
toUtf8str: stringUint8Array
fromUtf8data: Uint8Array, lossy?: boolean (default false)string
fromUtf8 throws on invalid UTF-8 sequences by default. Pass lossy: true to replace invalid bytes with the Unicode replacement character (U+FFFD).
import { toUtf8, fromUtf8 } from "@cosmjs/encoding";

const bytes = toUtf8("hello world");
const str = fromUtf8(bytes); // "hello world"

ASCII

FunctionParametersReturns
toAsciiinput: stringUint8Array
fromAsciidata: Uint8Arraystring
Throws if the input contains characters outside the printable ASCII range (code points below 0x20 or above 0x7E).

RFC 3339 Timestamps

FunctionParametersReturns
toRfc3339date: Date | ReadonlyDatestring
fromRfc3339str: stringDate
import { toRfc3339, fromRfc3339 } from "@cosmjs/encoding";

const timestamp = toRfc3339(new Date()); // "2024-01-15T10:30:00.000Z"
const date = fromRfc3339("2024-01-15T10:30:00.000Z");

Uint8Array Utilities

FunctionParametersReturns
fixUint8Arraysource: Uint8ArrayUint8Array
Ensures a value is a proper Uint8Array instance with a direct ArrayBuffer backing, which is necessary in some cross-environment scenarios (e.g. when Uint8Array subclass instances from protobuf libraries need normalization).