-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathToken.go
64 lines (56 loc) · 1.62 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
60
61
62
63
64
package zksync
import (
"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"
"math/big"
)
type Token struct {
Id uint32 `json:"id"`
Address string `json:"address"`
Symbol string `json:"symbol"`
Decimals uint `json:"decimals"`
IsNft bool `json:"is_nft"`
}
func CreateETH() *Token {
return &Token{
Id: 0,
Address: common.Address{}.String(),
Symbol: `ETH`,
Decimals: 18,
}
}
func (t Token) IsETH() bool {
return t.Address == common.Address{}.String() && t.Symbol == `ETH`
}
func (t Token) GetAddress() common.Address {
return common.HexToAddress(t.Address)
}
func (t Token) ToDecimalString(amount *big.Int) string {
amountFloat := big.NewFloat(0).SetInt(amount)
if t.IsNft {
// return origin int value in "XXX.0" format
return amountFloat.Text('f', 1)
}
// convert to pointed value considering decimals scale, like wei => ETH (10^18 wei == 1 ETH)
divider := big.NewFloat(0).SetInt(big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(t.Decimals)), nil)) // = 10^decimals
res := big.NewFloat(0).SetPrec(t.Decimals*8).Quo(amountFloat, divider) // = amount / 10^decimals
if res.IsInt() {
return res.Text('f', 1) // return int value in "XXX.0" format
}
return res.Text('f', -int(t.Decimals)) // format as numeric with specified decimals limit
}
type Tokens struct {
Tokens map[string]*Token
}
func (ts *Tokens) GetToken(id string) (*Token, error) {
if t, ok := ts.Tokens[id]; ok {
return t, nil
}
// suppose id is address
for _, t := range ts.Tokens {
if t.Address == id {
return t, nil
}
}
return nil, errors.New("token not found")
}