Home

Awesome

Borsh JS

Project license Project license Discord Travis status NPM version Size on NPM

Borsh JS is an implementation of the Borsh binary serialization format for JavaScript and TypeScript projects.

Borsh stands for Binary Object Representation Serializer for Hashing. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification.

[!TIP] We strongly recommend to use borsh-js alongside the amazing project Borsher, which we plan to merge in borsh.

Examples

(De)serializing a Value

import * as borsh from 'borsh';

const encodedU16 = borsh.serialize('u16', 2);
const decodedU16 = borsh.deserialize('u16', encodedU16);

const encodedStr = borsh.serialize('string', 'testing');
const decodedStr = borsh.deserialize('string', encodedStr);

(De)serializing an Object

import * as borsh from 'borsh';

const value = {x: 255, y: BigInt(20), z: '123', arr: [1, 2, 3]};
const schema = { struct: { x: 'u8', y: 'u64', 'z': 'string', 'arr': { array: { type: 'u8' }}}};

const encoded = borsh.serialize(schema, value);
const decoded = borsh.deserialize(schema, encoded);

API

The package exposes the following functions:

Schemas

Schemas are used to describe the structure of the data being serialized or deserialized. They are used to validate the data and to determine the order of the fields in the serialized data.

You can find examples of valid in the test folder.

[!TIP] We strongly recommend to use borsh-js alongside the amazing project Borsher, which we plan to merge in borsh.

Basic Types

Basic types are described by a string. The following types are supported:

Arrays, Options, Maps, Sets, Enums, and Structs

More complex objects are described by a JSON object. The following types are supported:

Type Mappings

JavascriptBorsh
numberu8 u16 u32 i8 i16 i32
bigintu64 u128 i64 i128
numberf32 f64
numberf32 f64
booleanbool
stringUTF-8 string
type[]fixed-size byte array
type[]dynamic sized array
objectenum
MapHashMap
SetHashSet
null or typeOption

Contributing

Install dependencies:

yarn install

Continuously build with:

yarn dev

Run tests:

yarn test

Run linter

yarn lint

Publish

Prepare dist version by running:

yarn build

When publishing to npm use np.

License

This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-MIT and LICENSE-APACHE for details.