-2

I am trying to use U256 in rust smart contract for near protocol with a library called ethnum. But it always give errors like:

the trait `JsonSchema` is not implemented for `U256`
 │     |
 │     = help: the following other types implement trait `JsonSchema`:
 │               &'a T
 │               &'a mut T
 │               ()
 │               (T0, T1)
 │               (T0, T1, T2)
 │               (T0, T1, T2, T3)
 │               (T0, T1, T2, T3, T4)
 │               (T0, T1, T2, T3, T4, T5)

I expect a smart contract which use U256 library to sum, change, multiply etc. so that it can be used for other smart contracts too in NEAR protocol's rust smart contract.

1 Answers1

0

The error is raised, because ethnum::U256 does not implement the schemars::JsonSchema trait. Unfortunately you can't implement JsonSchema on U256 yourself (trying to implement a foreign trait on foreign type would raise another error, namely E0117). But you can create a wrapper type around U256 (this is called the newtype pattern) and implement JsonSchema for it:

/*
[dependencies]
ethnum = { version = "1", features = ["serde"] }
schemars = "0.8"
serde = { version = "1", features = ["derive"] }
*/
use ethnum::U256 as _U256;
use schemars::{
    gen::SchemaGenerator,
    schema::{InstanceType, Schema, SchemaObject},
    schema_for, JsonSchema,
};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct U256(_U256);

impl JsonSchema for U256 {
    fn schema_name() -> String {
        "u256".to_owned()
    }

    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        let mut schema = SchemaObject {
            instance_type: Some(InstanceType::Integer.into()),
            format: Some(Self::schema_name()),
            ..Default::default()
        };
        schema.number().minimum = Some(0.0);
        schema.into()
    }
}

fn main() {
    let u256_schema = schema_for!(U256);
    println!("{u256_schema:?}");
}

Rustexplorer.

Jonas Fassbender
  • 2,371
  • 1
  • 3
  • 19
  • when i run the same code at https://remix.ethereum.org/, it also give similer error: the trait bound `ethnum::U256: Serialize` is not satisfied – Aakash Singh Rajput May 06 '23 at 15:30
  • Have you imported `ethnum` like I did? With the `serde` feature? I.e. is this how you import it in your `Cargo.toml` file: `ethnum = { version = "1", features = ["serde"] }` – Jonas Fassbender May 06 '23 at 17:59