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 `json:"id" meddler:"token_id"`
18 EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"` // Ethereum block number in which this token was registered
19 EthAddr ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
20 Name string `json:"name" meddler:"name"`
21 Symbol string `json:"symbol" meddler:"symbol"`
22 Decimals uint64 `json:"decimals" meddler:"decimals"`
23}
24
25// TokenInfo provides the price of the token in USD
26type TokenInfo struct {
27 TokenID uint32
28 Value float64
29 LastUpdated time.Time
30}
31
32// TokenID is the unique identifier of the token, as set in the smart contract
33type TokenID uint32 // current implementation supports up to 2^32 tokens
34
35// Bytes returns a byte array of length 4 representing the TokenID
36func (t TokenID) Bytes() []byte {
37 var tokenIDBytes [4]byte
38 binary.BigEndian.PutUint32(tokenIDBytes[:], uint32(t))
39 return tokenIDBytes[:]
40}
41
42// BigInt returns the *big.Int representation of the TokenID
43func (t TokenID) BigInt() *big.Int {
44 return big.NewInt(int64(t))
45}
46
47// TokenIDFromBytes returns TokenID from a byte array
48func TokenIDFromBytes(b []byte) (TokenID, error) {
49 if len(b) != tokenIDBytesLen {
50 return 0, fmt.Errorf("can not parse TokenID, bytes len %d, expected 4", len(b))
51 }
52 tid := binary.BigEndian.Uint32(b[:4])
53 return TokenID(tid), nil
54}
55
56// TokenIDFromBigInt returns a TokenID with the value of the given *big.Int
57func TokenIDFromBigInt(b *big.Int) TokenID {
58 return TokenID(b.Int64())
59}