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.

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