Skip to main content

见证者

见证者是一种具有 drop 的类型,证明其所有者在某个特权操作发生的时候是存在的,例如拥有一个模块的“一次性见证者”表明代码是在该模块首次发布时运行的。Coin 使用此模式确保其财政只被创建一次。

/// Module that defines a generic type `Guardian<T>` which can only be
/// instantiated with a witness.
module examples::guardian {
use sui::object::{Self, UID};
use sui::tx_context::TxContext;

/// Phantom parameter T can only be initialized in the `create_guardian`
/// function. But the types passed here must have `drop`.
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 sui::transfer;
use sui::tx_context::{Self, TxContext};

// Use the `guardian` as a dependency.
use 0x0::guardian;

/// This type is intended to be used only once.
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),
tx_context::sender(ctx)
)
}
}

这种模式在以下示例中被使用:

  • 流动性池
  • 受监管的代币