#casper #derive #boilerplate #contracts #type #byte #cl-typed

macro casper_types_derive

Use struct types in Casper contracts without boilerplate

1 unstable release

0.1.0 Apr 13, 2021

#17 in #casper

Download history 45/week @ 2023-11-27 26/week @ 2023-12-04 44/week @ 2023-12-11 50/week @ 2023-12-18 35/week @ 2023-12-25 13/week @ 2024-01-01 53/week @ 2024-01-08 44/week @ 2024-01-15 15/week @ 2024-01-22 13/week @ 2024-01-29 34/week @ 2024-02-05 57/week @ 2024-02-12 51/week @ 2024-02-19 72/week @ 2024-02-26 52/week @ 2024-03-04 73/week @ 2024-03-11

261 downloads per month
Used in 18 crates (5 directly)

MIT/Apache

7KB
100 lines

This crate contains three derive macros for casper_types::CLTyped, casper_types::bytesrepr::FromBytes and casper_types::bytesrepr::ToBytes.

You might want to implement these three traits for a struct you want to store in Casper storage. See storage API documentation on docs.casperlabs.io.

A macro declared on a struct like this:

use casper_types_derive::{CLTyped, ToBytes, FromBytes};

#[derive(CLTyped, ToBytes, FromBytes)]
struct Dog {
  name: String,
  likes_treat: BTreeMap<String, bool>,
}

Will expand into this:

impl CLTypes for Dog {
  fn cl_type(&self) -> CLType {
    CLType::Any
  }
}

impl FromBytes for Dog {
  fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), casper_types::bytesrepr::Error> {
    let (name, bytes) = FromBytes::from_bytes(bytes)?;
    let (likes_treat, bytes) = FromBytes::from_bytes(bytes)?;
    let value = Dog {
      name,
      likes_treat,
    };
    Ok((value, bytes))
  }
}

impl ToBytes for Dog {
  fn serialized_length(&self) -> usize {
    let mut size = 0;
    size += name.serialized_length();
    size += likes_treat.serialized_length();
    return size;
  }

  fn to_bytes(&self) -> Result<Vec<u8>, casper_types::bytesrepr::Error> {
    let mut vec = Vec::with_capacity(self.serialized_length());
    vec.append(self.name.to_bytes()?);
    vec.append(self.likes_treat.to_bytes()?);
    Ok(vec)
  }
}

Dependencies

~1.5MB
~33K SLoC