Contract Ownership

The following example implements access control to restrict functionality to a privileged user.

ABI

The interface contains a function to set the owner and a function that only the owner can use.

abi Ownership { #[storage(read, write)] fn set_owner(owner: Option<Identity>); #[storage(read)] fn action(); }

Identity

We must keep track of the owner in storage and compare them against the caller via msg_sender().

Initially there is no owner so we'll set them to None.

storage { owner: Option<Identity> = None, }

Implementation

To set the owner one of two conditions must be met:

  • There is no owner
  • The current owner is calling the function

To call our action() function the caller must be the owner of the contract.

impl Ownership for Contract { #[storage(read, write)] fn set_owner(owner: Option<Identity>) { assert(storage.owner.read().is_none() || storage.owner.read().unwrap() == msg_sender().unwrap()); storage.owner.write(owner); } #[storage(read)] fn action() { assert(storage.owner.read().unwrap() == msg_sender().unwrap()); // code } }