dao-xyz / borsh-ts

⚡️fast TypeScript implementation of Borsh serialization format
Apache License 2.0
37 stars 2 forks source link

expose enum variant at runtime #17

Closed vantessel closed 1 year ago

vantessel commented 1 year ago

I have an enum for which I need to get the specific variant at runtime. I added a static field to the classes with the identifier but noted it was missing after deserialization, which from the test below I guess is the expected behaviour?

https://github.com/dao-xyz/borsh-ts/blob/a91fa5ef947d9ca71d0b8ba2d87e15f9b9ffbf30/src/__tests__/index.test.ts#L152-L169

Using the enum variant would work too, however I don't see an easy way to access it without looking into the bytes manually. Is there a workaround for this or any way I can access the variant at runtime?

marcus-pousette commented 1 year ago

Try

import { getDiscriminator } from '@dao-xyz/borsh'

getDiscriminator(Clazz) 

it will yield all discriminator bytes before a class,

or even more simple, try

 import { getSchema }  from '@dao-xyz/borsh' 
 getSchema(Clazz, secondArg ).variant   // secondArg = 0, means super most class, secondArg 1, means your enum variant 

Play around with either one of those two, and see if you can get the info you are after.

Btw, if is nicer perhaps if you do

 abstract class Super {}

 const VARIANT_0 = 0
@variant(VARIANT_0)
 class Variant0 extends Super
 {
     static get variant() 
     { return  VARIANT_0 }
 }
marcus-pousette commented 1 year ago

static fields are not analyzed, so that is expected behaviour

vantessel commented 1 year ago

that worked, thank you!