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

2
Коментарі
.

Ви знаєте відповідь?

Будь ласка, увійдіть та поділіться нею.

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

242Пости541Відповіді
Sui.X.Peera.

Зароби свою частку з 1000 Sui

Заробляй бали репутації та отримуй винагороди за допомогу в розвитку спільноти Sui.

Кампанія винагородСерпень