github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/stdshim/coins.gno (about)

     1  package std
     2  
     3  import "strconv"
     4  
     5  // NOTE: this is selectly copied over from pkgs/std/coin.go
     6  // TODO: import all functionality(?).
     7  
     8  // Coin hold some amount of one currency.
     9  // A negative amount is invalid.
    10  type Coin struct {
    11  	Denom  string `json:"denom"`
    12  	Amount int64  `json:"amount"`
    13  }
    14  
    15  func (c Coin) String() string {
    16  	return strconv.Itoa(int(c.Amount)) + c.Denom
    17  }
    18  
    19  func (c Coin) IsGTE(other Coin) bool {
    20  	if c.Denom != other.Denom {
    21  		panic("invalid coin denominations: " + c.Denom)
    22  	}
    23  	return c.Amount >= other.Amount
    24  }
    25  
    26  // Coins is a set of Coin, one per currency
    27  type Coins []Coin
    28  
    29  func (cz Coins) String() string {
    30  	res := ""
    31  	for i, c := range cz {
    32  		if i > 0 {
    33  			res += ","
    34  		}
    35  		res += c.String()
    36  	}
    37  	return res
    38  }
    39  
    40  func (cz Coins) AmountOf(denom string) int64 {
    41  	for _, c := range cz {
    42  		if c.Denom == denom {
    43  			return c.Amount
    44  		}
    45  	}
    46  	return 0
    47  }
    48  
    49  func (a Coins) Add(b Coins) Coins {
    50  	c := Coins{}
    51  	for _, ac := range a {
    52  		bc := b.AmountOf(ac.Denom)
    53  		ac.Amount += bc
    54  		c = append(c, ac)
    55  	}
    56  	for _, bc := range b {
    57  		cc := c.AmountOf(bc.Denom)
    58  		if cc == 0 {
    59  			c = append(c, bc)
    60  		}
    61  	}
    62  	return c
    63  }
    64  
    65  // TODO implement Coin/Coins constructors.