near / borsh-construct-py

Python implementation of Binary Object Representation Serializer for Hashing
https://borsh.io/
MIT License
26 stars 8 forks source link

AttributeError: 'int' object has no attribute 'index' #13

Closed daoplays closed 2 years ago

daoplays commented 2 years ago

i'm trying to implement the following rust structures in python:

pub struct BlockChoices {
    pub num_choices : u32,
    pub choices : Vec<Choice>,
    pub weights : Vec<u64>
}

pub struct ChoiceData {
    pub blocks_to_process : u32,
    pub all_choices : Vec<BlockChoices>
} 

so far i've tried the following:

from borsh_construct import Enum, I32, CStruct, U8, U32, U64, HashMap, String, Vec
choice_type = Enum(
    "A",
    "B",
    "C",
    "D",
    enum_name = "Choice"
)

BlockChoices = CStruct(
    "num_choices" / U32,
    "choices" / Vec(choice_type),
    "weights"  / Vec(U64)
)

ChoiceData = CStruct(
    "blocks_to_process" / U32,
    "all_choices" / Vec(BlockChoices)
)

example_choices = Vec(choice_type).build([choice_type.enum.A(), choice_type.enum.A(), choice_type.enum.B()])
example_n_choices = 3
example_weights = Vec(U64).build([10,1,100])

example_block_choices = BlockChoices.build({"num_choices": 3, "choices": example_choices, "weights": example_weights})

example_choice_data = ChoiceData.build({"blocks_to_process": 1, "all_choices": example_block_choices}) 

but trying to create example_choice_data yields the following error:

AttributeError: 'int' object has no attribute 'index'

the individual bits work, i.e. i can create a vector of choices, but when i try and include a vector of choices in another struct then i get an error

daoplays commented 2 years ago

Discord provided the solution, only build once!

from borsh_construct import Enum, I32, CStruct, U8, U32, U64, HashMap, String, Vec
choice_type = Enum(
    "A",
    "B",
    "C",
    "D",
    enum_name = "Choice"
)

BlockChoices = CStruct(
    "num_choices" / U32,
    "choices" / Vec(choice_type),
    "weights"  / Vec(U64)
)

ChoiceData = CStruct(
    "blocks_to_process" / U32,
    "all_choices" / Vec(BlockChoices)
)

example_choices = [choice_type.enum.A(), choice_type.enum.A(), choice_type.enum.B()]
example_n_choices = 3
example_weights = [10,1,100]

example_block_choices = [{"num_choices": 3, "choices": example_choices, "weights": example_weights}]

example_choice_data = ChoiceData.build({"blocks_to_process": 1, "all_choices": example_block_choices})