github.com/cosmos/cosmos-sdk@v0.50.10/types/mapcoins.go (about)

     1  package types
     2  
     3  import "cosmossdk.io/math"
     4  
     5  // map coins is a map representation of sdk.Coins
     6  // intended solely for use in bulk additions.
     7  // All serialization and iteration should be done after conversion to sdk.Coins.
     8  type MapCoins map[string]math.Int
     9  
    10  func NewMapCoins(coins Coins) MapCoins {
    11  	m := make(MapCoins, len(coins))
    12  	m.Add(coins...)
    13  	return m
    14  }
    15  
    16  func (m MapCoins) Add(coins ...Coin) {
    17  	for _, coin := range coins {
    18  		existAmt, exists := m[coin.Denom]
    19  		// TODO: Once int supports in-place arithmetic, switch this to be in-place.
    20  		if exists {
    21  			m[coin.Denom] = existAmt.Add(coin.Amount)
    22  		} else {
    23  			m[coin.Denom] = coin.Amount
    24  		}
    25  	}
    26  }
    27  
    28  func (m MapCoins) ToCoins() Coins {
    29  	if len(m) == 0 {
    30  		return Coins{}
    31  	}
    32  	coins := make(Coins, 0, len(m))
    33  	for denom, amount := range m {
    34  		if amount.IsZero() {
    35  			continue
    36  		}
    37  		coins = append(coins, NewCoin(denom, amount))
    38  	}
    39  	if len(coins) == 0 {
    40  		return Coins{}
    41  	}
    42  	coins.Sort()
    43  	return coins
    44  }