Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cosmwasm-schema] Skip serializing Nones #2013

Open
larry0x opened this issue Jan 31, 2024 · 1 comment
Open

[cosmwasm-schema] Skip serializing Nones #2013

larry0x opened this issue Jan 31, 2024 · 1 comment

Comments

@larry0x
Copy link
Contributor

larry0x commented Jan 31, 2024

When serializing Rust types to JSON, the Nones are serialized to JSON nulls. For example:

use cosmwasm_schema::cw_serde;
use cosmwasm_std::to_json_string;

#[cw_serde]
struct MyStruct {
    pub maybe_string: Option<String>,
}

fn main() {
    let my_struct = MyStruct {
        maybe_string: None,
    };

    println!("{}", to_json_string(&my_struct).unwrap());
}
{"maybe_string":null}

This introduces some performance penalty. Since the Wasm host and the contract communicate data by loading serialized JSON strings into Wasm memory, having all the nulls means more data needs to be serialized and allocated into memory.

One way to avoid this is to use the serde_with::skip_serializing_none macro:

use cosmwasm_schema::cw_serde;
use cosmwasm_std::to_json_string;
use serde_with::skip_serializing_none;

#[skip_serializing_none]
#[cw_serde]
struct MyStruct {
    pub maybe_string: Option<String>,
}

fn main() {
    let my_struct = MyStruct {
        maybe_string: None,
    };

    println!("{}", to_json_string(&my_struct).unwrap());
}
{}

We can consider incorporating this into #[cw_serde], as well as adding it to all std library types.

Not sure how much performance penalty there is for including all the nulls or whether this improvement is worth it. Just a random thought.

@chipshort
Copy link
Collaborator

That would probably save small amounts of gas when transferring data from the contract into wasmd.
Wasmd / wasmvm charge 1 sdk gas unit per byte by default when deserializing json from the contract (can be changed by the chain, I believe).

I am a bit worried about the different ways different clients handle these things. For example a js client would then get undefined instead of null (probably not a huge problem in most cases, but could be one if it explicitly checks for === null).

I am also wondering: Does this impact the generated schema in some way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants