The Ownership Library provides a way to block anyone other than a single "owner" from calling functions. The Ownership Library is often used when needing administrative calls on a contract by a single user.
For implementation details on the Ownership Library please see the Sway Libs Docs .
In order to use the Ownership library, Sway Libs and Sway Standards must be added to the Forc.toml
file and then imported into your Sway project. To add Sway Libs as a dependency to the Forc.toml
file in your project please see the Getting Started . To add Sway Standards as a dependency please see the Sway Standards Book .
To import the Ownership Library and SRC-5 Standard to your Sway Smart Contract, add the following to your Sway file:
use sway_libs::ownership::*;
use standards::src5::*;
To implement the SRC-5 standard with the Ownership library, be sure to add the Sway Standards dependency to your contract. The following demonstrates the integration of the Ownership library with the SRC-5 standard.
use sway_libs::ownership::_owner;
use standards::src5::{SRC5, State};
impl SRC5 for Contract {
#[storage(read)]
fn owner() -> State {
_owner()
}
}
NOTE A constructor method must be implemented to initialize the owner.
Once imported, the Ownership Library's functions will be available. To use them initialize the owner for your contract by calling the initialize_ownership()
function in your own constructor method.
#[storage(read, write)]
fn my_constructor(new_owner: Identity) {
initialize_ownership(new_owner);
}
To restrict a function to only the owner, call the only_owner()
function.
#[storage(read)]
fn only_owner_may_call() {
only_owner();
// Only the contract's owner may reach this line.
}
To return the ownership state from storage, call the _owner()
function.
#[storage(read)]
fn get_owner_state() {
let owner: State = _owner();
}