Search code examples
nearprotocol

What does the @mutateState decorator mean in a NEAR smart contract (web assembly)?


From some examples using near-sdk-as, I have seen that they use the @mutateState decorator, but I'm not sure what it does.

This is a snippet from the starter example on Learn NEAR:

  // write the given value at the given key to account (contract) storage
  @mutateState()
  write(key: string, value: string): string {
    storage.set(key, value)
    return `✅ Data saved. ( ${this.storageReport()} )`
  }

I saw from this answer on a different question that:

If the method is decorated with @mutateState then the instance is written back to storage after the method call.

But I don't know what that means. I thought storage.set(key,value) would store the data without needing to use the decorator. Any help is appreciated


Solution

  • A singleton class is special. It's a class exported by the entry file. It represents a single class that is the state of the contract. Before a method is called the class's state is loaded and is passed as this. Normally this method will run and return. However, if the state of the contract is changed or mutated, you need to add this decorator so that before the method returns the state is written back to storage.

    In Rust this is handled by the type of self. &self is immutable so you can't change the state of the contract. &mut self is mutable and this method will also be written back to storage.

    The example you posted also doesn't demonstrate this.

    
    @mutateState
    setName(name: string): void {
        this.name = name;
    }