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