Skip to content

Add native TypeScript enum support to BorshSchema serialization #5

@r-near

Description

@r-near

Currently, when serializing TypeScript enums with Borsh, we need to manually convert enum values into an object format like { EnumValue: {} }. This isn't idiomatic TypeScript and creates unnecessary boilerplate.

Current usage:

enum Status {
  Pending,
  Fulfilled,
  Rejected
}

const status = Status.Pending;
const schema = BorshSchema.Enum({
  Pending: BorshSchema.Unit,
  Fulfilled: BorshSchema.Unit,
  Rejected: BorshSchema.Unit
});

// Need to manually convert to object format
const buffer = borshSerialize(schema, { Pending: {} });

Proposed change:

  • Add automatic conversion of TypeScript enum values during serialization
  • Allow direct serialization of enum values without manual object conversion

Desired usage:

enum Status {
  Pending,
  Fulfilled,
  Rejected
}

const status = Status.Pending;
const schema = BorshSchema.Enum({
  Pending: BorshSchema.Unit,
  Fulfilled: BorshSchema.Unit,
  Rejected: BorshSchema.Unit
});

// Just pass the enum value directly
const buffer = borshSerialize(schema, status);

Implementation requirements:

  1. Detect when a value is an enum value during serialization
  2. Convert it to the required object format internally
  3. Support both numeric and string-based enums
  4. Maintain backward compatibility with existing code

This would make the library more ergonomic for TypeScript users while maintaining the same underlying Borsh encoding format.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions