Publicación
Comparte tu conocimiento.
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
Respuestas
1The 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.
Sabes la respuesta?
Inicie sesión y compártalo.
Move is an executable bytecode language used to implement custom transactions and smart contracts.
Gana tu parte de 1000 Sui
Gana puntos de reputación y obtén recompensas por ayudar a crecer a la comunidad de Sui.

- ... SUIMatthardy+2095
- ... SUIacher+1666
- ... SUIjakodelarin+1092
- ... SUIChubbycheeks +1081
- ... SUITucker+1047
- ... SUIKurosakisui+1034
- ... SUIzerus+890