Peter Salomonsen
Peter Salomonsen

Reputation: 5683

How to add new properties to a NEAR Rust smart contract that already has state?

I have a Rust smart contract deployed to NEAR protocol, and now I want to update it and add properties for persistence. But the contract does already have state, and if calling the new version I get the error Cannot deserialize the contract state.

Here's the updated state struct ( where I want to add another HashMap ):

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct RepositoryPermission {
    permission: HashMap<String, HashMap<String, Permission>>,
    invitations: HashMap<InvitationId, Invitation>,  // I want to add this HashMap 
}

What is the best way to add new properties for persisting?

Upvotes: 1

Views: 171

Answers (1)

Peter Salomonsen
Peter Salomonsen

Reputation: 5683

Instead of adding the property to the original and already persisted struct, you can create a new struct

const INVITATIONS_KEY: &[u8] = b"INVITATIONS";

#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct Invitations {
    invitations: HashMap<InvitationId, Invitation>
}

and create (private) methods in the contract for deserialize / serialize this in the contract:

fn load_invitations(&self) -> Invitations {
        return env::storage_read(INVITATIONS_KEY)
                    .map(|data| Invitations::try_from_slice(&data).expect("Cannot deserialize the invitations."))
                    .unwrap_or_default();
    }

    fn save_invitations(&self, invitations: Invitations) {
        env::storage_write(INVITATIONS_KEY, &invitations.try_to_vec().expect("Cannot serialize invitations."));
    }

Upvotes: 1

Related Questions