How do I check if a given coin with a coin type X is in a list of allowed coin types? - Answered

Jeff on telegram:
How do I check if a given coin with a coin type X is in a list of allowed coin types?

4 Likes

Damir on Telegram:
Two ways to achieve that:

  1. Reflection: we have std::type_name module, which has 1 useful method to get a TypeName . Mixed with a sui::vec_set we get:

    struct Config has store, drop { allowed_types: VecSet<TypeName> }
    
    public fun add<T>(self: &mut Config) {
      vec_set::insert(&mut self.allowed_types,  type_name::get<T>())
    }
    
    public fun has_type<T>(self: &Config) {
      vec_set::contains(&self.allowed_types, &type_name::get<T>())
    }`
    
  2. Bag with typed keys (way more expensive as you create 2 objects to store key and value). A sui::bag can store any types in it, and when paired with a typed key, can be used for the same purpose without type reflection:

    struct Config has store { allowed_types: Bag } 
    struct TypeKey<phantom T> has copy, store, drop {}
    
    public fun add<T>(self: &mut Config) {
      bag::add(&mut self.allowed_types, TypeKey<T> {}, true)
    }
    
    public fun has_type<T>(self: &Config) {
      bag::contains(&self.allowed_types, TypeKey<T> {})
    }
    
1 Like