Move.

帖子

分享您的知识。

BigDev.
Aug 24, 2025
专家问答

Generic Types in Move for Reusability

Move’s generics enable reusable, type-safe code, critical for DeFi protocols handling multiple token types. Intermediate developers must apply constraints like key and store to ensure compatibility with Sui’s object model. Why are generics useful in Move for building reusable DeFi modules? Write a generic Move module for a vault that can store and withdraw any coin type. What constraints ensure the module works with Sui’s coin system?

module vault::generic_vault {
    use sui::object::{Self, UID};
    use sui::coin::{Self, Coin};
    use sui::balance::{Self, Balance};
    use sui::tx_context::{Self, TxContext};
    use sui::transfer;

    struct Vault has key {
        id: UID,
        balance: Balance,
    }

    // Create vault for any coin type
    public entry fun create_vault(ctx: &mut TxContext) {
        let vault = Vault {
            id: object::new(ctx),
            balance: balance::zero(),
        };
        transfer::share_object(vault);
    }

    // Deposit coins into vault
    public entry fun deposit(vault: &mut Vault, coin: Coin) {
        coin::put(&mut vault.balance, coin);
    }

    // Withdraw coins (simplified to sender)
    public entry fun withdraw(
        vault: &mut Vault,
        amount: u64,
        ctx: &mut TxContext
    ) {
        let coin = coin::take(&mut vault.balance, amount, ctx);
        transfer::public_transfer(coin, tx_context::sender(ctx));
    }
}
  • Move
5
1
分享
评论
.

答案

1
jakodelarin.
Aug 24 2025, 20:17

The Vault struct is generic over type T with key + store constraints, ensuring T is a valid Sui object (e.g., a coin) that can be stored and transferred. The create_vault function initializes a shared vault with an empty balance. The deposit function merges a Coin into the vault’s Balance using coin::put, while withdraw extracts a specified amount and transfers it to the sender. Generics allow this module to work with any coin type (e.g., SUI, custom tokens) without duplicating code. The key + store constraints ensure compatibility with Sui’s coin system, which requires these abilities for storage and transfer.

3
评论
.

你知道答案吗?

请登录并分享。

Move is an executable bytecode language used to implement custom transactions and smart contracts.

242帖子541答案
Sui.X.Peera.

赚取你的 1000 Sui 份额

获取声誉积分,并因帮助 Sui 社区成长而获得奖励。

奖励活动八月