How to serialize enum in borsh-js

Trying to serialize an object in Rust and deserialize it in JS We got 000100000031 hash, after serialization this:

pub enum Service {
    Stackoverflow,
    Twitter,
    Telegram,
}
pub struct ServiceId {
    pub service: Service,
    pub id: ExternalId,
}

When trying to deserialize in JS use this:

const Service = {
    Stackoverflow: 0,
    Twitter: 1,
    Telegram: 2
}

class ServiceId {
    constructor(service, id) {
        this.service = service
        this.id = id
    }
}
const value = new ServiceId(Service.Stackoverflow, userId)

const schema = new Map([
            [ServiceId,
                { kind: 'struct', fields: [['service', 'u8'], ['id', 'string']] }]
        ]);

After deserialization, we got this, but it is incorrect because we have an object inside an object and a redundant id parameter:

ServiceId { service: { service: undefined, id: '1' }, id: undefined }

Firstly it could be because in Rust we have enum type, so how we can use enum in borsh-js. Second if not, why do we have an incorrect results?


Solution 1:

It is hard to understand from documentation, but you need to create your class like this and all will be okay.

class ServiceId {
    constructor({ service, id }) {
        this.service = service
        this.id = id
    }
}
new ServiceId({ service: 'lol', id: 'kek' })

So you need to pass your params as object.