New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@dao-xyz/borsh

Package Overview
Dependencies
Maintainers
1
Versions
51
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@dao-xyz/borsh

Binary Object Representation Serializer for Hashing

  • 2.0.5
  • npm
  • Socket score

Version published
Weekly downloads
5.5K
increased by224.93%
Maintainers
1
Weekly downloads
 
Created
Source

Borsh TS

Project license Project license NPM version Size on NPM

Borsh TS is unofficial implementation of the [Borsh] binary serialization format for TypeScript projects. The motivation behind this library is to provide more convinient methods using field and class decorators.

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.

With this imlementation on can generate serialization/deserialization Schemas using decorators.

Installation

npm install @dao-xyz/borsh

or

yarn add @dao-xyz/borsh

Serializing and deserializing

Serializing an object

SomeClass class is decorated using decorators explained later

import {
  deserialize,
  serialize,
  field,
  variant,
  vec,
} from "@dao-xyz/borsh";

class SomeClass 
{
    @field({'u8'})
    x: number

    @field({'u64'})
    y: number

    @field({'String'})
    z: string

    @field({type: vec('u32')})
    q: number[]

    constructor(data?:SomeClass)
    {
        if(data)
        {
            Object.assign(this,data)
        }
    }
}

...

const value = new SomeClass({ x: 255, y: 20, z: 'abc', q: [1, 2, 3] });

// Serialize 
const serialized = serialize(value); 

// Deserialize
const deserialized = deserialize(Buffer.from(serialized),SomeClass);

In order for 'SomeClass' be deserialized into, it has to support empty constructor, i. e.

class SomeClass
{
    constructor(data = undefined)
    {
        if(data)
        {
            ...
        }
    }
}

Examples of schema generation using decorators

For more examples, see the tests.

Enum, variant at instruction "slot" 1.

class Super {}

@variant(0)
class Enum0 extends Super {
    @field({ type: "u8" })
    public a: number;

    constructor(a: number) {
    super();
        this.a = a;
    }
}

@variant(1)
class Enum1 extends Super {
    @field({ type: "u8" })
    public b: number;

    constructor(b: number) {
    super();
        this.b = b;
    }
}

class TestStruct {
    @field({ type: Super })
    public enum: Super;

    constructor(value: Super) {
        this.enum = value;
    }
}

Nested Schema generation for structs

class InnerStruct {

    @field({ type: 'u32' })
    public b: number;

}

class TestStruct {

    @field({ type: InnerStruct })
    public a: InnerStruct;

}

Arrays

Dynamically sized

class TestStruct {
  @field({ type: vec('u8') })
  public vec: number[];
}

Fixed length

class TestStruct {
  @field({ type: fixedArray('u8', 3) }) // Fixed array of length 3
  public fixedLengthArray: number[];
}

Option

class TestStruct {
  @field({ type: option('u8') })
  public a: numberundefined;
}

Custom serialization and deserialization


interface ComplexObject {
    a: number;
    b: number;
}
class TestStruct {
    @field({
        serialize: (value: ComplexObject, writer) => {
            writer.writeU16(value.a + value.b);
        },
        deserialize: (reader): ComplexObject => {
            let value = reader.readU16();
            return {
                a: value,
                b: value * 2,
            };
        },
    })
    public obj: ComplexObject;

    constructor(obj: ComplexObject) {
        this.obj = obj;
    }
}

const serialized = serialize(new TestStruct({ a: 2, b: 3 }));
const deserialied = deserialize(
    Buffer.from(serialized),
    TestStruct
);
expect(deserialied.obj).toBeDefined();
expect(deserialied.obj.a).toEqual(5);
expect(deserialied.obj.b).toEqual(10);

Explicit serialization order of fields

class TestStruct {
    @field({ type: 'u8', index: 1 })
    public a: number;


    @field({ type: 'u8', index: 0 })
    public b: number;
}

This will make b serialized into the buffer before a.

Validation

You can validate that classes have been decorated correctly:

validate([TestStruct])

Inheritance

Schema generation with class inheritance is not supported (yet)

Type Mappings

BorshTypeScript
u8 integernumber
u16 integernumber
u32 integernumber
u64 integerBN
u128 integerBN
u256 integerBN
u512 integerBN
f32 floatN/A
f64 floatN/A
fixed-size byte arrayUint8Array
UTF-8 stringstring
optionnull or type
mapN/A
setN/A
structsany

Contributing

Install dependencies:

yarn install

Run tests:

yarn test

Run linter

yarn pretty

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.

For official releases see: [Borsh]: https://borsh.io

FAQs

Package last updated on 14 Apr 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc