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.

56 lines
1.8 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. USD *float64 `json:"USD" meddler:"usd"`
  20. USDUpdate *time.Time `json:"fiatUpdate" meddler:"usd_update,utctime"`
  21. }
  22. // TokenInfo provides the price of the token in USD
  23. type TokenInfo struct {
  24. TokenID uint32
  25. Value float64
  26. LastUpdated time.Time
  27. }
  28. // TokenID is the unique identifier of the token, as set in the smart contract
  29. type TokenID uint32 // current implementation supports up to 2^32 tokens
  30. // Bytes returns a byte array of length 4 representing the TokenID
  31. func (t TokenID) Bytes() []byte {
  32. var tokenIDBytes [4]byte
  33. binary.BigEndian.PutUint32(tokenIDBytes[:], uint32(t))
  34. return tokenIDBytes[:]
  35. }
  36. // BigInt returns the *big.Int representation of the TokenID
  37. func (t TokenID) BigInt() *big.Int {
  38. return big.NewInt(int64(t))
  39. }
  40. // TokenIDFromBytes returns TokenID from a byte array
  41. func TokenIDFromBytes(b []byte) (TokenID, error) {
  42. if len(b) != tokenIDBytesLen {
  43. return 0, fmt.Errorf("can not parse TokenID, bytes len %d, expected 4", len(b))
  44. }
  45. tid := binary.BigEndian.Uint32(b[:4])
  46. return TokenID(tid), nil
  47. }