Capability

NameCapability
OriginLibra Project / Unknown Author
ExampleSui Move by Example / Damir Shamanaev
Depends onNone
Known to work onMove

Summary

A Capability is a resource proving that the owner of the resource is permitted to execute a certain action. This is the oldest known Move design pattern dating back to the Libra project and its token smart contract, where capabilities were used to authorize minting of coins.

Examples

module examples::item {
    use sui::transfer;
    use sui::id::VersionedID;
    use sui::utf8::{Self, String};
    use sui::tx_context::{Self, TxContext};

    /// Type that marks Capability to create new `Item`s.
    struct AdminCap has key { id: VersionedID }

    /// Custom NFT-like type.
    struct Item has key, store { id: VersionedID, name: String }

    /// Module initializer is called once on module publish.
    /// Here we create only one instance of `AdminCap` and send it to the publisher.
    fun init(ctx: &mut TxContext) {
        transfer::transfer(AdminCap {
            id: tx_context::new_id(ctx)
        }, tx_context::sender(ctx))
    }

    /// The entry function can not be called if `AdminCap` is not passed as
    /// the first argument. Hence only owner of the `AdminCap` can perform
    /// this action.
    public entry fun create_and_send(
        _: &AdminCap, name: vector<u8>, to: address, ctx: &mut TxContext
    ) {
        transfer::transfer(Item {
            id: tx_context::new_id(ctx),
            name: utf8::string_unsafe(name)
        }, to)
    }
}

Example for Sui Move is taken from the book Sui Move by Example by Damir Shamanaev.