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