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 indicates the Ethereum block number in which this token was registered
20	EthBlockNum int64             `json:"ethereumBlockNum" meddler:"eth_block_num"`
21	EthAddr     ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
22	Name        string            `json:"name" meddler:"name"`
23	Symbol      string            `json:"symbol" meddler:"symbol"`
24	Decimals    uint64            `json:"decimals" meddler:"decimals"`
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, tracerr.Wrap(fmt.Errorf("can not parse TokenID, bytes len %d, expected 4",
53			len(b)))
54	}
55	tid := binary.BigEndian.Uint32(b[:4])
56	return TokenID(tid), nil
57}
58
59// TokenIDFromBigInt returns a TokenID with the value of the given *big.Int
60func TokenIDFromBigInt(b *big.Int) TokenID {
61	return TokenID(b.Int64())
62}