How to deal with Coin Fragmentation from inside contract

Hi Friends!

Suppose I have a smart-contract which at some call needs to transfer certain amount of money from my wallet.

  • do I need to pass specific coin object to such entry function, not only amount (especially if it is custom coin, not “SUI”)
  • or in other words, can smart-contract just browse my wallet and pick suitable number of coins to make the required amount (probably splitting the last of them)

Thanks in advance!


I usually pass a vector of coins, then combine into a single coin and send back any extra value to the caller:

  public  fun handle_coin_vector<X>(
      vector_x: vector<Coin<X>>,
      coin_in_value: u64,
      ctx: &mut TxContext
    ): Coin<X> {
      let coin_x = coin::zero<X>(ctx);

      if (vector::is_empty(&vector_x)){
        return coin_x

      pay::join_vec(&mut coin_x, vector_x);

      let coin_x_value = coin::value(&coin_x);
      if (coin_x_value > coin_in_value) pay::split_and_transfer(&mut coin_x, coin_x_value - coin_in_value, tx_context::sender(ctx), ctx);


Jose, Hi and thanks for suggestion!

So you mean I should anyway merge coins manually - either in the smart-contract itself or before it, by some different service or contract?

My initial idea was that there may be some magic method which can browse coins in owner’s address, but seemingly no such magic exists at this point (perhaps even not going to in future), right?

For now yes, but I think programmable transactions will enable coins to be merged or split at the TX lvl.

1 Like

Oh, wow! thanks a lot, I never know yet of this upcoming feature, sounds very curious!

This makes sense if you already know all the respective coin object IDs, but if for example i want to check the coin balance of a user’s address and that address happens to have 50 coin objects it becomes very tiring to do this on the contract level

1 Like

Yep, that’s true. Even if it is a single coin, not 50, to deal with one’s money one needs not only wallet id (and coin name), but specific id of the coin. Not very convenient in some situations.

for the sui nft market any coin birdge is good