4

anchor-gen is a handy crate which allows the generation of a CPI crates from only a program's Anchor IDL.

It generates all the necessary Rust structs/functions/impls to allow CPI invocation of the target program.

While trying to use it for my own IDL (minimal example pasted below) I encountered errors from Borsh, complaining about the Default trait not being implemented on [u128, 172]. This makes sense as the Default trait is only implemented on a finite set of sizes (0 to 32), which is why I had to implement the Default trait for MyStruct manually in the program crate. However the IDL does not know about that.

I tried to add that Default implementation for MyStruct in the CPI crate, but to no avail since it clashes with the auto-generated one.

Question: Is there a way to override that Default auto-gen implementation? (I will take other workarounds as well if there are)


Reference IDL:

{
  "version": "0.1.0",
  "name": "my_program",
  "instructions": [
    {
      "name": "initMyStruct",
      "accounts": [
        {
          "name": "myStruct",
          "isMut": true,
          "isSigner": false
        }
      ],
      "args": []
    }
  ],
  "accounts": [
    {
      "name": "MyStruct",
      "type": {
        "kind": "struct",
        "fields": [
          {
            "name": "isMosturized",
            "type": "bool"
          },
          {
            "name": "reservedSpace",
            "type": {
              "array": [
                "u128",
                172
              ]
            }
          }
        ]
      }
    }
  ]
}

1 Answer 1

1

You cannot override/redefine a trait but the crate could allow skipping the implementation.

Since it is reserved space and ser/deser that data does not add anything, could you simply omit the reservedSpace field in the IDL?

The only necessary consistency between how long an account data should be and its serialized byte length is that account.data.len() >= serialized_account_data

edit: It appears to be fixed by https://github.com/saber-hq/anchor-gen/pull/5

1
  • A PR is up right now to do just that (skip implementation of Default for specified structs). As pointed out anchor-gen now automatically skips implementing Default if any nested type is missing the Default impl themselves, so no need for IDL hacks (which would work as long as the omitted field is (1) not carrying data like here for reservedSpace and (2) placed last in the struct).
    – man0s
    Commented Aug 5, 2022 at 9:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.