Witness
Witness is a pattern that is used for confirming the ownership of a type. To do so, one passes a drop
instance of a type. Coin relies on this implementation.
/// Module that defines a generic type `Guardian<T>` which can only be
/// instantiated with a witness.
module examples::guardian {
/// Phantom parameter T can only be initialized in the `create_guardian`
/// function. But the types passed here must have `drop`.
public struct Guardian<phantom T: drop> has key, store {
id: UID
}
/// The first argument of this function is an actual instance of the
/// type T with `drop` ability. It is dropped as soon as received.
public fun create_guardian<T: drop>(
_witness: T, ctx: &mut TxContext
): Guardian<T> {
Guardian { id: object::new(ctx) }
}
}
/// Custom module that makes use of the `guardian`.
module examples::peace_guardian {
// Use the `guardian` as a dependency.
use examples::guardian;
/// This type is intended to be used only once.
public struct PEACE has drop {}
/// Module initializer is the best way to ensure that the
/// code is called only once. With `Witness` pattern it is
/// often the best practice.
fun init(ctx: &mut TxContext) {
transfer::public_transfer(
guardian::create_guardian(PEACE {}, ctx),
ctx.sender()
)
}
}
This pattern is used in these examples: