You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Move语言中调用函数?合约函数场景实操咨询

填充后的 create_game 函数实现

下面是按照Move语言规范完成的create_game函数实现,每个TODO步骤都做了对应处理:

public entry fun create_game(
    account: &signer,
    prize_pool_amount: u64,
    player_one_address: address,
    player_two_address: address
) acquires State {
    // 检查State资源是否存在
    check_is_state_exists();

    // 验证调用者是合约部署者
    check_if_signer_is_contract_deployer(account);

    // 检查调用者拥有足够的APT
    check_if_signer_has_enough_apt_coins(account, prize_pool_amount);

    // 获取合约全局State可变引用(替换为你的合约实际地址)
    let state = borrow_global_mut<State>(@your_contract_address);
    // 获取下一个游戏ID
    let game_id = get_next_game_id(&mut state);

    // 创建新Game实例(根据你的Game结构体字段调整)
    let new_game = Game {
        id: game_id,
        player_one: player_one_address,
        player_two: player_two_address,
        prize_pool: prize_pool_amount,
        status: GameStatus::Active // 假设你定义了GameStatus枚举类型
    };

    // 将新游戏添加到State的SimpleMap存储中
    state.games.insert(game_id, new_game);

    // 转移APT到合约资源账户(替换为你的资源账户实际地址)
    Coin::transfer<APT>(account, @your_resource_account_address, prize_pool_amount);

    // 触发CreateGameEvent事件(字段需与你定义的事件结构体匹配)
    emit CreateGameEvent {
        game_id,
        creator: signer::address_of(account),
        player_one: player_one_address,
        player_two: player_two_address,
        prize_pool_amount
    };
}

关键细节说明

  • 全局State引用:borrow_global_mut<State>(@your_contract_address) 用于获取合约存储的State资源可变引用,必须替换为你的合约实际地址。
  • 辅助函数调用逻辑:
    • check_is_state_exists():若该函数需要传入State引用,可改为check_is_state_exists(&*state),内部逻辑通常是校验合约账户下是否存在State资源。
    • check_if_signer_is_contract_deployer(account):传入调用者的signer引用,内部会读取合约存储的deployer地址,与调用者地址做对比验证。
    • check_if_signer_has_enough_apt_coins(account, prize_pool_amount):内部通过Coin::balance<APT>(signer::address_of(account))获取调用者APT余额,与奖金池金额做校验。
    • get_next_game_id(&mut state):传入State可变引用,内部通常会读取当前存储的最大游戏ID,递增后更新State的对应字段并返回新ID。
  • APT转移:Coin::transfer<APT>是Move标准库的转账函数,需确保调用者已授权合约转移其APT资源(entry函数默认允许直接转移,无需额外授权)。
  • 事件触发:emit关键字用于触发事件,事件字段必须与你提前定义的CreateGameEvent结构体完全一致。

内容的提问来源于stack exchange,提问作者NickLazzari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:13:14