Giter VIP home page Giter VIP logo

fvm-macro's Introduction

FVM Macros

#[derive(StateObject)]

This macro derives the StateObject trait implementation for the annotated struct. This trait handles state serde from the blockstore via load and save methods.

#[derive(Serialize_tuple, Deserialize_tuple, Clone, Debug, Default, StateObject)]
pub struct ComputeState {
    pub count: u64,
}

Generates the following:

impl StateObject for ComputeState {
  fn load() -> Self {
      // First, load the current state root.
      let root = match sdk::sself::root() {
          Ok(root) => root,
          Err(err) => abort!(USR_ILLEGAL_STATE, "failed to get root: {:?}", err),
      };

      // Load the actor state from the state tree.
      match Blockstore.get_cbor::<Self>(&root) {
          Ok(Some(state)) => state,
          Ok(None) => abort!(USR_ILLEGAL_STATE, "state does not exist"),
          Err(err) => abort!(USR_ILLEGAL_STATE, "failed to get state: {}", err),
      }
  }
  fn save(&self) -> Cid {
    let serialized = match to_vec(self) {
        Ok(s) => s,
        Err(err) => abort!(USR_SERIALIZATION, "failed to serialize state: {:?}", err),
    };
    let cid = match sdk::ipld::put(Code::Blake2b256.into(), 32, DAG_CBOR, serialized.as_slice())
    {
        Ok(cid) => cid,
        Err(err) => abort!(USR_SERIALIZATION, "failed to store initial state: {:}", err),
    };
    if let Err(err) = sdk::sself::set_root(&cid) {
        abort!(USR_ILLEGAL_STATE, "failed to set root ciid: {:}", err);
    }
    cid
  }  
}

#[fvm_actor(state=ComputeState, dispatch="method_num")]

This procedural macro derives an Actor trait implementation for the annotated implementation. The implementation is annotated so the macro can parse the public methods and autmatically create an impl with dispatch and the actor entrypoint.

#[fvm_actor(state=ComputeState, dispatch="method_num")]
impl ComputeActor {
    /// The constructor populates the initial state.
    ///
    /// Method num 1. This is part of the Filecoin calling convention.
    /// InitActor#Exec will call the constructor on method_num = 1.

    pub fn constructor(_: RawBytes, state: ComputeState) -> Option<RawBytes> {
      // This constant should be part of the SDK.
      const INIT_ACTOR_ADDR: ActorID = 1;

      // Should add SDK sugar to perform ACL checks more succinctly.
      // i.e. the equivalent of the validate_* builtin-actors runtime methods.
      // https://github.com/filecoin-project/builtin-actors/blob/master/actors/runtime/src/runtime/fvm.rs#L110-L146
      if sdk::message::caller() != INIT_ACTOR_ADDR {
          abort!(USR_FORBIDDEN, "constructor invoked by non-init actor");
      }

      state.save();
      None
    }

    pub fn say_hello(_: RawBytes, mut state: ComputeState) -> Option<RawBytes> {
      state.count += 1;
      state.save();
  
      let ret = to_vec(format!("Hello world #{}!", &state.count).as_str());
      match ret {
          Ok(ret) => Some(RawBytes::new(ret)),
          Err(err) => {
              abort!(
                  USR_ILLEGAL_STATE,
                  "failed to serialize return value: {:?}",
                  err
              );
          }
      }
    }
}

Each public method is extracted and assigned a number, because of this, the constructor needs to be the first public function in the impl.

Example code generated from the macro:

impl Actor for ComputeActor {
      fn load() -> ComputeState {
        match sdk::message::method_number() {
          1 => <ComputeState>::default(),
          _ => <ComputeState>::load()
        }
      }
      fn dispatch(id: u32) -> u32 {
        let params = sdk::message::params_raw(id).unwrap().1;
        let params = RawBytes::new(params);
        let state: ComputeState = <ComputeActor>::load();

        let ret: Option<RawBytes> = match sdk::message::method_number() {
          1 => <ComputActor>::constructor(params, state),
          2 => <ComputActor>::say_hello(params, state),
          _ => abort!(USR_UNHANDLED_MESSAGE, "unrecognized method"),
        };

        match ret {
          None => NO_DATA_BLOCK_ID,
          Some(v) => match sdk::ipld::put_block(DAG_CBOR, v.bytes()) {
              Ok(id) => id,
              Err(err) => abort!(USR_SERIALIZATION, "failed to store return value: {}", err),
          },
        }
      }
    }
  };

  #[no_mangle]
  pub fn invoke(id: u32) -> u32 {
      <ComputeActor>::dispatch(id)
  }

fvm-macro's People

Contributors

dreadful-dev avatar

Stargazers

Mike avatar raulk avatar Jim Pick avatar

Watchers

 avatar

Forkers

abu0306

fvm-macro's Issues

Control state serialization logic

There’s the idea of implementing the concept of read-only transactions, user-managed read-write transactions, and managed read-write transactions.

Read only transactions:

  • would not save state
  • read state automatically from StateObject if provided as state parameter
  • revert if state was modified?

User managed read-write:

  • would not automatically read or write
  • delegates read and write to dispatched function

Managed read-write:

  • automatically loads state
  • automatically saves state

No read:

  • does not access state

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.