Move.

Beitrag

Teile dein Wissen.

BigDev.
Aug 24, 2025
Experten Q&A

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
Teilen
Kommentare
.

Antworten

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
Kommentare
.

Weißt du die Antwort?

Bitte melde dich an und teile sie.

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

242Beiträge541Antworten
Sui.X.Peera.

Verdiene deinen Anteil an 1000 Sui

Sammle Reputationspunkte und erhalte Belohnungen für deine Hilfe beim Wachstum der Sui-Community.

BelohnungskampagneAugust