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.7 KiB

4 years ago
  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 `meddler:"token_id"`
  14. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum block number in which this token was registered
  15. EthAddr ethCommon.Address `meddler:"eth_addr"`
  16. Name string `meddler:"name"`
  17. Symbol string `meddler:"symbol"`
  18. Decimals uint64 `meddler:"decimals"`
  19. USD float64 `meddler:"usd,zeroisnull"`
  20. USDUpdate time.Time `meddler:"usd_update,utctimez"`
  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.LittleEndian.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.LittleEndian.Uint32(b[:4])
  46. return TokenID(tid), nil
  47. }