github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/std/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  // TODO: implement Coin/Coins constructors.
     8  
     9  // Coin hold some amount of one currency.
    10  // A negative amount is invalid.
    11  type Coin struct {
    12  	Denom  string `json:"denom"`
    13  	Amount int64  `json:"amount"`
    14  }
    15  
    16  func (c Coin) String() string {
    17  	return strconv.Itoa(int(c.Amount)) + c.Denom
    18  }
    19  
    20  func (c Coin) IsGTE(other Coin) bool {
    21  	if c.Denom != other.Denom {
    22  		panic("invalid coin denominations: " + c.Denom)
    23  	}
    24  	return c.Amount >= other.Amount
    25  }
    26  
    27  // Coins is a set of Coin, one per currency
    28  type Coins []Coin
    29  
    30  func (cz Coins) String() string {
    31  	res := ""
    32  	for i, c := range cz {
    33  		if i > 0 {
    34  			res += ","
    35  		}
    36  		res += c.String()
    37  	}
    38  	return res
    39  }
    40  
    41  func (cz Coins) AmountOf(denom string) int64 {
    42  	for _, c := range cz {
    43  		if c.Denom == denom {
    44  			return c.Amount
    45  		}
    46  	}
    47  	return 0
    48  }
    49  
    50  func (a Coins) Add(b Coins) Coins {
    51  	c := Coins{}
    52  	for _, ac := range a {
    53  		bc := b.AmountOf(ac.Denom)
    54  		ac.Amount += bc
    55  		c = append(c, ac)
    56  	}
    57  	for _, bc := range b {
    58  		cc := c.AmountOf(bc.Denom)
    59  		if cc == 0 {
    60  			c = append(c, bc)
    61  		}
    62  	}
    63  	return c
    64  }
    65  
    66  // expand for usage within natively bound functions.
    67  func (cz Coins) expandNative() (denoms []string, amounts []int64) {
    68  	denoms = make([]string, len(cz))
    69  	amounts = make([]int64, len(cz))
    70  	for i, coin := range cz {
    71  		denoms[i] = coin.Denom
    72  		amounts[i] = coin.Amount
    73  	}
    74  	return denoms, amounts
    75  }