You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

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