Skip to main content

Initializers 模块

模块初始化函数 init 具有特殊性,因为它仅在以下情况下执行一次 - 当你发布相关模块时,并且必须具有以下属性:

  • 函数名称必须是 init
  • 参数列表必须以 &mut TxContext&TxContext 类型结束
  • 没有返回值
  • 私有可见性
  • 可选地,参数列表以按值接受模块的一次性见证的方式开始

例如,以下 init 函数都是有效的:

  • fun init(ctx: &TxContext)
  • fun init(ctx: &mut TxContext)
  • fun init(otw: EXAMPLE, ctx: &TxContext)
  • fun init(otw: EXAMPLE, ctx: &mut TxContext)

符合这些条件的每个函数都将在首次发布包时运行,而在其他时间(包括升级包时)都不会运行。这意味着在升级期间引入的 init 函数(对于新模块或现有模块)将永远不会运行。

以下示例演示了模块中的有效 init 函数:

module examples::one_timer {
use sui::transfer;
use sui::object::{Self, UID};
use sui::tx_context::{Self, TxContext};

/// The one of a kind - created in the module initializer.
struct CreatorCapability has key {
id: UID
}

/// This function is only called once on module publish.
/// Use it to make sure something has happened only once, like
/// here - only module author will own a version of a
/// `CreatorCapability` struct.
fun init(ctx: &mut TxContext) {
transfer::transfer(CreatorCapability {
id: object::new(ctx),
}, tx_context::sender(ctx))
}
}