1

I have a question regarding the frontend polkadot.js api. Suppose I have a struct

pub struct B {
    b: i32,
}
pub struct A {
    a: Vec<u8>,
    b: B,
}

I want to encode struct A into byte array and then pass it in substrate dispatch call, then I will decode it from byte array. What is the api to achieve this?

In short:

 frontend in polkadot.js api: encode structure to Vec<u8>
 backend in substrate module dispatch call: decode Vec<u8> back to struct.

I didn't find the corresponding APIs and examples on polkadot.js document. Thanks!

ohmygoddess
  • 619
  • 1
  • 7
  • 23
  • As far as i know in the backend ( substrate based node) they are considered `custom types`. When you connect to your api (in frontend) you need to pass the custom type definition so the polkadot-js knows how to decode it and encode it when you send it to the chain. look [here](https://polkadot.js.org/api/start/types.basics.html) and [here](https://polkadot.js.org/api/start/types.create.html) – woss Sep 13 '20 at 18:02
  • I know how to use the custom types. The reason I want to encode/decode by myself is because it will be tricky to paste a structure into the input of extrinsic call. So my plan is to use a helper function (in js) to encode the structure into Vec directly – ohmygoddess Sep 13 '20 at 19:29
  • hm, i think you need to serialize it, i was asking the same question wanting to save json string and then use it to build Vec an all of them ( parity guys ) were advising against. for custom things i use the JSON.stringify then `stringToU8a `helper function from the `import { stringToU8a } from '@polkadot/util'` . if i'm not mistaken if you encode that with `stringToHex` from the same package you might decode it on the backend and get the Vec since that is exactly Uin8Array in js – woss Sep 13 '20 at 19:44
  • This seems promising. If my understanding is correct: struct -> string (using JSON.stringify), string -> bytearray (using stringToU8a). To decode it, which rust library should I use? – ohmygoddess Sep 13 '20 at 21:54
  • I did some tests. I can use serde to decode it into a general map. But if want to decode as structure defined above, I have to implement deserialize trait in serde library. – ohmygoddess Sep 13 '20 at 23:29
  • 1
    hm, not sure about the serde. as far as i know it is not `no-std` compatible with wasm. i guess you can wait until guys from parity take this over or you can ask on the public matrix channel. – woss Sep 13 '20 at 23:48
  • @ohmygoddess polkadot-js has support for encoding custom structs so my recommendation would be to use that. Can you elaborate how https://polkadot.js.org/docs/api/start/types.extend#user-defined-structs does not address your usecase? – apopiak Oct 30 '20 at 10:59

0 Answers0