0

I have a piece of code written in std, and it is bypassing/not-included in runtime as it should work but I want to use it in runtime environment, is there a way to use it. As the code written in std will not compile with native substrate no_std build.

Basically code is parsing a json and storing its key value in a StorageMap which we will get during runtime and it is a dynamic value which will change after every era.

Piece of code is as follows:

#[pallet::call]
impl<T: Config> Pallet<T> {
    #[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
    pub fn esg_score(origin: OriginFor<T>, json_data: Vec<u8>) -> DispatchResult {
        let signer = ensure_signed(origin)?;
        #[cfg(feature = "std")]
        let parseAndStoreData = |jsonStr: &str| {
            let parsed: ListOfScores = serde_json::from_str(jsonStr).unwrap()
            for item in parsed.0 {
                <GetScore::<T>>::insert(item.account.clone(), item.score);
            }
                                
            #[cfg(feature = "std")]
            parseAndStoreEsgData(&String::from_utf8_lossy(&json_data[..])[..]);         
            Self::deposit_event(Event::Stored(json_data, signer.clone()));
            Ok(())
    }
1
  • This is a bad direction, as even if you get this to work, your native and wasm runtime will produce different state root, and therefore your blockchain consensus will break. What are you trying to achieve here?
    – kianenigma
    Commented Sep 26, 2022 at 7:13

1 Answer 1

1

Check my previous answer: Compiled code withe #[cfg(feature = "std")] and facing issues while setting up staging environment


You should transform that code/lib to no_std.

For your example, String is a Vec actually. You should use the Vec<u8> directly.

If you want to play with JSON object, I think there are some crates that provide a json::from_bytes(&json_data) method.

2
  • 2
    Correct me if I'm wrong, but I believe it is generally heavily discouraged to use JSON in a substrate runtime, and one should use SCALE instead. See e.g. this answer. Commented Sep 26, 2022 at 7:38
  • Yep, thanks. But if he wants to use JSON anyway. Anyway, this is just an example. I think 'how to deal with the bytes object in Substrate' would be another question. It's a little bit off-topic.
    – AurevoirXavier
    Commented Sep 26, 2022 at 7:40

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.