hermez-node/common/token.go
common/token.goRaw
1package common
2
3import (
4 "encoding/binary"
5 "fmt"
6 "math/big"
7 "time"
8
9 ethCommon "github.com/ethereum/go-ethereum/common"
10)
11
12// tokenIDBytesLen defines the length of the TokenID byte array representation
13const tokenIDBytesLen = 4
14
15// Token is a struct that represents an Ethereum token that is supported in Hermez network
16type Token struct {
17 TokenID TokenID `meddler:"token_id"`
18 EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum block number in which this token was registered
19 EthAddr ethCommon.Address `meddler:"eth_addr"`
20 Name string `meddler:"name"`
21 Symbol string `meddler:"symbol"`
22 Decimals uint64 `meddler:"decimals"`
23 USD float64 `meddler:"usd,zeroisnull"`
24 USDUpdate time.Time `meddler:"usd_update,utctimez"`
25}
26
27// TokenInfo provides the price of the token in USD
28type TokenInfo struct {
29 TokenID uint32
30 Value float64
31 LastUpdated time.Time
32}
33
34// TokenID is the unique identifier of the token, as set in the smart contract
35type TokenID uint32 // current implementation supports up to 2^32 tokens
36
37// Bytes returns a byte array of length 4 representing the TokenID
38func (t TokenID) Bytes() []byte {
39 var tokenIDBytes [4]byte
40 binary.BigEndian.PutUint32(tokenIDBytes[:], uint32(t))
41 return tokenIDBytes[:]
42}
43
44// BigInt returns the *big.Int representation of the TokenID
45func (t TokenID) BigInt() *big.Int {
46 return big.NewInt(int64(t))
47}
48
49// TokenIDFromBytes returns TokenID from a byte array
50func TokenIDFromBytes(b []byte) (TokenID, error) {
51 if len(b) != tokenIDBytesLen {
52 return 0, fmt.Errorf("can not parse TokenID, bytes len %d, expected 4", len(b))
53 }
54 tid := binary.BigEndian.Uint32(b[:4])
55 return TokenID(tid), nil
56}