-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
59 lines (50 loc) · 1.28 KB
/
token.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package token
import (
"fmt"
"strings"
"regexp"
"github.com/ericlagergren/decimal"
)
const tokenDenomRegexStr = `^([[:digit:]]+(?:\.[[:digit:]]+)?|\.[[:digit:]]+)[[:space:]]*([a-zA-Z][a-zA-Z0-9/:._-]{2,127})$`
var TokenDenomRegex = regexp.MustCompile(tokenDenomRegexStr)
type Token struct {
Amount decimal.Big `json:"amount"`
Symbol string `json:"symbol"`
}
func (t *Token) String() string {
return fmt.Sprintf("%s%s", t.Amount.String(), t.Symbol)
}
func (t *Token) Rebase(exponent int, symbol string) *Token {
scale := t.Amount.Scale()
token := &Token{
Symbol: symbol,
Amount: t.Amount,
}
token.Amount.SetScale(scale + exponent)
return token
}
func ParseToken(s string) (*Token, error) {
matches := TokenDenomRegex.FindStringSubmatch(strings.TrimSpace(s))
if len(matches) != 3 {
return &Token{}, fmt.Errorf("failed to parse token")
}
token := &Token{
Symbol: matches[2],
}
_, ok := token.Amount.SetString(matches[1])
if !ok {
return token, fmt.Errorf("failed to parse token amount")
}
return token, nil
}
func ParseTokens(s string) ([]*Token, error) {
tokens := []*Token{}
for _, tokenString := range strings.Split(s, ",") {
token, err := ParseToken(tokenString)
if err != nil {
return nil, err
}
tokens = append(tokens, token)
}
return tokens, nil
}